From 3da4ae9c1967442b015ce9740e3d46d32fcd4d26 Mon Sep 17 00:00:00 2001 From: Pamela Dragosh Date: Thu, 6 Sep 2018 20:17:27 -0400 Subject: Fix checkstyle policy-core Working on the policy-core submodule in drools pdp. Issue-ID: POLICY-882 Change-Id: I58d418110fe0fda90f97117ef17edfc13d648ccc Signed-off-by: Pamela Dragosh --- .../onap/policy/drools/core/PolicyContainer.java | 56 +- .../org/onap/policy/drools/core/PolicySession.java | 54 +- .../drools/core/PolicySessionFeatureAPI.java | 129 +++-- .../org/onap/policy/drools/core/jmx/PdpJmx.java | 42 +- .../policy/drools/core/jmx/PdpJmxListener.java | 63 ++- .../onap/policy/drools/core/jmx/PdpJmxMBean.java | 7 +- .../org/onap/policy/drools/core/lock/Lock.java | 8 +- .../core/lock/PolicyResourceLockFeatureAPI.java | 41 +- .../core/lock/PolicyResourceLockManager.java | 18 +- .../policy/drools/core/lock/SimpleLockManager.java | 89 +-- .../policy/drools/util/FeatureEnabledChecker.java | 2 +- .../java/org/onap/policy/drools/util/KieUtils.java | 28 +- .../policy/drools/core/DroolsContainerTest.java | 610 ++++++++++----------- .../drools/core/PolicySessionFeatureApiTest.java | 137 +++++ .../drools/core/TestPolicySessionFeatureAPI.java | 157 ------ .../org/onap/policy/drools/core/lock/LockTest.java | 5 +- .../lock/PolicyResourceLockFeatureAPITest.java | 4 + .../core/lock/PolicyResourceLockManagerTest.java | 8 +- .../drools/core/lock/SimpleLockManagerTest.java | 59 +- .../onap/policy/drools/core/lock/TestUtils.java | 55 -- .../onap/policy/drools/core/lock/TestingUtils.java | 55 ++ .../drools/util/FeatureEnabledCheckerTest.java | 1 + ...onap.policy.drools.core.PolicySessionFeatureAPI | 2 +- 23 files changed, 823 insertions(+), 807 deletions(-) create mode 100644 policy-core/src/test/java/org/onap/policy/drools/core/PolicySessionFeatureApiTest.java delete mode 100644 policy-core/src/test/java/org/onap/policy/drools/core/TestPolicySessionFeatureAPI.java delete mode 100644 policy-core/src/test/java/org/onap/policy/drools/core/lock/TestUtils.java create mode 100644 policy-core/src/test/java/org/onap/policy/drools/core/lock/TestingUtils.java diff --git a/policy-core/src/main/java/org/onap/policy/drools/core/PolicyContainer.java b/policy-core/src/main/java/org/onap/policy/drools/core/PolicyContainer.java index 8a86a5c5..f2a084e4 100644 --- a/policy-core/src/main/java/org/onap/policy/drools/core/PolicyContainer.java +++ b/policy-core/src/main/java/org/onap/policy/drools/core/PolicyContainer.java @@ -79,7 +79,7 @@ public class PolicyContainer implements Startable { * dependencies from the Maven repository to create the 'PolicyContainer' and associated * 'KieContainer'. * - * An exception occurs if the creation of the 'KieContainer' fails. + *

An exception occurs if the creation of the 'KieContainer' fails. * * @param groupId the 'groupId' associated with the artifact * @param artifactId the artifact name @@ -94,7 +94,7 @@ public class PolicyContainer implements Startable { * associated artifact and remaining dependencies from the Maven repository to create the * 'PolicyContainer' and associated 'KieContainer'. * - * An exception occurs if the creation of the 'KieContainer' fails. + *

An exception occurs if the creation of the 'KieContainer' fails. * * @param releaseId indicates the artifact that is to be installed in this container */ @@ -109,7 +109,7 @@ public class PolicyContainer implements Startable { } synchronized (containers) { if (newReleaseId != null) { - logger.info("Add a new kieContainer in containers: releaseId: " + newReleaseId.toString()); + logger.info("Add a new kieContainer in containers: releaseId: {}", newReleaseId.toString()); } else { logger.warn("input releaseId is null"); } @@ -133,7 +133,7 @@ public class PolicyContainer implements Startable { private ReleaseId loadArtifact(String groupId, String artifactId, String version) { String[] versions = version.split(","); if (versions.length > 1) { - logger.info("Multiple KieContainer versions are specified: " + version); + logger.info("Multiple KieContainer versions are specified: {}", version); } // indicates a 'newKieContainer' call failed @@ -147,7 +147,7 @@ public class PolicyContainer implements Startable { try { // Create a 'ReleaseId' object describing the artifact, and // create a 'KieContainer' based upon it. - logger.info("Create new KieContainer start, version = " + ver + " ..."); + logger.info("Create new KieContainer start, version = {} ...", ver); releaseId = kieServices.newReleaseId(groupId, artifactId, ver); kieContainer = kieServices.newKieContainer(releaseId); @@ -168,6 +168,8 @@ public class PolicyContainer implements Startable { } /** + * Get name. + * * @return the name of the container, which is the String equivalent of the 'ReleaseId'. It has * the form: * @@ -181,6 +183,8 @@ public class PolicyContainer implements Startable { } /** + * Get kie container. + * * @return the associated 'KieContainer' instance */ public KieContainer getKieContainer() { @@ -188,6 +192,8 @@ public class PolicyContainer implements Startable { } /** + * Get class loader. + * * @return the 'ClassLoader' associated with the 'KieContainer' instance */ public ClassLoader getClassLoader() { @@ -195,6 +201,8 @@ public class PolicyContainer implements Startable { } /** + * Get group Id. + * * @return the Maven GroupId of the top-level artifact wrapped by the container. */ public String getGroupId() { @@ -202,6 +210,8 @@ public class PolicyContainer implements Startable { } /** + * Get artifact id. + * * @return the Maven ArtifactId of the top-level artifact wrapped by the container. */ public String getArtifactId() { @@ -209,6 +219,8 @@ public class PolicyContainer implements Startable { } /** + * Get version. + * * @return the version of the top-level artifact wrapped by the container (this may change as * updates occur) */ @@ -236,10 +248,10 @@ public class PolicyContainer implements Startable { */ private PolicySession activatePolicySession(String name, String kieBaseName) { synchronized (sessions) { - logger.info("activatePolicySession:name :" + name); + logger.info("activatePolicySession:name :{}", name); PolicySession session = sessions.get(name); if (session != null) { - logger.info("activatePolicySession:session - " + session.getFullName() + " is returned."); + logger.info("activatePolicySession:session - {} is returned.", session.getFullName()); return session; } KieSession kieSession = null; @@ -275,7 +287,7 @@ public class PolicyContainer implements Startable { logger.error(ERROR_STRING + feature.getClass().getName(), e); } } - logger.info("activatePolicySession:new session was added in sessions with name " + name); + logger.info("activatePolicySession:new session was added in sessions with name {}", name); } logger.info("activatePolicySession:session - " + (session == null ? "null" : session.getFullName()) + " is returned."); @@ -310,15 +322,15 @@ public class PolicyContainer implements Startable { // fetch KieBase, and verify it belongs to this KieContainer boolean match = false; KieBase kieBase = kieSession.getKieBase(); - logger.info("adoptKieSession:kieBase: " + kieBase); + logger.info("adoptKieSession:kieBase: {}", kieBase); for (String kieBaseName : kieContainer.getKieBaseNames()) { - logger.info("adoptKieSession:kieBaseName: " + kieBaseName); + logger.info("adoptKieSession:kieBaseName: {}", kieBaseName); if (kieBase == kieContainer.getKieBase(kieBaseName)) { match = true; break; } } - logger.info("adoptKieSession:match " + match); + logger.info("adoptKieSession:match {}", match); // if we don't have a match yet, the last chance is to look at the // default KieBase, if it exists if (!match && kieBase != kieContainer.getKieBase()) { @@ -333,7 +345,7 @@ public class PolicyContainer implements Startable { // create the new 'PolicySession', add it to the table, // and return the object to the caller - logger.info("adoptKieSession:create a new policySession with name " + name); + logger.info("adoptKieSession:create a new policySession with name {}", name); PolicySession policySession = new PolicySession(name, this, kieSession); sessions.put(name, policySession); @@ -378,7 +390,7 @@ public class PolicyContainer implements Startable { if (releaseId == null) { logger.warn("updateToVersion:input releaseId is null"); } else { - logger.info("updateToVersion:releaseId " + releaseId.toString()); + logger.info("updateToVersion:releaseId {}", releaseId); } // stop all session threads @@ -399,6 +411,8 @@ public class PolicyContainer implements Startable { } /** + * Get policy containers. + * * @return all existing 'PolicyContainer' instances */ public static Collection getPolicyContainers() { @@ -408,6 +422,8 @@ public class PolicyContainer implements Startable { } /** + * Get policy sessions. + * * @return all of the 'PolicySession' instances */ public Collection getPolicySessions() { @@ -454,7 +470,7 @@ public class PolicyContainer implements Startable { } /** - * Insert a fact into a specific named session + * Insert a fact into a specific named session. * * @param name this is the session name * @param object this is the fact to be inserted into the session @@ -475,7 +491,7 @@ public class PolicyContainer implements Startable { } /** - * Insert a fact into all sessions associated with this container + * Insert a fact into all sessions associated with this container. * * @param object this is the fact to be inserted into the sessions * @return 'true' if the fact was inserted into at least one session, 'false' if not @@ -660,15 +676,15 @@ public class PolicyContainer implements Startable { /** * This method does the following: * - * 1) Initializes logging 2) Starts the DroolsPDP Integrity Monitor 3) Initilaizes persistence + *

1) Initializes logging 2) Starts the DroolsPDP Integrity Monitor 3) Initilaizes persistence * - * It no longer reads in properties files, o creates 'PolicyContainer' instances. + *

It no longer reads in properties files, o creates 'PolicyContainer' instances. * * @param args standard 'main' arguments, which are currently ignored */ public static void globalInit(String[] args) { String configDir = "config"; - logger.info("PolicyContainer.main: configDir=" + configDir); + logger.info("PolicyContainer.main: configDir={}", configDir); // invoke 'globalInit' on all of the features for (PolicySessionFeatureAPI feature : PolicySessionFeatureAPI.impl.getList()) { @@ -681,7 +697,7 @@ public class PolicyContainer implements Startable { } /** - * Fetch the adjunct object associated with a given feature + * Fetch the adjunct object associated with a given feature. * * @param object this is typically the singleton feature object that is used as a key, but it * might also be useful to use nested objects within the feature as keys. @@ -692,7 +708,7 @@ public class PolicyContainer implements Startable { } /** - * Store the adjunct object associated with a given feature + * Store the adjunct object associated with a given feature. * * @param object this is typically the singleton feature object that is used as a key, but it * might also be useful to use nested objects within the feature as keys. diff --git a/policy-core/src/main/java/org/onap/policy/drools/core/PolicySession.java b/policy-core/src/main/java/org/onap/policy/drools/core/PolicySession.java index 7646225e..bb2148c0 100644 --- a/policy-core/src/main/java/org/onap/policy/drools/core/PolicySession.java +++ b/policy-core/src/main/java/org/onap/policy/drools/core/PolicySession.java @@ -44,8 +44,8 @@ import org.slf4j.LoggerFactory; /** * This class is a wrapper around 'KieSession', which adds the following: - *

- * 1) A thread running 'KieSession.fireUntilHalt()' + * + *

1) A thread running 'KieSession.fireUntilHalt()' * 2) Access to UEB * 3) Logging of events */ @@ -75,7 +75,7 @@ public class PolicySession new ThreadLocal<>(); /** - * Internal constructor - create a 'PolicySession' instance + * Internal constructor - create a 'PolicySession' instance. * * @param name the name of this 'PolicySession' (and 'kieSession') * @param container the 'PolicyContainer' instance containing this session @@ -91,6 +91,8 @@ public class PolicySession } /** + * Get policy container. + * * @return the 'PolicyContainer' object containing this session */ public PolicyContainer getPolicyContainer() { @@ -98,6 +100,8 @@ public class PolicySession } /** + * Get Kie Session. + * * @return the associated 'KieSession' instance */ public KieSession getKieSession() { @@ -105,17 +109,21 @@ public class PolicySession } /** + * Get name. + * * @return the local name of this session, which should either match the - * name specified in 'kmodule.xml' file associated with this session, or the - * name passed on the 'PolicyContainer.adoptKieSession' method. + * name specified in 'kmodule.xml' file associated with this session, or the + * name passed on the 'PolicyContainer.adoptKieSession' method. */ public String getName() { return name; } /** + * Get full name. + * * @return the 'PolicyContainer' name, followed by ':', followed by the - * local name of the session. It should be useful in log messages. + * local name of the session. It should be useful in log messages. */ public String getFullName() { return container.getName() + ":" + name; @@ -137,8 +145,9 @@ public class PolicySession for (PolicySessionFeatureAPI feature : PolicySessionFeatureAPI.impl.getList()) { try { - if ((threadModel = feature.selectThreadModel(this)) != null) + if ((threadModel = feature.selectThreadModel(this)) != null) { break; + } } catch (Exception e) { logger.error("ERROR: Feature API: " + feature.getClass().getName(), e); @@ -164,7 +173,7 @@ public class PolicySession } /** - * Notification that 'updateToVersion' was called on the container + * Notification that 'updateToVersion' was called on the container. */ void updated() { if (threadModel != null) { @@ -183,29 +192,31 @@ public class PolicySession } /** + * Get current session. + * * @return the 'PolicySession' instance associated with the current thread - * (Note that this only works if the current thread is the one running - * 'kieSession.fireUntilHalt()'.) + * (Note that this only works if the current thread is the one running + * 'kieSession.fireUntilHalt()'.) */ public static PolicySession getCurrentSession() { return policySess.get(); } /** - * Fetch the adjunct object associated with a given feature + * Fetch the adjunct object associated with a given feature. * * @param object this is typically the singleton feature object that is * used as a key, but it might also be useful to use nested objects * within the feature as keys. * @return a feature-specific object associated with the key, or 'null' - * if it is not found. + * if it is not found. */ public Object getAdjunct(Object object) { return adjuncts.get(object); } /** - * Store the adjunct object associated with a given feature + * Store the adjunct object associated with a given feature. * * @param object this is typically the singleton feature object that is * used as a key, but it might also be useful to use nested objects @@ -253,8 +264,7 @@ public class PolicySession * {@inheritDoc} */ @Override - public void afterRuleFlowGroupDeactivated - (RuleFlowGroupDeactivatedEvent event) { + public void afterRuleFlowGroupDeactivated(RuleFlowGroupDeactivatedEvent event) { if (logger.isDebugEnabled()) { logger.debug("afterRuleFlowGroupDeactivated: " + getFullName() + ": AgendaEventListener.afterRuleFlowGroupDeactivated(" @@ -302,8 +312,7 @@ public class PolicySession * {@inheritDoc} */ @Override - public void beforeRuleFlowGroupActivated - (RuleFlowGroupActivatedEvent event) { + public void beforeRuleFlowGroupActivated(RuleFlowGroupActivatedEvent event) { if (logger.isDebugEnabled()) { logger.debug("beforeRuleFlowGroupActivated: " + getFullName() + ": AgendaEventListener.beforeRuleFlowGroupActivated(" @@ -315,8 +324,7 @@ public class PolicySession * {@inheritDoc} */ @Override - public void beforeRuleFlowGroupDeactivated - (RuleFlowGroupDeactivatedEvent event) { + public void beforeRuleFlowGroupDeactivated(RuleFlowGroupDeactivatedEvent event) { if (logger.isDebugEnabled()) { logger.debug("beforeRuleFlowGroupDeactivated: " + getFullName() + ": AgendaEventListener.beforeRuleFlowGroupDeactivated(" @@ -391,12 +399,12 @@ public class PolicySession */ public interface ThreadModel { /** - * Start the thread or threads that do the 'KieSession' processing + * Start the thread or threads that do the 'KieSession' processing. */ public void start(); /** - * Stop the thread or threads that do the 'KieSession' processing + * Stop the thread or threads that do the 'KieSession' processing. */ public void stop(); @@ -425,7 +433,7 @@ public class PolicySession volatile boolean repeat = true; /** - * Constructor - initialize 'session' and create thread + * Constructor - initialize 'session' and create thread. * * @param session the 'PolicySession' instance */ @@ -435,6 +443,8 @@ public class PolicySession } /** + * Get thread name. + * * @return the String to use as the thread name */ private String getThreadName() { diff --git a/policy-core/src/main/java/org/onap/policy/drools/core/PolicySessionFeatureAPI.java b/policy-core/src/main/java/org/onap/policy/drools/core/PolicySessionFeatureAPI.java index 867325cd..3e49ee5b 100644 --- a/policy-core/src/main/java/org/onap/policy/drools/core/PolicySessionFeatureAPI.java +++ b/policy-core/src/main/java/org/onap/policy/drools/core/PolicySessionFeatureAPI.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * policy-core * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 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. @@ -32,76 +32,71 @@ import org.onap.policy.drools.utils.OrderedServiceImpl; * return a 'void' value. In other cases, such as 'activatePolicySession', * may */ -public interface PolicySessionFeatureAPI extends OrderedService -{ - /** - * 'FeatureAPI.impl.getList()' returns an ordered list of objects - * implementing the 'FeatureAPI' interface. - */ - public static OrderedServiceImpl impl = - new OrderedServiceImpl<>(PolicySessionFeatureAPI.class); +public interface PolicySessionFeatureAPI extends OrderedService { + /** + * 'FeatureAPI.impl.getList()' returns an ordered list of objects + * implementing the 'FeatureAPI' interface. + */ + public static OrderedServiceImpl impl = + new OrderedServiceImpl<>(PolicySessionFeatureAPI.class); - /** - * This method is called during initialization at a point right after - * 'PolicyContainer' initialization has completed. - * - * @param args standard 'main' arguments, which are currently ignored - * @param configDir the relative directory containing configuration files - */ - public default void globalInit(String[] args, String configDir) {} + /** + * This method is called during initialization at a point right after + * 'PolicyContainer' initialization has completed. + * + * @param args standard 'main' arguments, which are currently ignored + * @param configDir the relative directory containing configuration files + */ + public default void globalInit(String[] args, String configDir) {} - /** - * This method is used to create a 'KieSession' as part of a - * 'PolicyContainer'. The caller of this method will iterate over the - * implementers of this interface until one returns a non-null value. - * - * @param policyContainer the 'PolicyContainer' instance containing this - * session - * @param name the name of the KieSession (which is also the name of - * the associated PolicySession) - * @param kieBaseName the name of the 'KieBase' instance containing - * this session - * @return a new KieSession, if one was created, or 'null' if not - * (this depends on the capabilities and state of the object implementing - * this interface) - */ - public default KieSession activatePolicySession - (PolicyContainer policyContainer, String name, String kieBaseName) - { - return null; - } + /** + * This method is used to create a 'KieSession' as part of a + * 'PolicyContainer'. The caller of this method will iterate over the + * implementers of this interface until one returns a non-null value. + * + * @param policyContainer the 'PolicyContainer' instance containing this + * session + * @param name the name of the KieSession (which is also the name of + * the associated PolicySession) + * @param kieBaseName the name of the 'KieBase' instance containing + * this session + * @return a new KieSession, if one was created, or 'null' if not + * (this depends on the capabilities and state of the object implementing + * this interface) + */ + public default KieSession activatePolicySession(PolicyContainer policyContainer, String name, String kieBaseName) { + return null; + } - /** - * This method is called after a new 'PolicySession' has been initialized, - * and linked to the 'PolicyContainer'. - * - * @param policySession the new 'PolicySession' instance - */ - public default void newPolicySession(PolicySession policySession) {} + /** + * This method is called after a new 'PolicySession' has been initialized, + * and linked to the 'PolicyContainer'. + * + * @param policySession the new 'PolicySession' instance + */ + public default void newPolicySession(PolicySession policySession) {} - /** - * This method is called to select the 'ThreadModel' instance associated - * with a 'PolicySession' instance. - */ - public default PolicySession.ThreadModel selectThreadModel - (PolicySession session) - { - return null; - } + /** + * This method is called to select the 'ThreadModel' instance associated + * with a 'PolicySession' instance. + */ + public default PolicySession.ThreadModel selectThreadModel(PolicySession session) { + return null; + } - /** - * This method is called after 'KieSession.dispose()' is called - * - * @param policySession the 'PolicySession' object that wrapped the - * 'KieSession' - */ - public default void disposeKieSession(PolicySession policySession) {} + /** + * This method is called after 'KieSession.dispose()' is called. + * + * @param policySession the 'PolicySession' object that wrapped the + * 'KieSession' + */ + public default void disposeKieSession(PolicySession policySession) {} - /** - * This method is called after 'KieSession.destroy()' is called - * - * @param policySession the 'PolicySession' object that wrapped the - * 'KieSession' - */ - public default void destroyKieSession(PolicySession policySession) {} + /** + * This method is called after 'KieSession.destroy()' is called. + * + * @param policySession the 'PolicySession' object that wrapped the + * 'KieSession' + */ + public default void destroyKieSession(PolicySession policySession) {} } diff --git a/policy-core/src/main/java/org/onap/policy/drools/core/jmx/PdpJmx.java b/policy-core/src/main/java/org/onap/policy/drools/core/jmx/PdpJmx.java index 19f6afb4..e1a89752 100644 --- a/policy-core/src/main/java/org/onap/policy/drools/core/jmx/PdpJmx.java +++ b/policy-core/src/main/java/org/onap/policy/drools/core/jmx/PdpJmx.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * policy-core * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 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. @@ -24,29 +24,29 @@ import java.util.concurrent.atomic.AtomicLong; public class PdpJmx implements PdpJmxMBean { - private static PdpJmx instance = new PdpJmx(); - private final AtomicLong updates = new AtomicLong(); - private final AtomicLong actions = new AtomicLong(); + private static PdpJmx instance = new PdpJmx(); + private final AtomicLong updates = new AtomicLong(); + private final AtomicLong actions = new AtomicLong(); - public static PdpJmx getInstance() { - return instance; - } + public static PdpJmx getInstance() { + return instance; + } - @Override - public long getUpdates(){ - return updates.longValue(); - } + @Override + public long getUpdates() { + return updates.longValue(); + } - @Override - public long getRulesFired(){ - return actions.longValue(); - } + @Override + public long getRulesFired() { + return actions.longValue(); + } - public void updateOccured(){ - updates.incrementAndGet(); - } + public void updateOccured() { + updates.incrementAndGet(); + } - public void ruleFired(){ - actions.incrementAndGet(); - } + public void ruleFired() { + actions.incrementAndGet(); + } } diff --git a/policy-core/src/main/java/org/onap/policy/drools/core/jmx/PdpJmxListener.java b/policy-core/src/main/java/org/onap/policy/drools/core/jmx/PdpJmxListener.java index 9136defb..04f0dfd0 100644 --- a/policy-core/src/main/java/org/onap/policy/drools/core/jmx/PdpJmxListener.java +++ b/policy-core/src/main/java/org/onap/policy/drools/core/jmx/PdpJmxListener.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * policy-core * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 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. @@ -35,36 +35,41 @@ import org.slf4j.LoggerFactory; public class PdpJmxListener { - public static final Logger logger = LoggerFactory.getLogger(PdpJmxListener.class); + public static final Logger logger = LoggerFactory.getLogger(PdpJmxListener.class); - private PdpJmxListener() { - } + private PdpJmxListener() { + } - public static void stop() { - final MBeanServer server = ManagementFactory.getPlatformMBeanServer(); - try { - server.unregisterMBean(new ObjectName("PolicyEngine:type=PdpJmx")); - } catch (MBeanRegistrationException | InstanceNotFoundException - | MalformedObjectNameException e) { - logger.error("PdpJmxListener.stop(): " + - "Could not unregister PolicyEngine:type=PdpJmx MBean " + - "with the MBean server", e); - } - - } + /** + * Stop the listener. + */ + public static void stop() { + final MBeanServer server = ManagementFactory.getPlatformMBeanServer(); + try { + server.unregisterMBean(new ObjectName("PolicyEngine:type=PdpJmx")); + } catch (MBeanRegistrationException | InstanceNotFoundException + | MalformedObjectNameException e) { + logger.error("PdpJmxListener.stop(): " + + "Could not unregister PolicyEngine:type=PdpJmx MBean " + + "with the MBean server", e); + } - - public static void start() { - final MBeanServer server = ManagementFactory.getPlatformMBeanServer(); - try { - server.registerMBean(PdpJmx.getInstance(), new ObjectName("PolicyEngine:type=PdpJmx")); - } catch (InstanceAlreadyExistsException | MBeanRegistrationException - | NotCompliantMBeanException | MalformedObjectNameException e) { - logger.error("PdpJmxListener.start(): " + - "Could not unregister PolicyEngine:type=PdpJmx MBean " + - "with the MBean server", e); - } - - } + } + + /** + * Start. + */ + public static void start() { + final MBeanServer server = ManagementFactory.getPlatformMBeanServer(); + try { + server.registerMBean(PdpJmx.getInstance(), new ObjectName("PolicyEngine:type=PdpJmx")); + } catch (InstanceAlreadyExistsException | MBeanRegistrationException + | NotCompliantMBeanException | MalformedObjectNameException e) { + logger.error("PdpJmxListener.start(): " + + "Could not unregister PolicyEngine:type=PdpJmx MBean " + + "with the MBean server", e); + } + + } } diff --git a/policy-core/src/main/java/org/onap/policy/drools/core/jmx/PdpJmxMBean.java b/policy-core/src/main/java/org/onap/policy/drools/core/jmx/PdpJmxMBean.java index 37a9e4dc..d2c05f85 100644 --- a/policy-core/src/main/java/org/onap/policy/drools/core/jmx/PdpJmxMBean.java +++ b/policy-core/src/main/java/org/onap/policy/drools/core/jmx/PdpJmxMBean.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * policy-core * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,6 +22,7 @@ package org.onap.policy.drools.core.jmx; public interface PdpJmxMBean { - public long getRulesFired(); - public long getUpdates(); + public long getRulesFired(); + + public long getUpdates(); } diff --git a/policy-core/src/main/java/org/onap/policy/drools/core/lock/Lock.java b/policy-core/src/main/java/org/onap/policy/drools/core/lock/Lock.java index d3764910..de62b24a 100644 --- a/policy-core/src/main/java/org/onap/policy/drools/core/lock/Lock.java +++ b/policy-core/src/main/java/org/onap/policy/drools/core/lock/Lock.java @@ -59,7 +59,7 @@ public class Lock { * The requester was not the owner, nor was it waiting in the queue. */ NOT_FOUND - }; + } /** * The last owner to grab the lock, never {@code null}. @@ -75,6 +75,7 @@ public class Lock { private LinkedHashMap requester2item = new LinkedHashMap<>(5); /** + * Constructor. * * @param owner the current owner of this lock */ @@ -83,6 +84,7 @@ public class Lock { } /** + * Get owner. * * @return the current owner of the lock, or the last owner of the lock, if the lock * is not currently owned. (This will never be {@code null}.) @@ -94,7 +96,7 @@ public class Lock { /** * Adds a new requester to the queue of requesters. * - * @param requester + * @param requester the requester * @param item to be associated with the requester, must not be {@code null} * @return {@code true} if the requester was added, {@code false} if it already owns * the lock or is already in the queue @@ -123,7 +125,7 @@ public class Lock { * item associated with the requester, it is unable to notify the new owner that it's * the new owner; that is left up to the code that invokes this method. * - * @param requester + * @param requester the requester * @param newOwner the new owner info is placed here, if the result is RELOCKED * @return the result */ diff --git a/policy-core/src/main/java/org/onap/policy/drools/core/lock/PolicyResourceLockFeatureAPI.java b/policy-core/src/main/java/org/onap/policy/drools/core/lock/PolicyResourceLockFeatureAPI.java index 5aee490f..105d6ec9 100644 --- a/policy-core/src/main/java/org/onap/policy/drools/core/lock/PolicyResourceLockFeatureAPI.java +++ b/policy-core/src/main/java/org/onap/policy/drools/core/lock/PolicyResourceLockFeatureAPI.java @@ -26,12 +26,12 @@ import org.onap.policy.drools.utils.OrderedServiceImpl; /** * Resource locks. Each lock has an "owner", which is intended to be unique across a * single instance of a running PolicyEngine. - *

- * This interface provides a way to invoke optional features at various points in the + * + *

This interface provides a way to invoke optional features at various points in the * code. At appropriate points in the application, the code iterates through this list, * invoking these optional methods. - *

- * Implementers may choose to implement a level of locking appropriate to the application. + * + *

Implementers may choose to implement a level of locking appropriate to the application. * For instance, they may choose to implement an engine-wide locking scheme, or they may * choose to implement a global locking scheme (e.g., through a shared DB). */ @@ -45,7 +45,6 @@ public interface PolicyResourceLockFeatureAPI extends OrderedService { new OrderedServiceImpl<>(PolicyResourceLockFeatureAPI.class); /** - * * Result of a requested operation. */ public enum OperResult { @@ -65,7 +64,7 @@ public interface PolicyResourceLockFeatureAPI extends OrderedService { /** * The implementer did not handle the request; additional locking logic should - * be performed. + * be performed. */ OPER_UNHANDLED } @@ -73,8 +72,8 @@ public interface PolicyResourceLockFeatureAPI extends OrderedService { /** * This method is called before a lock is acquired on a resource. * - * @param resourceId - * @param owner + * @param resourceId resource id + * @param owner owner * @param holdSec the amount of time, in seconds, that the lock should be held * @return the result, where OPER_DENIED indicates that the lock is currently * held by another owner @@ -86,8 +85,8 @@ public interface PolicyResourceLockFeatureAPI extends OrderedService { /** * This method is called after a lock for a resource has been acquired or denied. * - * @param resourceId - * @param owner + * @param resourceId resource id + * @param owner owner * @param locked {@code true} if the lock was acquired, {@code false} if it was denied * @return {@code true} if the implementer handled the request, {@code false} * otherwise @@ -100,8 +99,8 @@ public interface PolicyResourceLockFeatureAPI extends OrderedService { * This method is called before a lock is refreshed on a resource. It may be invoked * repeatedly to extend the time that a lock is held. * - * @param resourceId - * @param owner + * @param resourceId resource id + * @param owner owner * @param holdSec the amount of time, in seconds, that the lock should be held * @return the result, where OPER_DENIED indicates that the resource is not * currently locked by the given owner @@ -114,8 +113,8 @@ public interface PolicyResourceLockFeatureAPI extends OrderedService { * This method is called after a lock for a resource has been refreshed (or after the * refresh has been denied). * - * @param resourceId - * @param owner + * @param resourceId resource id + * @param owner owner * @param locked {@code true} if the lock was acquired, {@code false} if it was denied * @return {@code true} if the implementer handled the request, {@code false} * otherwise @@ -127,8 +126,8 @@ public interface PolicyResourceLockFeatureAPI extends OrderedService { /** * This method is called before a lock on a resource is released. * - * @param resourceId - * @param owner + * @param resourceId resource id + * @param owner owner * @return the result, where OPER_DENIED indicates that the lock is not * currently held by the given owner */ @@ -139,8 +138,8 @@ public interface PolicyResourceLockFeatureAPI extends OrderedService { /** * This method is called after a lock on a resource is released. * - * @param resourceId - * @param owner + * @param resourceId resource id + * @param owner owner * @param unlocked {@code true} if the lock was released, {@code false} if the owner * did not have a lock on the resource * @return {@code true} if the implementer handled the request, {@code false} @@ -153,7 +152,7 @@ public interface PolicyResourceLockFeatureAPI extends OrderedService { /** * This method is called before a check is made to determine if a resource is locked. * - * @param resourceId + * @param resourceId resource id * @return the result, where OPER_ACCEPTED indicates that the resource is * locked, while OPER_DENIED indicates that it is not */ @@ -165,8 +164,8 @@ public interface PolicyResourceLockFeatureAPI extends OrderedService { * This method is called before a check is made to determine if a particular owner * holds the lock on a resource. * - * @param resourceId - * @param owner + * @param resourceId resource id + * @param owner owner * @return the result, where OPER_ACCEPTED indicates that the resource is * locked by the given owner, while OPER_DENIED indicates that it is * not diff --git a/policy-core/src/main/java/org/onap/policy/drools/core/lock/PolicyResourceLockManager.java b/policy-core/src/main/java/org/onap/policy/drools/core/lock/PolicyResourceLockManager.java index 8e13ced4..3612b29d 100644 --- a/policy-core/src/main/java/org/onap/policy/drools/core/lock/PolicyResourceLockManager.java +++ b/policy-core/src/main/java/org/onap/policy/drools/core/lock/PolicyResourceLockManager.java @@ -47,6 +47,7 @@ public class PolicyResourceLockManager extends SimpleLockManager { } /** + * Get instance. * * @return the manager singleton */ @@ -61,7 +62,7 @@ public class PolicyResourceLockManager extends SimpleLockManager { /** * Sets the factory to be used by junit tests. * - * @param factory + * @param factory the factory */ protected static void setFactory(Factory factory) { PolicyResourceLockManager.factory = factory; @@ -134,6 +135,7 @@ public class PolicyResourceLockManager extends SimpleLockManager { } /** + * Is locked. * * @throws IllegalArgumentException if the resourceId is {@code null} */ @@ -146,13 +148,14 @@ public class PolicyResourceLockManager extends SimpleLockManager { return doBoolIntercept(impl -> impl.beforeIsLocked(resourceId), () -> - // implementer didn't do the work - defer to the superclass + // implementer didn't do the work - defer to the superclass super.isLocked(resourceId) ); } /** - * + * Is locked by. + * * @throws IllegalArgumentException if the resourceId or owner is {@code null} */ @Override @@ -177,8 +180,8 @@ public class PolicyResourceLockManager extends SimpleLockManager { * of them returns a result other than OPER_UNHANDLED. If they all return * OPER_UNHANDLED, then it returns the result of applying the default function. * - * @param interceptFunc - * @param defaultFunc + * @param interceptFunc intercept function + * @param defaultFunc default function * @return {@code true} if success, {@code false} otherwise */ private boolean doBoolIntercept(Function interceptFunc, @@ -199,8 +202,8 @@ public class PolicyResourceLockManager extends SimpleLockManager { * @param continueValue if the implementer returns this value, then it continues to * check addition implementers * @param func function to be applied to the implementers - * @return first non-null value returned by an implementer, continueValue if - * they all returned continueValue + * @return first non-null value returned by an implementer, continueValue if + * they all returned continueValue */ private static T doIntercept(T continueValue, Function func) { @@ -241,6 +244,7 @@ public class PolicyResourceLockManager extends SimpleLockManager { public static class Factory { /** + * Get implementers. * * @return the list of feature implementers */ diff --git a/policy-core/src/main/java/org/onap/policy/drools/core/lock/SimpleLockManager.java b/policy-core/src/main/java/org/onap/policy/drools/core/lock/SimpleLockManager.java index 243ba3cb..427fbbc6 100644 --- a/policy-core/src/main/java/org/onap/policy/drools/core/lock/SimpleLockManager.java +++ b/policy-core/src/main/java/org/onap/policy/drools/core/lock/SimpleLockManager.java @@ -67,7 +67,7 @@ public class SimpleLockManager { private final SortedSet locks = new TreeSet<>(); /** - * + * Constructor. */ public SimpleLockManager() { super(); @@ -78,8 +78,8 @@ public class SimpleLockManager { * it's the same owner; the same owner can use {@link #refresh(String, String, int) * refresh()}, instead, to extend a lock on a resource. * - * @param resourceId - * @param owner + * @param resourceId resource id + * @param owner owner * @param holdSec the amount of time, in seconds, that the lock should be held * @return {@code true} if locked, {@code false} if the resource is already locked by * a different owner @@ -97,10 +97,10 @@ public class SimpleLockManager { boolean locked = false; - synchronized(locker) { + synchronized (locker) { cleanUpLocks(); - if(!resource2data.containsKey(resourceId)) { + if (!resource2data.containsKey(resourceId)) { Data data = new Data(owner, resourceId, currentTime.getMillis() + TimeUnit.SECONDS.toMillis(holdSec)); resource2data.put(resourceId, data); locks.add(data); @@ -116,8 +116,8 @@ public class SimpleLockManager { /** * Attempts to refresh a lock on a resource. * - * @param resourceId - * @param owner + * @param resourceId resource id + * @param owner owner * @param holdSec the amount of time, in seconds, that the lock should be held * @return {@code true} if locked, {@code false} if the resource is not currently * locked by the given owner @@ -135,7 +135,7 @@ public class SimpleLockManager { boolean refreshed = false; - synchronized(locker) { + synchronized (locker) { cleanUpLocks(); Data existingLock = resource2data.get(resourceId); @@ -159,8 +159,8 @@ public class SimpleLockManager { /** * Unlocks a resource. * - * @param resourceId - * @param owner + * @param resourceId resource id + * @param owner owner * @return {@code true} if unlocked, {@code false} if the given owner does not * currently hold a lock on the resource * @throws IllegalArgumentException if the resourceId or owner is {@code null} @@ -176,11 +176,11 @@ public class SimpleLockManager { Data data; - synchronized(locker) { + synchronized (locker) { cleanUpLocks(); - if((data = resource2data.get(resourceId)) != null) { - if(owner.equals(data.getOwner())) { + if ((data = resource2data.get(resourceId)) != null) { + if (owner.equals(data.getOwner())) { resource2data.remove(resourceId); locks.remove(data); @@ -199,7 +199,7 @@ public class SimpleLockManager { /** * Determines if a resource is locked by anyone. * - * @param resourceId + * @param resourceId resource id * @return {@code true} if the resource is locked, {@code false} otherwise * @throws IllegalArgumentException if the resourceId is {@code null} */ @@ -211,7 +211,7 @@ public class SimpleLockManager { boolean locked; - synchronized(locker) { + synchronized (locker) { cleanUpLocks(); locked = resource2data.containsKey(resourceId); @@ -225,8 +225,8 @@ public class SimpleLockManager { /** * Determines if a resource is locked by a particular owner. * - * @param resourceId - * @param owner + * @param resourceId resource id + * @param owner owner * @return {@code true} if the resource is locked, {@code false} otherwise * @throws IllegalArgumentException if the resourceId or owner is {@code null} */ @@ -242,7 +242,7 @@ public class SimpleLockManager { Data data; - synchronized(locker) { + synchronized (locker) { cleanUpLocks(); data = resource2data.get(resourceId); @@ -260,14 +260,13 @@ public class SimpleLockManager { private void cleanUpLocks() { long tcur = currentTime.getMillis(); - synchronized(locker) { + synchronized (locker) { Iterator it = locks.iterator(); - while(it.hasNext()) { - Data d = it.next(); - if(d.getExpirationMs() <= tcur) { + while (it.hasNext()) { + Data data = it.next(); + if (data.getExpirationMs() <= tcur) { it.remove(); - resource2data.remove(d.getResource()); - + resource2data.remove(data.getResource()); } else { break; } @@ -307,10 +306,11 @@ public class SimpleLockManager { private final long texpireMs; /** + * Constructor. * - * @param resource - * @param owner - * @param texpireMs + * @param resource resource + * @param owner owner + * @param texpireMs time expire in milliseconds */ public Data(String owner, String resource, long texpireMs) { this.owner = owner; @@ -331,12 +331,14 @@ public class SimpleLockManager { } @Override - public int compareTo(Data o) { - int diff = Long.compare(texpireMs, o.texpireMs); - if(diff == 0) - diff = resource.compareTo(o.resource); - if(diff == 0) - diff = owner.compareTo(o.owner); + public int compareTo(Data data) { + int diff = Long.compare(texpireMs, data.texpireMs); + if (diff == 0) { + diff = resource.compareTo(data.resource); + } + if (diff == 0) { + diff = owner.compareTo(data.owner); + } return diff; } @@ -352,23 +354,30 @@ public class SimpleLockManager { @Override public boolean equals(Object obj) { - if (this == obj) + if (this == obj) { return true; - if (obj == null) + } + if (obj == null) { return false; - if (getClass() != obj.getClass()) + } + if (getClass() != obj.getClass()) { return false; + } Data other = (Data) obj; if (owner == null) { - if (other.owner != null) + if (other.owner != null) { return false; - } else if (!owner.equals(other.owner)) + } + } else if (!owner.equals(other.owner)) { return false; + } if (resource == null) { - if (other.resource != null) + if (other.resource != null) { return false; - } else if (!resource.equals(other.resource)) + } + } else if (!resource.equals(other.resource)) { return false; + } return (texpireMs == other.texpireMs); } } diff --git a/policy-core/src/main/java/org/onap/policy/drools/util/FeatureEnabledChecker.java b/policy-core/src/main/java/org/onap/policy/drools/util/FeatureEnabledChecker.java index e604c30a..3bbfdcf4 100644 --- a/policy-core/src/main/java/org/onap/policy/drools/util/FeatureEnabledChecker.java +++ b/policy-core/src/main/java/org/onap/policy/drools/util/FeatureEnabledChecker.java @@ -28,7 +28,7 @@ import java.util.Properties; public class FeatureEnabledChecker { /** - * + * Constructor. */ private FeatureEnabledChecker() { super(); diff --git a/policy-core/src/main/java/org/onap/policy/drools/util/KieUtils.java b/policy-core/src/main/java/org/onap/policy/drools/util/KieUtils.java index 16e166d2..a3efe433 100644 --- a/policy-core/src/main/java/org/onap/policy/drools/util/KieUtils.java +++ b/policy-core/src/main/java/org/onap/policy/drools/util/KieUtils.java @@ -37,16 +37,16 @@ import org.kie.api.builder.model.KieModuleModel; import org.kie.scanner.MavenRepository; /** - * Kie related utilities + * Kie related utilities. */ public class KieUtils { - private KieUtils() { - throw new IllegalStateException("Utility class"); - } - + private KieUtils() { + throw new IllegalStateException("Utility class"); + } + /** - * Installs a rules artifact in the local maven repository + * Installs a rules artifact in the local maven repository. * * @param kmodule kmodule specification * @param pom pom @@ -56,7 +56,8 @@ public class KieUtils { * @return releaseId result o a sucessful installation * @throws IOException error accessing necessary resources */ - public static ReleaseId installArtifact(String kmodule, String pom, String drlKJarPath, String drl) throws IOException { + public static ReleaseId installArtifact(String kmodule, String pom, String drlKJarPath, + String drl) throws IOException { KieModuleModel kieModule = KieModuleModelImpl.fromXML(kmodule); final KieFileSystem kieFileSystem = KieServices.Factory.get().newKieFileSystem(); @@ -72,15 +73,15 @@ public class KieUtils { pomFile.deleteOnExit(); ReleaseId releaseId = kieBuilder.getKieModule().getReleaseId(); - MavenRepository.getMavenRepository(). - installArtifact(releaseId, + MavenRepository.getMavenRepository() + .installArtifact(releaseId, (InternalKieModule) kieBuilder.getKieModule(), pomFile); return releaseId; } /** - * Installs a rules artifact in the local maven repository + * Installs a rules artifact in the local maven repository. * * @param kmodule kmodule specification * @param pom pom @@ -101,16 +102,17 @@ public class KieUtils { KieBuilder kieBuilder = kieBuild(kieFileSystem); ReleaseId releaseId = kieBuilder.getKieModule().getReleaseId(); - MavenRepository.getMavenRepository(). - installArtifact(releaseId, (InternalKieModule) kieBuilder.getKieModule(), pom); + MavenRepository.getMavenRepository() + .installArtifact(releaseId, (InternalKieModule) kieBuilder.getKieModule(), pom); return releaseId; } private static KieBuilder kieBuild(KieFileSystem kieFileSystem) { KieBuilder kieBuilder = KieServices.Factory.get().newKieBuilder(kieFileSystem); List messages = kieBuilder.buildAll().getResults().getMessages(); - if (messages != null && !messages.isEmpty()) + if (messages != null && !messages.isEmpty()) { throw new IllegalArgumentException(messages.toString()); + } return kieBuilder; } } diff --git a/policy-core/src/test/java/org/onap/policy/drools/core/DroolsContainerTest.java b/policy-core/src/test/java/org/onap/policy/drools/core/DroolsContainerTest.java index 1da6e011..d2d0dec2 100644 --- a/policy-core/src/test/java/org/onap/policy/drools/core/DroolsContainerTest.java +++ b/policy-core/src/test/java/org/onap/policy/drools/core/DroolsContainerTest.java @@ -26,330 +26,302 @@ import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import java.nio.file.Paths; -import java.util.ArrayList; +import java.util.Arrays; import java.util.Collection; import org.junit.BeforeClass; import org.junit.Test; import org.onap.policy.drools.util.KieUtils; /** - * These tests focus on the following classes: - * PolicyContainer - * PolicySession - * PolicySessionFeatureAPI + * These tests focus on the following classes. + * PolicyContainer + * PolicySession + * PolicySessionFeatureAPI */ -public class DroolsContainerTest -{ - /** - * This test is centered around the creation of a 'PolicyContainer' - * and 'PolicySession', and the updating of that container to a new - * version. - */ - @BeforeClass - public static void setUp() throws Exception - { - KieUtils.installArtifact - (Paths.get("src/test/resources/drools-artifact-1.1/src/main/resources/META-INF/kmodule.xml").toFile(), - Paths.get("src/test/resources/drools-artifact-1.1/pom.xml").toFile(), - "src/main/resources/rules/org/onap/policy/drools/core/test/rules.drl", - Paths.get("src/test/resources/drools-artifact-1.1/src/main/resources/rules.drl").toFile()); - - KieUtils.installArtifact - (Paths.get("src/test/resources/drools-artifact-1.2/src/main/resources/META-INF/kmodule.xml").toFile(), - Paths.get("src/test/resources/drools-artifact-1.2/pom.xml").toFile(), - "src/main/resources/rules/org/onap/policy/drools/core/test/rules.drl", - Paths.get("src/test/resources/drools-artifact-1.2/src/main/resources/rules.drl").toFile()); - } - - /** - * This test is centered around the creation of a 'PolicyContainer' - * and 'PolicySession', and the updating of that container to a new - * version. - */ - @Test - public void createAndUpdate() throws Exception - { - // make sure feature log starts out clean - TestPolicySessionFeatureAPI.getLog(); - - // run 'globalInit', and verify expected feature hook fired - PolicyContainer.globalInit(new String[0]); - assertEquals(buildArrayList("globalInit"), - TestPolicySessionFeatureAPI.getLog()); - - // initial conditions -- there should be no containers - assertEquals(0, PolicyContainer.getPolicyContainers().size()); - - // create the container, and start it - PolicyContainer container = - new PolicyContainer("org.onap.policy.drools-pdp", - "drools-artifact1", "17.1.0-SNAPSHOT"); - container.start(); - assertTrue(container.isAlive()); - - // verify expected feature hooks fired - assertEquals(buildArrayList("activatePolicySession", - "newPolicySession", - "selectThreadModel"), - TestPolicySessionFeatureAPI.getLog()); - - // this container should be on the list - { - Collection containers = - PolicyContainer.getPolicyContainers(); - assertEquals(1, containers.size()); - assertTrue(containers.contains(container)); - } - - // verify initial container attributes - assertEquals("org.onap.policy.drools-pdp:drools-artifact1:17.1.0-SNAPSHOT", - container.getName()); - assertEquals("org.onap.policy.drools-pdp", container.getGroupId()); - assertEquals("drools-artifact1", container.getArtifactId()); - assertEquals("17.1.0-SNAPSHOT", container.getVersion()); - - try - { - // fetch the session, and verify that it exists - PolicySession session = container.getPolicySession("session1"); - assertTrue(session != null); - - // get all sessions, and verify that this one is the only one - { - Collection sessions = container.getPolicySessions(); - assertEquals(1, sessions.size()); - assertTrue(sessions.contains(session)); - } - - // verify session attributes - assertEquals(container, session.getPolicyContainer()); - assertEquals("session1", session.getName()); - assertEquals("org.onap.policy.drools-pdp:drools-artifact1:17.1.0-SNAPSHOT:session1", - session.getFullName()); - - // insert a new fact - int[] a = new int[]{0, 3, 8, 2}; - session.getKieSession().insert(a); - - // the Drools rules should add 3 + 8 + 2, and store 13 in a[0] - assertTrue(waitForChange(a) == 13); - - // update the container to a new version -- - // the rules will then multiply values rather than add them - assertEquals("[]", - container.updateToVersion("17.2.0-SNAPSHOT").toString()); - - // verify expected feature hooks fired - assertEquals(buildArrayList("selectThreadModel"), - TestPolicySessionFeatureAPI.getLog()); - - // verify new container attributes - assertEquals - ("org.onap.policy.drools-pdp:drools-artifact1:17.2.0-SNAPSHOT", - container.getName()); - assertEquals("org.onap.policy.drools-pdp", container.getGroupId()); - assertEquals("drools-artifact1", container.getArtifactId()); - assertEquals("17.2.0-SNAPSHOT", container.getVersion()); - - // verify new session attributes - assertEquals(container, session.getPolicyContainer()); - assertEquals("session1", session.getName()); - assertEquals("org.onap.policy.drools-pdp:drools-artifact1:17.2.0-SNAPSHOT:session1", - session.getFullName()); - - // the updated rules should now multiply 3 * 8 * 2, and return 48 - - a[0] = 0; - container.insert("session1", a); - assertTrue(waitForChange(a) == 48); - } - finally - { - container.shutdown(); - assertFalse(container.isAlive()); - - // verify expected feature hooks fired - assertEquals(buildArrayList("disposeKieSession"), - TestPolicySessionFeatureAPI.getLog()); - } - - // final conditions -- there should be no containers - assertEquals(0, PolicyContainer.getPolicyContainers().size()); - } - - /** - * This test create a 'PolicyContainer' and 'PolicySession', and verifies - * their behavior, but uses alternate interfaces to increase code coverage. - * In addition, feature hook invocations will trigger exceptions in this - * test, also to increase code coverage. - */ - @Test - public void versionList() throws Exception - { - // make sure feature log starts out clean - TestPolicySessionFeatureAPI.getLog(); - - // trigger exceptions in all feature hooks - TestPolicySessionFeatureAPI.setExceptionTrigger(true); - - // run 'globalInit', and verify expected feature hook fired - PolicyContainer.globalInit(new String[0]); - assertEquals(buildArrayList("globalInit-exception"), - TestPolicySessionFeatureAPI.getLog()); - - // initial conditions -- there should be no containers - assertEquals(0, PolicyContainer.getPolicyContainers().size()); - - String versionList = - "17.3.0-SNAPSHOT,17.1.0-SNAPSHOT,17.2.0-SNAPSHOT"; - - // versions should be tried in order -- the 17.1.0-SNAPSHOT should "win", - // given the fact that '17.3.0-SNAPSHOT' doesn't exist - PolicyContainer container = - new PolicyContainer("org.onap.policy.drools-pdp", - "drools-artifact1", versionList); - // the following should be equivalent to 'container.start()' - PolicyContainer.activate(); - assertTrue(container.isAlive()); - - // verify expected feature hooks fired - assertEquals(buildArrayList("activatePolicySession-exception", - "newPolicySession-exception", - "selectThreadModel-exception"), - TestPolicySessionFeatureAPI.getLog()); - - // this container should be on the list - { - Collection containers = - PolicyContainer.getPolicyContainers(); - assertEquals(1, containers.size()); - assertTrue(containers.contains(container)); - } - - // verify initial container attributes - assertEquals("org.onap.policy.drools-pdp:drools-artifact1:17.1.0-SNAPSHOT", - container.getName()); - assertEquals("org.onap.policy.drools-pdp", container.getGroupId()); - assertEquals("drools-artifact1", container.getArtifactId()); - assertEquals("17.1.0-SNAPSHOT", container.getVersion()); - - // some container adjunct tests - { - Object bogusAdjunct = new Object(); - - // initially, no adjunct - assertSame(null, container.getAdjunct(this)); - - // set and verify adjunct - container.setAdjunct(this, bogusAdjunct); - assertSame(bogusAdjunct, container.getAdjunct(this)); - - // clear and verify adjunct - container.setAdjunct(this, null); - assertSame(null, container.getAdjunct(this)); - } - - try - { - // fetch the session, and verify that it exists - PolicySession session = container.getPolicySession("session1"); - assertTrue(session != null); - - // get all sessions, and verify that this one is the only one - { - Collection sessions = container.getPolicySessions(); - assertEquals(1, sessions.size()); - assertTrue(sessions.contains(session)); - } - - // verify session attributes - assertEquals(container, session.getPolicyContainer()); - assertEquals("session1", session.getName()); - assertEquals("org.onap.policy.drools-pdp:drools-artifact1:17.1.0-SNAPSHOT:session1", - session.getFullName()); - - // some session adjunct tests - { - Object bogusAdjunct = new Object(); - - // initially, no adjunct - assertSame(null, session.getAdjunct(this)); - - // set and verify adjunct - session.setAdjunct(this, bogusAdjunct); - assertSame(bogusAdjunct, session.getAdjunct(this)); - - // clear and verify adjunct - session.setAdjunct(this, null); - assertSame(null, session.getAdjunct(this)); - } - - // insert a new fact (using 'insertAll') - int[] a = new int[]{0, 7, 3, 4}; - container.insertAll(a); - - // the Drools rules should add 7 + 3 + 4, and store 14 in a[0] - assertTrue(waitForChange(a) == 14); - - // exercise some more API methods - assertEquals(container.getClassLoader(), - container.getKieContainer().getClassLoader()); - } - finally - { - // should be equivalent to 'shutdown' without persistence - container.destroy(); - assertFalse(container.isAlive()); - - // verify expected feature hooks fired - assertEquals(buildArrayList("destroyKieSession-exception"), - TestPolicySessionFeatureAPI.getLog()); - - // clear exception trigger - TestPolicySessionFeatureAPI.setExceptionTrigger(false); - } - - // final conditions -- there should be no containers - assertEquals(0, PolicyContainer.getPolicyContainers().size()); - } - - /** - * This method is tied to the expected behavior of the drools sessions. - * Initially, the value of 'array[0]' should be 0. The Drools rules - * will either add or multiply 'array[1]' through 'array[n-1]', depending - * upon the version. It waits up to 30 seconds for a non-zero value - * to appear. - */ - private int waitForChange(int[] array) throws InterruptedException - { - int rval = -1; - - // the value is tested every 1/100 of a second, and it waits up to - // 3000 iterations (= 30 seconds) for a non-zero value - for (int i = 0 ; i < 3000 ; i += 1) - { - // wait for 10 milliseconds = 1/100 of a second - Thread.sleep(10); - if ((rval = array[0]) != 0) - { - // a non-zero value has been stored - break; - } - } - return(rval); - } - - /** - * @param args an array of string arguments - * @return an ArrayList constructed from the provided arguments - */ - private ArrayList buildArrayList(String... args) - { - ArrayList rval = new ArrayList<>(); - for (String arg : args) - { - rval.add(arg); - } - return(rval); - } +public class DroolsContainerTest { + /** + * This test is centered around the creation of a 'PolicyContainer' + * and 'PolicySession', and the updating of that container to a new + * version. + */ + @BeforeClass + public static void setUp() throws Exception { + KieUtils.installArtifact( + Paths.get("src/test/resources/drools-artifact-1.1/src/main/resources/META-INF/kmodule.xml").toFile(), + Paths.get("src/test/resources/drools-artifact-1.1/pom.xml").toFile(), + "src/main/resources/rules/org/onap/policy/drools/core/test/rules.drl", + Paths.get("src/test/resources/drools-artifact-1.1/src/main/resources/rules.drl").toFile()); + + KieUtils.installArtifact( + Paths.get("src/test/resources/drools-artifact-1.2/src/main/resources/META-INF/kmodule.xml").toFile(), + Paths.get("src/test/resources/drools-artifact-1.2/pom.xml").toFile(), + "src/main/resources/rules/org/onap/policy/drools/core/test/rules.drl", + Paths.get("src/test/resources/drools-artifact-1.2/src/main/resources/rules.drl").toFile()); + } + + /** + * This test is centered around the creation of a 'PolicyContainer' + * and 'PolicySession', and the updating of that container to a new + * version. + */ + @Test + public void createAndUpdate() throws Exception { + // make sure feature log starts out clean + PolicySessionFeatureApiTest.getLog(); + + // run 'globalInit', and verify expected feature hook fired + PolicyContainer.globalInit(new String[0]); + assertEquals(Arrays.asList("globalInit"), + PolicySessionFeatureApiTest.getLog()); + + // initial conditions -- there should be no containers + assertEquals(0, PolicyContainer.getPolicyContainers().size()); + + // create the container, and start it + PolicyContainer container = + new PolicyContainer("org.onap.policy.drools-pdp", + "drools-artifact1", "17.1.0-SNAPSHOT"); + container.start(); + assertTrue(container.isAlive()); + + // verify expected feature hooks fired + assertEquals(Arrays.asList("activatePolicySession", + "newPolicySession", + "selectThreadModel"), + PolicySessionFeatureApiTest.getLog()); + + // this container should be on the list + { + Collection containers = + PolicyContainer.getPolicyContainers(); + assertEquals(1, containers.size()); + assertTrue(containers.contains(container)); + } + + // verify initial container attributes + assertEquals("org.onap.policy.drools-pdp:drools-artifact1:17.1.0-SNAPSHOT", + container.getName()); + assertEquals("org.onap.policy.drools-pdp", container.getGroupId()); + assertEquals("drools-artifact1", container.getArtifactId()); + assertEquals("17.1.0-SNAPSHOT", container.getVersion()); + + try { + // fetch the session, and verify that it exists + PolicySession session = container.getPolicySession("session1"); + assertTrue(session != null); + + // get all sessions, and verify that this one is the only one + { + Collection sessions = container.getPolicySessions(); + assertEquals(1, sessions.size()); + assertTrue(sessions.contains(session)); + } + + // verify session attributes + assertEquals(container, session.getPolicyContainer()); + assertEquals("session1", session.getName()); + assertEquals("org.onap.policy.drools-pdp:drools-artifact1:17.1.0-SNAPSHOT:session1", + session.getFullName()); + + // insert a new fact + int[] facts = new int[]{0, 3, 8, 2}; + session.getKieSession().insert(facts); + + // the Drools rules should add 3 + 8 + 2, and store 13 in a[0] + assertTrue(waitForChange(facts) == 13); + + // update the container to a new version -- + // the rules will then multiply values rather than add them + assertEquals("[]", + container.updateToVersion("17.2.0-SNAPSHOT").toString()); + + // verify expected feature hooks fired + assertEquals(Arrays.asList("selectThreadModel"), + PolicySessionFeatureApiTest.getLog()); + + // verify new container attributes + assertEquals("org.onap.policy.drools-pdp:drools-artifact1:17.2.0-SNAPSHOT", + container.getName()); + assertEquals("org.onap.policy.drools-pdp", container.getGroupId()); + assertEquals("drools-artifact1", container.getArtifactId()); + assertEquals("17.2.0-SNAPSHOT", container.getVersion()); + + // verify new session attributes + assertEquals(container, session.getPolicyContainer()); + assertEquals("session1", session.getName()); + assertEquals("org.onap.policy.drools-pdp:drools-artifact1:17.2.0-SNAPSHOT:session1", + session.getFullName()); + + // the updated rules should now multiply 3 * 8 * 2, and return 48 + + facts[0] = 0; + container.insert("session1", facts); + assertTrue(waitForChange(facts) == 48); + } finally { + container.shutdown(); + assertFalse(container.isAlive()); + + // verify expected feature hooks fired + assertEquals(Arrays.asList("disposeKieSession"), + PolicySessionFeatureApiTest.getLog()); + } + + // final conditions -- there should be no containers + assertEquals(0, PolicyContainer.getPolicyContainers().size()); + } + + /** + * This test create a 'PolicyContainer' and 'PolicySession', and verifies + * their behavior, but uses alternate interfaces to increase code coverage. + * In addition, feature hook invocations will trigger exceptions in this + * test, also to increase code coverage. + */ + @Test + public void versionList() throws Exception { + // make sure feature log starts out clean + PolicySessionFeatureApiTest.getLog(); + + // trigger exceptions in all feature hooks + PolicySessionFeatureApiTest.setExceptionTrigger(true); + + // run 'globalInit', and verify expected feature hook fired + PolicyContainer.globalInit(new String[0]); + assertEquals(Arrays.asList("globalInit-exception"), + PolicySessionFeatureApiTest.getLog()); + + // initial conditions -- there should be no containers + assertEquals(0, PolicyContainer.getPolicyContainers().size()); + + String versionList = + "17.3.0-SNAPSHOT,17.1.0-SNAPSHOT,17.2.0-SNAPSHOT"; + + // versions should be tried in order -- the 17.1.0-SNAPSHOT should "win", + // given the fact that '17.3.0-SNAPSHOT' doesn't exist + PolicyContainer container = + new PolicyContainer("org.onap.policy.drools-pdp", + "drools-artifact1", versionList); + // the following should be equivalent to 'container.start()' + PolicyContainer.activate(); + assertTrue(container.isAlive()); + + // verify expected feature hooks fired + assertEquals(Arrays.asList("activatePolicySession-exception", + "newPolicySession-exception", + "selectThreadModel-exception"), + PolicySessionFeatureApiTest.getLog()); + + // this container should be on the list + { + Collection containers = + PolicyContainer.getPolicyContainers(); + assertEquals(1, containers.size()); + assertTrue(containers.contains(container)); + } + + // verify initial container attributes + assertEquals("org.onap.policy.drools-pdp:drools-artifact1:17.1.0-SNAPSHOT", + container.getName()); + assertEquals("org.onap.policy.drools-pdp", container.getGroupId()); + assertEquals("drools-artifact1", container.getArtifactId()); + assertEquals("17.1.0-SNAPSHOT", container.getVersion()); + + // some container adjunct tests + { + Object bogusAdjunct = new Object(); + + // initially, no adjunct + assertSame(null, container.getAdjunct(this)); + + // set and verify adjunct + container.setAdjunct(this, bogusAdjunct); + assertSame(bogusAdjunct, container.getAdjunct(this)); + + // clear and verify adjunct + container.setAdjunct(this, null); + assertSame(null, container.getAdjunct(this)); + } + + try { + // fetch the session, and verify that it exists + PolicySession session = container.getPolicySession("session1"); + assertTrue(session != null); + + // get all sessions, and verify that this one is the only one + { + Collection sessions = container.getPolicySessions(); + assertEquals(1, sessions.size()); + assertTrue(sessions.contains(session)); + } + + // verify session attributes + assertEquals(container, session.getPolicyContainer()); + assertEquals("session1", session.getName()); + assertEquals("org.onap.policy.drools-pdp:drools-artifact1:17.1.0-SNAPSHOT:session1", + session.getFullName()); + + // some session adjunct tests + { + Object bogusAdjunct = new Object(); + + // initially, no adjunct + assertSame(null, session.getAdjunct(this)); + + // set and verify adjunct + session.setAdjunct(this, bogusAdjunct); + assertSame(bogusAdjunct, session.getAdjunct(this)); + + // clear and verify adjunct + session.setAdjunct(this, null); + assertSame(null, session.getAdjunct(this)); + } + + // insert a new fact (using 'insertAll') + int[] facts = new int[]{0, 7, 3, 4}; + container.insertAll(facts); + + // the Drools rules should add 7 + 3 + 4, and store 14 in a[0] + assertTrue(waitForChange(facts) == 14); + + // exercise some more API methods + assertEquals(container.getClassLoader(), + container.getKieContainer().getClassLoader()); + } finally { + // should be equivalent to 'shutdown' without persistence + container.destroy(); + assertFalse(container.isAlive()); + + // verify expected feature hooks fired + assertEquals(Arrays.asList("destroyKieSession-exception"), + PolicySessionFeatureApiTest.getLog()); + + // clear exception trigger + PolicySessionFeatureApiTest.setExceptionTrigger(false); + } + + // final conditions -- there should be no containers + assertEquals(0, PolicyContainer.getPolicyContainers().size()); + } + + /** + * This method is tied to the expected behavior of the drools sessions. + * Initially, the value of 'array[0]' should be 0. The Drools rules + * will either add or multiply 'array[1]' through 'array[n-1]', depending + * upon the version. It waits up to 30 seconds for a non-zero value + * to appear. + */ + private int waitForChange(int[] array) throws InterruptedException { + int rval = -1; + + // the value is tested every 1/100 of a second, and it waits up to + // 3000 iterations (= 30 seconds) for a non-zero value + for (int i = 0 ; i < 3000 ; i += 1) { + // wait for 10 milliseconds = 1/100 of a second + Thread.sleep(10); + if ((rval = array[0]) != 0) { + // a non-zero value has been stored + break; + } + } + return (rval); + } } diff --git a/policy-core/src/test/java/org/onap/policy/drools/core/PolicySessionFeatureApiTest.java b/policy-core/src/test/java/org/onap/policy/drools/core/PolicySessionFeatureApiTest.java new file mode 100644 index 00000000..aef4e265 --- /dev/null +++ b/policy-core/src/test/java/org/onap/policy/drools/core/PolicySessionFeatureApiTest.java @@ -0,0 +1,137 @@ +/*- + * ============LICENSE_START======================================================= + * policy-core + * ================================================================================ + * Copyright (C) 2017-2018 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.core; + +import java.util.ArrayList; +import org.kie.api.runtime.KieSession; + +/** + * This class supports 'DroolsContainerTest' by implementing + * 'PolicySessionFeatureAPI', and providing a means to indicate + * which hooks have been invoked. + */ +public class PolicySessionFeatureApiTest implements PolicySessionFeatureAPI { + // contains the log entries since the most recent 'getLog()' call + private static ArrayList log = new ArrayList<>(); + + // if 'true', trigger an exception right after doing the log, + // to verify that exceptions are handled + private static boolean exceptionTrigger = false; + + /** + * Get log. + * + * @return the current contents of the log, and clear the log + */ + public static ArrayList getLog() { + synchronized (log) { + ArrayList rval = new ArrayList<>(log); + log.clear(); + return rval; + } + } + + /** + * This method controls whether these hooks trigger an exception after + * being invoked. + * + * @param indicator if 'true', subsequent hook method calls will trigger + * an exception; if 'false', no exception is triggered + */ + public static void setExceptionTrigger(boolean indicator) { + exceptionTrigger = indicator; + } + + /** + * This method adds an entry to the log, and possibly triggers an exception. + * + * @param arg value to add to the log + */ + private static void addLog(String arg) { + if (exceptionTrigger) { + // the log entry will include a '-exception' appended to the end + synchronized (log) { + log.add(arg + "-exception"); + } + System.out.println("*** " + arg + "-exception invoked ***"); + + // throw an exception -- it is up to the invoking code to catch it + throw(new IllegalStateException("Triggered from " + arg)); + } else { + // create a log entry, and display to standard output + synchronized (log) { + log.add(arg); + } + System.out.println("*** " + arg + " invoked ***"); + } + } + + /** + * {@inheritDoc}. + */ + public int getSequenceNumber() { + return 1; + } + + /** + * {@inheritDoc}. + */ + public void globalInit(String[] args, String configDir) { + addLog("globalInit"); + } + + /** + * {@inheritDoc}. + */ + public KieSession activatePolicySession(PolicyContainer policyContainer, String name, String kieBaseName) { + addLog("activatePolicySession"); + return null; + } + + /** + * {@inheritDoc}. + */ + public void newPolicySession(PolicySession policySession) { + addLog("newPolicySession"); + } + + /** + * {@inheritDoc}. + */ + public PolicySession.ThreadModel selectThreadModel(PolicySession session) { + addLog("selectThreadModel"); + return null; + } + + /** + * {@inheritDoc}. + */ + public void disposeKieSession(PolicySession policySession) { + addLog("disposeKieSession"); + } + + /** + * {@inheritDoc}. + */ + public void destroyKieSession(PolicySession policySession) { + addLog("destroyKieSession"); + } +} diff --git a/policy-core/src/test/java/org/onap/policy/drools/core/TestPolicySessionFeatureAPI.java b/policy-core/src/test/java/org/onap/policy/drools/core/TestPolicySessionFeatureAPI.java deleted file mode 100644 index f456d814..00000000 --- a/policy-core/src/test/java/org/onap/policy/drools/core/TestPolicySessionFeatureAPI.java +++ /dev/null @@ -1,157 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * policy-core - * ================================================================================ - * Copyright (C) 2017 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.core; - -import java.util.ArrayList; -import org.kie.api.runtime.KieSession; - -/** - * This class supports 'DroolsContainerTest' by implementing - * 'PolicySessionFeatureAPI', and providing a means to indicate - * which hooks have been invoked. - */ -public class TestPolicySessionFeatureAPI implements PolicySessionFeatureAPI -{ - // contains the log entries since the most recent 'getLog()' call - static private ArrayList log = new ArrayList<>(); - - // if 'true', trigger an exception right after doing the log, - // to verify that exceptions are handled - static private boolean exceptionTrigger = false; - - /** - * @return the current contents of the log, and clear the log - */ - static public ArrayList getLog() - { - synchronized(log) - { - ArrayList rval = new ArrayList<>(log); - log.clear(); - return(rval); - } - } - - /** - * This method controls whether these hooks trigger an exception after - * being invoked. - * - * @param indicator if 'true', subsequent hook method calls will trigger - * an exception; if 'false', no exception is triggered - */ - static public void setExceptionTrigger(boolean indicator) - { - exceptionTrigger = indicator; - } - - /** - * This method adds an entry to the log, and possibly triggers an exception - * - * @param arg value to add to the log - */ - static private void addLog(String arg) - { - if (exceptionTrigger) - { - // the log entry will include a '-exception' appended to the end - synchronized(log) - { - log.add(arg + "-exception"); - } - System.out.println("*** " + arg + "-exception invoked ***"); - - // throw an exception -- it is up to the invoking code to catch it - throw(new IllegalStateException("Triggered from " + arg)); - } - else - { - // create a log entry, and display to standard output - synchronized(log) - { - log.add(arg); - } - System.out.println("*** " + arg + " invoked ***"); - } - } - - /***************************************/ - /* 'PolicySessionFeatureAPI' interface */ - /***************************************/ - - /** - * {@inheritDoc} - */ - public int getSequenceNumber() - { - return(1); - } - - /** - * {@inheritDoc} - */ - public void globalInit(String args[], String configDir) - { - addLog("globalInit"); - } - - /** - * {@inheritDoc} - */ - public KieSession activatePolicySession - (PolicyContainer policyContainer, String name, String kieBaseName) - { - addLog("activatePolicySession"); - return(null); - } - - /** - * {@inheritDoc} - */ - public void newPolicySession(PolicySession policySession) - { - addLog("newPolicySession"); - } - - /** - * {@inheritDoc} - */ - public PolicySession.ThreadModel selectThreadModel(PolicySession session) - { - addLog("selectThreadModel"); - return(null); - } - - /** - * {@inheritDoc} - */ - public void disposeKieSession(PolicySession policySession) - { - addLog("disposeKieSession"); - } - - /** - * {@inheritDoc} - */ - public void destroyKieSession(PolicySession policySession) - { - addLog("destroyKieSession"); - } -} diff --git a/policy-core/src/test/java/org/onap/policy/drools/core/lock/LockTest.java b/policy-core/src/test/java/org/onap/policy/drools/core/lock/LockTest.java index bd11dcf9..5a88b02f 100644 --- a/policy-core/src/test/java/org/onap/policy/drools/core/lock/LockTest.java +++ b/policy-core/src/test/java/org/onap/policy/drools/core/lock/LockTest.java @@ -20,7 +20,10 @@ package org.onap.policy.drools.core.lock; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + import org.junit.Before; import org.junit.Test; import org.onap.policy.drools.core.lock.Lock.RemoveResult; diff --git a/policy-core/src/test/java/org/onap/policy/drools/core/lock/PolicyResourceLockFeatureAPITest.java b/policy-core/src/test/java/org/onap/policy/drools/core/lock/PolicyResourceLockFeatureAPITest.java index 0d7d9437..522a3f51 100644 --- a/policy-core/src/test/java/org/onap/policy/drools/core/lock/PolicyResourceLockFeatureAPITest.java +++ b/policy-core/src/test/java/org/onap/policy/drools/core/lock/PolicyResourceLockFeatureAPITest.java @@ -22,6 +22,7 @@ package org.onap.policy.drools.core.lock; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; + import org.junit.Before; import org.junit.Test; import org.onap.policy.drools.core.lock.PolicyResourceLockFeatureAPI.OperResult; @@ -33,6 +34,9 @@ public class PolicyResourceLockFeatureAPITest { private PolicyResourceLockFeatureAPI api; + /** + * set up. + */ @Before public void setUp() { api = new PolicyResourceLockFeatureAPI() { diff --git a/policy-core/src/test/java/org/onap/policy/drools/core/lock/PolicyResourceLockManagerTest.java b/policy-core/src/test/java/org/onap/policy/drools/core/lock/PolicyResourceLockManagerTest.java index 5cbed304..962fb96a 100644 --- a/policy-core/src/test/java/org/onap/policy/drools/core/lock/PolicyResourceLockManagerTest.java +++ b/policy-core/src/test/java/org/onap/policy/drools/core/lock/PolicyResourceLockManagerTest.java @@ -32,7 +32,8 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import static org.onap.policy.drools.core.lock.TestUtils.expectException; +import static org.onap.policy.drools.core.lock.TestingUtils.expectException; + import java.util.Arrays; import java.util.LinkedList; import java.util.List; @@ -79,6 +80,9 @@ public class PolicyResourceLockManagerTest { PolicyResourceLockManager.setFactory(saveFactory); } + /** + * Set up. + */ @Before public void setUp() { impl1 = mock(PolicyResourceLockFeatureAPI.class); @@ -104,7 +108,7 @@ public class PolicyResourceLockManagerTest { /** * Initializes an implementer so it always returns {@code null}. * - * @param impl + * @param impl implementer */ private void initImplementer(PolicyResourceLockFeatureAPI impl) { when(impl.beforeLock(anyString(), anyString(), anyInt())).thenReturn(OperResult.OPER_UNHANDLED); diff --git a/policy-core/src/test/java/org/onap/policy/drools/core/lock/SimpleLockManagerTest.java b/policy-core/src/test/java/org/onap/policy/drools/core/lock/SimpleLockManagerTest.java index feabdbc0..6afe5a83 100644 --- a/policy-core/src/test/java/org/onap/policy/drools/core/lock/SimpleLockManagerTest.java +++ b/policy-core/src/test/java/org/onap/policy/drools/core/lock/SimpleLockManagerTest.java @@ -24,7 +24,8 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; -import static org.onap.policy.drools.core.lock.TestUtils.expectException; +import static org.onap.policy.drools.core.lock.TestingUtils.expectException; + import java.util.LinkedList; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; @@ -78,6 +79,9 @@ public class SimpleLockManagerTest { Whitebox.setInternalState(SimpleLockManager.class, TIME_FIELD, savedTime); } + /** + * Set up. + */ @Before public void setUp() { testTime = new TestTime(); @@ -112,18 +116,18 @@ public class SimpleLockManagerTest { mgr.lock(RESOURCE_A, OWNER1, MAX_AGE_SEC); // sleep half of the cycle - testTime.sleep(MAX_AGE_MS/2); + testTime.sleep(MAX_AGE_MS / 2); assertTrue(mgr.isLockedBy(RESOURCE_A, OWNER1)); // extend the lock mgr.refresh(RESOURCE_A, OWNER1, MAX_AGE_SEC); // verify still locked after sleeping the other half of the cycle - testTime.sleep(MAX_AGE_MS/2+1); + testTime.sleep(MAX_AGE_MS / 2 + 1); assertTrue(mgr.isLockedBy(RESOURCE_A, OWNER1)); // and should release after another half cycle - testTime.sleep(MAX_AGE_MS/2); + testTime.sleep(MAX_AGE_MS / 2); assertFalse(mgr.isLockedBy(RESOURCE_A, OWNER1)); } @@ -338,13 +342,13 @@ public class SimpleLockManagerTest { assertTrue(mgr.isLocked(RESOURCE_A)); assertTrue(mgr.isLocked(RESOURCE_B)); - testTime.sleep(MAX_AGE_MS/4); + testTime.sleep(MAX_AGE_MS / 4); mgr.lock(RESOURCE_C, OWNER1, MAX_AGE_SEC); assertTrue(mgr.isLocked(RESOURCE_A)); assertTrue(mgr.isLocked(RESOURCE_B)); assertTrue(mgr.isLocked(RESOURCE_C)); - testTime.sleep(MAX_AGE_MS/4); + testTime.sleep(MAX_AGE_MS / 4); mgr.lock(RESOURCE_D, OWNER1, MAX_AGE_SEC); assertTrue(mgr.isLocked(RESOURCE_A)); assertTrue(mgr.isLocked(RESOURCE_B)); @@ -352,19 +356,19 @@ public class SimpleLockManagerTest { assertTrue(mgr.isLocked(RESOURCE_D)); // sleep remainder of max age - first two should expire - testTime.sleep(MAX_AGE_MS/2); + testTime.sleep(MAX_AGE_MS / 2); assertFalse(mgr.isLocked(RESOURCE_A)); assertFalse(mgr.isLocked(RESOURCE_B)); assertTrue(mgr.isLocked(RESOURCE_C)); assertTrue(mgr.isLocked(RESOURCE_D)); // another quarter - next one should expire - testTime.sleep(MAX_AGE_MS/4); + testTime.sleep(MAX_AGE_MS / 4); assertFalse(mgr.isLocked(RESOURCE_C)); assertTrue(mgr.isLocked(RESOURCE_D)); // another quarter - last one should expire - testTime.sleep(MAX_AGE_MS/4); + testTime.sleep(MAX_AGE_MS / 4); assertFalse(mgr.isLocked(RESOURCE_D)); } @@ -389,9 +393,7 @@ public class SimpleLockManagerTest { long ttime = System.currentTimeMillis() + 50; Data data = new Data(OWNER1, RESOURCE_A, ttime); Data dataSame = new Data(OWNER1, RESOURCE_A, ttime); - Data dataDiffExpire = new Data(OWNER1, RESOURCE_A, ttime+1); - Data dataDiffOwner = new Data(OWNER2, RESOURCE_A, ttime); - Data dataDiffResource = new Data(OWNER1, RESOURCE_B, ttime); + Data dataDiffExpire = new Data(OWNER1, RESOURCE_A, ttime + 1); assertEquals(0, data.compareTo(data)); assertEquals(0, data.compareTo(dataSame)); @@ -399,6 +401,9 @@ public class SimpleLockManagerTest { assertTrue(data.compareTo(dataDiffExpire) < 0); assertTrue(dataDiffExpire.compareTo(data) > 0); + Data dataDiffOwner = new Data(OWNER2, RESOURCE_A, ttime); + Data dataDiffResource = new Data(OWNER1, RESOURCE_B, ttime); + assertTrue(data.compareTo(dataDiffOwner) < 0); assertTrue(dataDiffOwner.compareTo(data) > 0); @@ -411,17 +416,19 @@ public class SimpleLockManagerTest { long ttime = System.currentTimeMillis() + 1; Data data = new Data(OWNER1, RESOURCE_A, ttime); Data dataSame = new Data(OWNER1, RESOURCE_A, ttime); - Data dataDiffExpire = new Data(OWNER1, RESOURCE_A, ttime+1); + Data dataDiffExpire = new Data(OWNER1, RESOURCE_A, ttime + 1); Data dataDiffOwner = new Data(OWNER2, RESOURCE_A, ttime); - Data dataDiffResource = new Data(OWNER1, RESOURCE_B, ttime); - Data dataNullOwner = new Data(null, RESOURCE_A, ttime); - Data dataNullResource = new Data(OWNER1, null, ttime); int hc1 = data.hashCode(); assertEquals(hc1, dataSame.hashCode()); assertTrue(hc1 != dataDiffExpire.hashCode()); assertTrue(hc1 != dataDiffOwner.hashCode()); + + Data dataDiffResource = new Data(OWNER1, RESOURCE_B, ttime); + Data dataNullOwner = new Data(null, RESOURCE_A, ttime); + Data dataNullResource = new Data(OWNER1, null, ttime); + assertTrue(hc1 != dataDiffResource.hashCode()); assertTrue(hc1 != dataNullOwner.hashCode()); assertTrue(hc1 != dataNullResource.hashCode()); @@ -432,15 +439,14 @@ public class SimpleLockManagerTest { long ttime = System.currentTimeMillis() + 50; Data data = new Data(OWNER1, RESOURCE_A, ttime); Data dataSame = new Data(OWNER1, RESOURCE_A, ttime); - Data dataDiffExpire = new Data(OWNER1, RESOURCE_A, ttime+1); - Data dataDiffOwner = new Data(OWNER2, RESOURCE_A, ttime); - Data dataDiffResource = new Data(OWNER1, RESOURCE_B, ttime); - Data dataNullOwner = new Data(null, RESOURCE_A, ttime); - Data dataNullResource = new Data(OWNER1, null, ttime); + Data dataDiffExpire = new Data(OWNER1, RESOURCE_A, ttime + 1); assertTrue(data.equals(data)); assertTrue(data.equals(dataSame)); + Data dataDiffOwner = new Data(OWNER2, RESOURCE_A, ttime); + Data dataDiffResource = new Data(OWNER1, RESOURCE_B, ttime); + assertFalse(data.equals(dataDiffExpire)); assertFalse(data.equals(dataDiffOwner)); assertFalse(data.equals(dataDiffResource)); @@ -448,6 +454,9 @@ public class SimpleLockManagerTest { assertFalse(data.equals(null)); assertFalse(data.equals("string")); + Data dataNullOwner = new Data(null, RESOURCE_A, ttime); + Data dataNullResource = new Data(OWNER1, null, ttime); + assertFalse(dataNullOwner.equals(data)); assertFalse(dataNullResource.equals(data)); @@ -464,7 +473,7 @@ public class SimpleLockManagerTest { String[] resources = {RESOURCE_A, RESOURCE_B}; - AtomicInteger nfail = new AtomicInteger(0); + final AtomicInteger nfail = new AtomicInteger(0); CountDownLatch stopper = new CountDownLatch(1); CountDownLatch completed = new CountDownLatch(nthreads); @@ -472,7 +481,7 @@ public class SimpleLockManagerTest { for (int x = 0; x < nthreads; ++x) { String owner = "owner." + x; - Thread t = new Thread(() -> { + Thread thread = new Thread(() -> { for (int y = 0; y < nlocks; ++y) { String res = resources[y % resources.length]; @@ -495,8 +504,8 @@ public class SimpleLockManagerTest { completed.countDown(); }); - t.setDaemon(true); - threads.add(t); + thread.setDaemon(true); + threads.add(thread); } // start the threads diff --git a/policy-core/src/test/java/org/onap/policy/drools/core/lock/TestUtils.java b/policy-core/src/test/java/org/onap/policy/drools/core/lock/TestUtils.java deleted file mode 100644 index f843f6ab..00000000 --- a/policy-core/src/test/java/org/onap/policy/drools/core/lock/TestUtils.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * ONAP - * ================================================================================ - * Copyright (C) 2018 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.core.lock; - -public class TestUtils { - - /** - * Invokes a function that is expected to throw an exception. - * - * @param clazz class of exception that is expected - * @param func - * @return - */ - public static T expectException(Class clazz, VoidFunction func) { - try { - func.apply(); - throw new AssertionError("missing exception"); - - } catch (Exception e) { - try { - return clazz.cast(e); - - } catch (ClassCastException e2) { - throw new AssertionError("incorrect exception type", e2); - } - } - } - - /** - * Void function that may throw an exception. - */ - @FunctionalInterface - public static interface VoidFunction { - - public void apply() throws Exception; - } -} diff --git a/policy-core/src/test/java/org/onap/policy/drools/core/lock/TestingUtils.java b/policy-core/src/test/java/org/onap/policy/drools/core/lock/TestingUtils.java new file mode 100644 index 00000000..17a11a09 --- /dev/null +++ b/policy-core/src/test/java/org/onap/policy/drools/core/lock/TestingUtils.java @@ -0,0 +1,55 @@ +/* + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 2018 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.core.lock; + +public class TestingUtils { + + /** + * Invokes a function that is expected to throw an exception. + * + * @param clazz class of exception that is expected + * @param func function + * @return object + */ + public static T expectException(Class clazz, VoidFunction func) { + try { + func.apply(); + throw new AssertionError("missing exception"); + + } catch (Exception e) { + try { + return clazz.cast(e); + + } catch (ClassCastException e2) { + throw new AssertionError("incorrect exception type", e2); + } + } + } + + /** + * Void function that may throw an exception. + */ + @FunctionalInterface + public static interface VoidFunction { + + public void apply() throws Exception; + } +} diff --git a/policy-core/src/test/java/org/onap/policy/drools/util/FeatureEnabledCheckerTest.java b/policy-core/src/test/java/org/onap/policy/drools/util/FeatureEnabledCheckerTest.java index cd79592f..c118b897 100644 --- a/policy-core/src/test/java/org/onap/policy/drools/util/FeatureEnabledCheckerTest.java +++ b/policy-core/src/test/java/org/onap/policy/drools/util/FeatureEnabledCheckerTest.java @@ -22,6 +22,7 @@ package org.onap.policy.drools.util; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; + import java.util.Properties; import org.junit.Test; diff --git a/policy-core/src/test/resources/META-INF/services/org.onap.policy.drools.core.PolicySessionFeatureAPI b/policy-core/src/test/resources/META-INF/services/org.onap.policy.drools.core.PolicySessionFeatureAPI index d6b088c3..6bc87035 100644 --- a/policy-core/src/test/resources/META-INF/services/org.onap.policy.drools.core.PolicySessionFeatureAPI +++ b/policy-core/src/test/resources/META-INF/services/org.onap.policy.drools.core.PolicySessionFeatureAPI @@ -1 +1 @@ -org.onap.policy.drools.core.TestPolicySessionFeatureAPI +org.onap.policy.drools.core.PolicySessionFeatureApiTest -- cgit 1.2.3-korg