Address sonar issues in drools-pdp 82/105182/3
authorJim Hahn <jrh3@att.com>
Mon, 6 Apr 2020 19:33:23 +0000 (15:33 -0400)
committerJim Hahn <jrh3@att.com>
Mon, 6 Apr 2020 23:30:02 +0000 (19:30 -0400)
Addressed the following sonar issues:
- add "final" to public static fields
- commented code; some were bogus - just updated the comments
  so sonar is happy
- use "{}" instead of string concatenation
- junit should assert something
- when using logger, invoke compute-intensive tasks conditionally
- use superclass name instead of subclass name to access static fields
- don't always return the same value
- remove "transient" from fields of classes that aren't Serializable
- don't nest try/catch blocks
- use appropriate class name in Logger.getLogger()
- use Predicate<T> instead of Function<T,Boolean>
- remove unused parameters from private methods
- either log or throw
- remove duplicate methods
- use remove() TLS instead of set(null)
- null check is implicit in instanceof check
- do something with return value
- don't use volatile
- don't return "null" list; used Optional instead
- add no-arg constructor to non-Serializable superclass
- add callSuper=true for EqualsAndHashCode
- don't declare "throws XXX" where XXX is a subclass of RuntimeException
- remove serialVersionUID field if the class isn't Serializable

Also addressed some eclipse warnings:
- unused fields
- suppress generic typic cast warnings

Issue-ID: POLICY-2305
Change-Id: I906d5bf71c1f86531423e23b3667a585cdba45e1
Signed-off-by: Jim Hahn <jrh3@att.com>
59 files changed:
api-server-pool-state-control/src/main/java/org/onap/policy/drools/control/api/DroolsPdpStateControlApiConstants.java
feature-active-standby-management/pom.xml
feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/ActiveStandbyFeature.java
feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/DroolsPdpsElectionHandler.java
feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/JpaDroolsPdpsConnector.java
feature-active-standby-management/src/test/java/org/onap/policy/drools/activestandby/PmStandbyStateChangeNotifierTest.java
feature-controller-logging/src/main/java/org/onap/policy/drools/controller/logging/ControllerLoggingFeature.java
feature-distributed-locking/src/main/java/org/onap/policy/distributed/locking/DistributedLockManager.java
feature-distributed-locking/src/test/java/org/onap/policy/distributed/locking/DistributedLockManagerTest.java
feature-healthcheck/src/main/java/org/onap/policy/drools/healthcheck/HealthCheckManager.java
feature-lifecycle/src/main/java/org/onap/policy/drools/lifecycle/LifecycleFeature.java
feature-lifecycle/src/main/java/org/onap/policy/drools/lifecycle/PolicyTypeDroolsController.java
feature-lifecycle/src/main/java/org/onap/policy/drools/lifecycle/PolicyTypeNativeArtifactController.java
feature-lifecycle/src/main/java/org/onap/policy/drools/lifecycle/PolicyTypeNativeDroolsController.java
feature-lifecycle/src/test/java/org/onap/policy/drools/lifecycle/LifecycleStateActivePoliciesTest.java
feature-lifecycle/src/test/java/org/onap/policy/drools/lifecycle/LifecycleStateActiveTest.java
feature-lifecycle/src/test/java/org/onap/policy/drools/lifecycle/PolicyTypeDroolsControllerTest.java
feature-pooling-dmaap/src/main/java/org/onap/policy/drools/pooling/PoolingFeature.java
feature-pooling-dmaap/src/main/java/org/onap/policy/drools/pooling/state/ActiveState.java
feature-pooling-dmaap/src/main/java/org/onap/policy/drools/pooling/state/FilterUtils.java
feature-pooling-dmaap/src/test/java/org/onap/policy/drools/pooling/DmaapManagerTest.java
feature-pooling-dmaap/src/test/java/org/onap/policy/drools/pooling/PoolingManagerImplTest.java
feature-pooling-dmaap/src/test/java/org/onap/policy/drools/pooling/PoolingPropertiesTest.java
feature-pooling-dmaap/src/test/java/org/onap/policy/drools/pooling/SerializerTest.java
feature-pooling-dmaap/src/test/java/org/onap/policy/drools/pooling/message/BucketAssignmentsTest.java
feature-pooling-dmaap/src/test/java/org/onap/policy/drools/pooling/state/StateTest.java
feature-session-persistence/pom.xml
feature-session-persistence/src/main/java/org/onap/policy/drools/persistence/PersistenceFeature.java
feature-session-persistence/src/test/java/org/onap/policy/drools/persistence/GenSchema.java
feature-session-persistence/src/test/java/org/onap/policy/drools/persistence/PersistenceFeatureTest.java
feature-simulators/src/main/java/org/onap/policy/drools/simulators/DMaaPSimulatorJaxRs.java
feature-state-management/src/main/java/org/onap/policy/drools/statemanagement/DroolsPdpIntegrityMonitor.java
feature-state-management/src/main/java/org/onap/policy/drools/statemanagement/RepositoryAudit.java
feature-state-management/src/main/java/org/onap/policy/drools/statemanagement/StateManagementFeature.java
feature-test-transaction/src/main/java/org/onap/policy/drools/testtransaction/TtControllerTask.java
policy-core/src/main/java/org/onap/policy/drools/core/PolicyContainer.java
policy-core/src/main/java/org/onap/policy/drools/core/PolicySession.java
policy-core/src/main/java/org/onap/policy/drools/core/lock/AlwaysFailLock.java
policy-core/src/main/java/org/onap/policy/drools/util/KieUtils.java
policy-core/src/test/java/org/onap/policy/drools/core/PolicySessionTest.java
policy-core/src/test/java/org/onap/policy/drools/core/lock/AlwaysFailLockTest.java
policy-core/src/test/java/org/onap/policy/drools/core/lock/LockImplTest.java
policy-core/src/test/java/org/onap/policy/drools/util/KieUtilsTest.java
policy-domains/src/main/java/org/onap/policy/drools/domain/models/artifact/NativeArtifactPolicy.java
policy-domains/src/main/java/org/onap/policy/drools/domain/models/controller/ControllerPolicy.java
policy-domains/src/main/java/org/onap/policy/drools/domain/models/controller/ControllerSinkTopic.java
policy-domains/src/main/java/org/onap/policy/drools/domain/models/controller/ControllerSourceTopic.java
policy-domains/src/main/java/org/onap/policy/drools/domain/models/controller/ControllerTopic.java
policy-domains/src/main/java/org/onap/policy/drools/domain/models/legacy/LegacyPolicy.java
policy-domains/src/main/java/org/onap/policy/drools/domain/models/operational/OperationalPolicy.java
policy-domains/src/main/java/org/onap/policy/drools/domain/models/operational/OperationalProperties.java
policy-domains/src/test/java/org/onap/policy/drools/domain/models/DroolsPolicyTest.java
policy-domains/src/test/java/org/onap/policy/drools/domain/models/legacy/LegacyPolicyTest.java
policy-domains/src/test/java/org/onap/policy/drools/domain/models/operational/OperationalPolicyTest.java
policy-utils/src/main/java/org/onap/policy/drools/policies/DomainMaker.java
policy-utils/src/main/java/org/onap/policy/drools/utils/PropertyUtil.java
policy-utils/src/test/java/org/onap/policy/drools/models/domains/a/DomainAPolicy.java
policy-utils/src/test/java/org/onap/policy/drools/policies/DomainMakerTest.java
pom.xml

index c82003f..df88bf3 100644 (file)
@@ -28,7 +28,7 @@ public class DroolsPdpStateControlApiConstants {
      * 'FeatureAPI.impl.getList()' returns an ordered list of objects
      * implementing the 'FeatureAPI' interface.
      */
-    public static OrderedServiceImpl<DroolsPdpStateControlApi> impl =
+    public static final OrderedServiceImpl<DroolsPdpStateControlApi> impl =
         new OrderedServiceImpl<>(DroolsPdpStateControlApi.class);
 
     private DroolsPdpStateControlApiConstants() {
index 8512868..00daa1f 100644 (file)
             <artifactId>junit</artifactId>
             <scope>test</scope>
         </dependency>
+        <dependency>
+            <groupId>org.assertj</groupId>
+            <artifactId>assertj-core</artifactId>
+            <scope>test</scope>
+        </dependency>
     </dependencies>
 
 </project>
index 91d30d7..2b75ea5 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * feature-active-standby-management
  * ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2020 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.
@@ -151,10 +151,8 @@ public class ActiveStandbyFeature implements ActiveStandbyFeatureApi,
          */
         DroolsPdp existingPdp = conn.getPdp(resourceName);
         if (existingPdp != null) {
-            logger.info("Found existing PDP record, pdpId="
-                    + existingPdp.getPdpId() + ", isDesignated="
-                    + existingPdp.isDesignated() + ", updatedDate="
-                    + existingPdp.getUpdatedDate());
+            logger.info("Found existing PDP record, pdpId={} isDesignated={}, updatedDate={}",
+                     existingPdp.getPdpId(), existingPdp.isDesignated(), existingPdp.getUpdatedDate());
             myPdp = existingPdp;
         }
 
index 37382e8..f51e071 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * feature-active-standby-management
  * ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2020 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.
@@ -92,7 +92,7 @@ public class DroolsPdpsElectionHandler implements ThreadRunningChecker {
         pdpdNowActive = null;
         pdpdLastActive = null;
         this.pdpsConnector = pdps;
-        DroolsPdpsElectionHandler.myPdp = myPdp;
+        setMyPdp(myPdp);
         this.isDesignated = false;
 
         // The interval between checks of the DesignationWaiter to be sure it is running.
@@ -152,6 +152,10 @@ public class DroolsPdpsElectionHandler implements ThreadRunningChecker {
         }
     }
 
+    private static void setMyPdp(DroolsPdp myPdp) {
+        DroolsPdpsElectionHandler.myPdp = myPdp;
+    }
+
     public static void setIsUnitTesting(boolean val) {
         isUnitTesting = val;
     }
@@ -403,9 +407,11 @@ public class DroolsPdpsElectionHandler implements ThreadRunningChecker {
         }
 
         private void demoteMyPdp(DroolsPdp pdp, String standbyStatus) throws Exception {
-            //Keep the order like this.  StateManagement is last since it
-            //triggers controller shutdown
-            //This will change isDesignated and it can enter another if(combination) below
+            /*
+             * Keep the order like this. StateManagement is last since it triggers
+             * controller shutdown. This will change isDesignated and it can enter another
+             * if-combination below
+             */
             pdpsConnector.standDownPdp(pdp.getPdpId());
             myPdp.setDesignated(false);
             isDesignated = false;
@@ -422,8 +428,8 @@ public class DroolsPdpsElectionHandler implements ThreadRunningChecker {
 
         private void pdpDesignatedNotCurrent(DroolsPdp pdp) {
             /*
-             * Changes designated to 0 but it is still potentially providing service
-             * Will affect isDesignated, so, it can enter an if(combination) below
+             * Changes designated to 0 but it is still potentially providing service.
+             * Will affect isDesignated, so, it can enter an if-combination below
              */
             pdpsConnector.standDownPdp(pdp.getPdpId());
 
@@ -614,7 +620,7 @@ public class DroolsPdpsElectionHandler implements ThreadRunningChecker {
             }
             waitTimerLastRunDate = currentTime.getDate();
             logger.debug("DesignatedWaiter.run (designatedPdp.getPdpId().equals(myPdp.getPdpId())) "
-                            + "waitTimerLastRunDate = " + waitTimerLastRunDate);
+                            + "waitTimerLastRunDate = {}", waitTimerLastRunDate);
             myPdp.setUpdatedDate(waitTimerLastRunDate);
             pdpsConnector.update(myPdp);
         }
@@ -786,7 +792,7 @@ public class DroolsPdpsElectionHandler implements ThreadRunningChecker {
                 // So, we must demote it
                 demoteMyPdp();
             }
-        } //end: for(DroolsPdp pdp : listOfDesignated)
+        }
 
         DroolsPdp lowestPriorityPdp = data.getLowestPriority();
 
index 1830d05..6e45696 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * feature-active-standby-management
  * ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2020 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.
@@ -566,7 +566,7 @@ public class JpaDroolsPdpsConnector implements DroolsPdpsConnector {
                 try {
                     em.getTransaction().rollback();
                 } catch (Exception e) {
-                    logger.error(method + ": Caught Exception attempting to rollback EntityTransaction,", e);
+                    logger.error("{}: Caught Exception attempting to rollback EntityTransaction", method, e);
                 }
             }
 
@@ -574,7 +574,7 @@ public class JpaDroolsPdpsConnector implements DroolsPdpsConnector {
             try {
                 em.close();
             } catch (Exception e) {
-                logger.error(method + ": Caught Exception attempting to close EntityManager, ", e);
+                logger.error("{}: Caught Exception attempting to close EntityManager", method, e);
             }
         }
     }
index 4a89d25..1cf20e2 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * ONAP
  * ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -20,6 +20,7 @@
 
 package org.onap.policy.drools.activestandby;
 
+import static org.assertj.core.api.Assertions.assertThatCode;
 import static org.junit.Assert.assertEquals;
 import static org.mockito.Matchers.any;
 import static org.mockito.Matchers.eq;
@@ -263,7 +264,7 @@ public class PmStandbyStateChangeNotifierTest {
     @Test
     public void testGetPolicyEngineManager() {
         // use real object with real method - no exception expected
-        new PmStandbyStateChangeNotifier().getPolicyEngineManager();
+        assertThatCode(() -> new PmStandbyStateChangeNotifier().getPolicyEngineManager()).doesNotThrowAnyException();
     }
 
     private class MyNotifier extends PmStandbyStateChangeNotifier {
index 5e90025..30f9076 100755 (executable)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * feature-controller-logging
  * ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019-2020 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.
@@ -51,6 +51,8 @@ import org.slf4j.LoggerFactory;
 public class ControllerLoggingFeature
                 implements PolicyEngineFeatureApi, DroolsControllerFeatureApi, PolicyControllerFeatureApi {
 
+    private static final String LINE_SEP = System.lineSeparator();
+
     @Override
     public int getSequenceNumber() {
         return 1000;
@@ -63,7 +65,7 @@ public class ControllerLoggingFeature
     @Override
     public boolean beforeOffer(PolicyController controller, CommInfrastructure protocol, String topic, String event) {
         Logger controllerLogger = LoggerFactory.getLogger(controller.getName());
-        controllerLogger.info("[IN|{}|{}]{}{}", protocol, topic, System.lineSeparator(), event);
+        controllerLogger.info("[IN|{}|{}]{}{}", protocol, topic, LINE_SEP, event);
         return false;
     }
 
@@ -78,7 +80,7 @@ public class ControllerLoggingFeature
             Logger controllerLogger = LoggerFactory
                             .getLogger(PolicyControllerConstants.getFactory().get(controller).getName());
             controllerLogger.info("[OUT|{}|{}]{}{}", sink.getTopicCommInfrastructure(), sink.getTopic(),
-                            System.lineSeparator(), json);
+                            LINE_SEP, json);
         }
         return false;
     }
@@ -92,7 +94,7 @@ public class ControllerLoggingFeature
                     String topic, String event) {
         for (ControllerConfiguration controller : configuration.getControllers()) {
             Logger controllerLogger = LoggerFactory.getLogger(controller.getName());
-            controllerLogger.info("[IN|{}|{}]{}{}", commType, topic, System.lineSeparator(), event);
+            controllerLogger.info("[IN|{}|{}]{}{}", commType, topic, LINE_SEP, event);
         }
         return false;
     }
index 528fa7c..c114d26 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * ONAP
  * ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019-2020 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.
@@ -341,7 +341,7 @@ public class DistributedLockManager extends LockManager<DistributedLockManager.D
             DistributedLock lock = lockref.get();
             if (lock != null) {
                 logger.debug("removed lock from map {}", lock);
-                lock.deny(DistributedLock.LOCK_LOST_MSG);
+                lock.deny(FeatureLockImpl.LOCK_LOST_MSG);
             }
         }
     }
index 065795b..5a0c6f7 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * ONAP
  * ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -21,6 +21,7 @@
 package org.onap.policy.distributed.locking;
 
 import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatCode;
 import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
 import static org.assertj.core.api.Assertions.assertThatThrownBy;
 import static org.junit.Assert.assertEquals;
@@ -348,7 +349,7 @@ public class DistributedLockManagerTest {
         // use a data source that throws an exception when closed
         feature = new InvalidDbLockingFeature(TRANSIENT);
 
-        shutdownFeature();
+        assertThatCode(() -> shutdownFeature()).doesNotThrowAnyException();
     }
 
     @Test
@@ -1438,7 +1439,7 @@ public class DistributedLockManagerTest {
         feature.beforeCreateLockManager(engine, new Properties());
         feature.afterStart(engine);
 
-        shutdownFeature();
+        assertThatCode(() -> shutdownFeature()).doesNotThrowAnyException();
     }
 
     /**
index f0b9313..38af2d8 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * ONAP
  * ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019-2020 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.
@@ -122,7 +122,7 @@ public class HealthCheckManager implements HealthCheck {
                 startServer(server);
             }
         } catch (Exception e) {
-            logger.warn("{}: cannot start {}", this, e);
+            logger.warn("{}: cannot start", this, e);
             return false;
         }
 
index 12828e0..003740c 100644 (file)
@@ -71,7 +71,7 @@ public class LifecycleFeature
 
     @Override
     public boolean beforeShutdown(PolicyEngine engine) {
-        return fsmShutdown(engine);
+        return fsmShutdown();
     }
 
     @Override
@@ -114,7 +114,7 @@ public class LifecycleFeature
         return false;
     }
 
-    private boolean fsmShutdown(PolicyEngine engine) {
+    private boolean fsmShutdown() {
         fsm.shutdown();
         return false;
     }
index 8dfbf2f..71e4072 100644 (file)
@@ -24,7 +24,7 @@ import com.fasterxml.jackson.annotation.JsonIgnore;
 import java.util.List;
 import java.util.Map;
 import java.util.concurrent.ConcurrentHashMap;
-import java.util.function.Function;
+import java.util.function.Predicate;
 import lombok.Getter;
 import lombok.NonNull;
 import org.apache.commons.lang3.StringUtils;
@@ -50,7 +50,7 @@ public class PolicyTypeDroolsController implements PolicyTypeController {
     protected static final ToscaPolicyTypeIdentifier compliantType =
         new ToscaPolicyTypeIdentifier("onap.policies.controlloop.operational.common.Drools", "1.0.0");
 
-    private static final Logger logger = LoggerFactory.getLogger(PolicyTypeController.class);
+    private static final Logger logger = LoggerFactory.getLogger(PolicyTypeDroolsController.class);
 
     @Getter
     protected final Map<String, PolicyController> controllers = new ConcurrentHashMap<>();
@@ -60,7 +60,7 @@ public class PolicyTypeDroolsController implements PolicyTypeController {
 
     @GsonJsonIgnore
     @JsonIgnore
-    protected final transient LifecycleFsm fsm;
+    protected final LifecycleFsm fsm;
 
     /**
      * Creates a Policy Type Drools Controller.
@@ -120,17 +120,12 @@ public class PolicyTypeDroolsController implements PolicyTypeController {
         return List.of(this.controllers.get(controllerName));
     }
 
-    private boolean perform(ToscaPolicy policy, Function<PolicyController, Boolean> operation) {
+    private boolean perform(ToscaPolicy policy, Predicate<PolicyController> operation) {
         try {
             List<PolicyController> selected = selectControllers(policy);
             boolean success = true;
             for (PolicyController controller : selected) {
-                try {
-                    success = operation.apply(controller) && success;
-                } catch (RuntimeException r) {
-                    logger.warn("invalid offer to controller: {}", controller);
-                    success = false;
-                }
+                success = modifyController(operation, controller) && success;
             }
             return success && !selected.isEmpty();
         } catch (CoderException e) {
@@ -139,6 +134,15 @@ public class PolicyTypeDroolsController implements PolicyTypeController {
         }
     }
 
+    private boolean modifyController(Predicate<PolicyController> operation, PolicyController controller) {
+        try {
+            return operation.test(controller);
+        } catch (RuntimeException r) {
+            logger.warn("invalid offer to controller: {}", controller);
+            return false;
+        }
+    }
+
     private List<PolicyController> selectControllers(ToscaPolicy policy) throws CoderException {
         List<PolicyController> selected;
         if (legacyType.equals(policyType)) {
index 113bb88..810c2ec 100644 (file)
@@ -44,7 +44,7 @@ public class PolicyTypeNativeArtifactController implements PolicyTypeController
 
     @GsonJsonIgnore
     @JsonIgnore
-    protected final transient LifecycleFsm fsm;
+    protected final LifecycleFsm fsm;
 
     public PolicyTypeNativeArtifactController(LifecycleFsm fsm, ToscaPolicyTypeIdentifier policyType) {
         this.policyType = policyType;
index e74b289..9a11955 100644 (file)
@@ -55,7 +55,7 @@ public class PolicyTypeNativeDroolsController implements PolicyTypeController {
 
     @GsonJsonIgnore
     @JsonIgnore
-    protected final transient LifecycleFsm fsm;
+    protected final LifecycleFsm fsm;
 
     public PolicyTypeNativeDroolsController(LifecycleFsm fsm, ToscaPolicyTypeIdentifier policyType) {
         this.policyType = policyType;
@@ -72,9 +72,10 @@ public class PolicyTypeNativeDroolsController implements PolicyTypeController {
 
         ControllerProperties controllerConfig = controllerPolicy.getProperties();
 
+        configControllerName(controllerConfig, controllerProps);
+
         boolean success =
-            configControllerName(controllerConfig, controllerProps)
-            && configControllerSources(controllerConfig, controllerProps)
+            configControllerSources(controllerConfig, controllerProps)
             && configControllerSinks(controllerConfig, controllerProps)
             && configControllerCustom(controllerConfig, controllerProps);
 
@@ -145,10 +146,9 @@ public class PolicyTypeNativeDroolsController implements PolicyTypeController {
         return nativePolicy;
     }
 
-    private boolean configControllerName(ControllerProperties controllerConfig, Properties controllerProps)  {
+    private void configControllerName(ControllerProperties controllerConfig, Properties controllerProps)  {
         controllerProps
                 .setProperty(DroolsPropertyConstants.PROPERTY_CONTROLLER_NAME, controllerConfig.getControllerName());
-        return true;
     }
 
     private boolean configControllerSources(ControllerProperties controllerConfig, Properties controllerProps) {
@@ -241,11 +241,10 @@ public class PolicyTypeNativeDroolsController implements PolicyTypeController {
 
     private boolean configControllerCustom(ControllerProperties controllerConfig, Properties controllerProps) {
         Map<String, String> configCustom = controllerConfig.getCustomConfig();
-        if (configCustom == null || configCustom.isEmpty()) {
-            return true;
+        if (configCustom != null && !configCustom.isEmpty()) {
+            controllerProps.putAll(configCustom);
         }
 
-        controllerProps.putAll(configCustom);
         return true;
     }
 
@@ -255,7 +254,7 @@ public class PolicyTypeNativeDroolsController implements PolicyTypeController {
 
     private List<String> sourceTopics(List<ControllerSourceTopic> sourceTopics) {
         if (sourceTopics == null) {
-            return Collections.EMPTY_LIST;
+            return Collections.emptyList();
         }
 
         return sourceTopics.stream()
@@ -265,7 +264,7 @@ public class PolicyTypeNativeDroolsController implements PolicyTypeController {
 
     private List<String> sinkTopics(List<ControllerSinkTopic> sinkTopics) {
         if (sinkTopics == null) {
-            return Collections.EMPTY_LIST;
+            return Collections.emptyList();
         }
 
         return sinkTopics.stream()
index 0e5937f..fdcaac5 100644 (file)
@@ -125,6 +125,7 @@ public class LifecycleStateActivePoliciesTest extends LifecycleStateRunningTest
         ToscaPolicy policyNativeArtifact =
                 getPolicyFromFile(EXAMPLE_NATIVE_ARTIFACT_POLICY_JSON, EXAMPLE_NATIVE_DROOLS_ARTIFACT_POLICY_NAME);
 
+        @SuppressWarnings("unchecked")
         Map<String, String> controllerMap =
                 (Map<String, String>) policyNativeArtifact.getProperties().get("controller");
         controllerMap.put("name", "xyz987");
@@ -239,7 +240,7 @@ public class LifecycleStateActivePoliciesTest extends LifecycleStateRunningTest
         assertEquals(policyNativeController, fsm.getPoliciesMap().get(policyNativeController.getIdentifier()));
         assertEquals(policyNativeFooController, fsm.getPoliciesMap().get(policyNativeFooController.getIdentifier()));
 
-        update.setPolicies(Collections.EMPTY_LIST);
+        update.setPolicies(Collections.emptyList());
         assertTrue(fsm.update(update));
         assertThatIllegalArgumentException().isThrownBy(() -> controllerSupport.getController().getDrools());
         assertNull(fsm.getPoliciesMap().get(policyNativeController.getIdentifier()));
index f370d0d..54f7d68 100644 (file)
@@ -155,7 +155,7 @@ public class LifecycleStateActiveTest extends LifecycleStateRunningTest {
 
         fsm.source.offer(new StandardCoder().encode(change));
         assertEquals(PdpState.ACTIVE, fsm.state());
-        assertEquals(LifecycleFsm.DEFAULT_PDP_GROUP, fsm.getGroup());;
+        assertEquals(LifecycleFsm.DEFAULT_PDP_GROUP, fsm.getGroup());
         assertNotEquals("b", fsm.getSubgroup());
 
         change.setName(fsm.getName());
index a56e250..bb4b563 100644 (file)
@@ -45,7 +45,6 @@ public class PolicyTypeDroolsControllerTest extends LifecycleStateRunningTest {
             "policies/vCPE.policy.operational.input.tosca.json";
 
     private ToscaPolicy policy;
-    private OperationalPolicy operationalPolicy;
     private PolicyTypeDroolsController controller;
 
     /**
@@ -55,7 +54,7 @@ public class PolicyTypeDroolsControllerTest extends LifecycleStateRunningTest {
     public void init() throws CoderException {
         fsm = makeFsmWithPseudoTime();
         policy = getExamplesPolicy(VCPE_OPERATIONAL_DROOLS_POLICY_JSON, OP_POLICY_NAME_VCPE);
-        operationalPolicy = fsm.getDomainMaker().convertTo(policy, OperationalPolicy.class);
+        fsm.getDomainMaker().convertTo(policy, OperationalPolicy.class);
         controller = new PolicyTypeDroolsController(
             fsm, PolicyTypeDroolsController.compliantType, controllerSupport.getController());
 
index da8a918..00b7a21 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * ONAP
  * ================================================================================
- * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-2020 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.
@@ -158,7 +158,7 @@ public class PoolingFeature implements PolicyEngineFeatureApi, PolicyControllerF
                 ctlr2pool.computeIfAbsent(name, xxx -> makeManager(host, controller, props, activeLatch));
 
             } catch (PropertyException e) {
-                logger.error("pooling disabled due to exception for {}", name, e);
+                logger.error("pooling disabled due to exception for {}", name);
                 throw new PoolingFeatureRtException(e);
             }
 
@@ -196,12 +196,15 @@ public class PoolingFeature implements PolicyEngineFeatureApi, PolicyControllerF
 
     @Override
     public boolean afterShutdown(PolicyController controller) {
-        deleteManager(controller);
-        return false;
+        return commonShutdown(controller);
     }
 
     @Override
     public boolean afterHalt(PolicyController controller) {
+        return commonShutdown(controller);
+    }
+
+    private boolean commonShutdown(PolicyController controller) {
         deleteManager(controller);
         return false;
     }
@@ -284,7 +287,7 @@ public class PoolingFeature implements PolicyEngineFeatureApi, PolicyControllerF
             boolean success) {
 
         // clear any stored arguments
-        offerArgs.set(null);
+        offerArgs.remove();
 
         return false;
     }
index 58205dd..c5ee2ae 100644 (file)
@@ -2,14 +2,14 @@
  * ============LICENSE_START=======================================================
  * ONAP
  * ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018, 2020 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.
@@ -67,7 +67,7 @@ public class ActiveState extends ProcessingState {
 
     /**
      * Constructor.
-     * 
+     *
      * @param mgr pooling manager
      */
     public ActiveState(PoolingManager mgr) {
@@ -97,7 +97,7 @@ public class ActiveState extends ProcessingState {
             // wrapped around - successor is the first host in the set
             succHost = assigned.first();
         }
-        logger.info("this host's successor is {} on topic {}", succHost, getTopic());        
+        logger.info("this host's successor is {} on topic {}", succHost, getTopic());
 
         if ((predHost = assigned.lower(getHost())) == null) {
             // wrapped around - predecessor is the last host in the set
@@ -185,7 +185,6 @@ public class ActiveState extends ProcessingState {
 
         if (src == null) {
             logger.warn("Heartbeat message has no source on topic {}", getTopic());
-            return null;
 
         } else if (src.equals(getHost())) {
             logger.info("saw my heartbeat on topic {}", getTopic());
@@ -194,7 +193,7 @@ public class ActiveState extends ProcessingState {
         } else if (src.equals(predHost)) {
             logger.info("saw heartbeat from {} on topic {}", src, getTopic());
             predHeartbeatSeen = true;
-            
+
         } else {
             logger.info("ignored heartbeat message from {} on topic {}", src, getTopic());
         }
@@ -239,10 +238,10 @@ public class ActiveState extends ProcessingState {
         } else if (isLeader() || (predHost.equals(src) && predHost.equals(assigned.first()))) {
             /*
              * Case 1: We are the leader.
-             * 
+             *
              * Case 2: Our predecessor was the leader and it has gone offline - we should
              * become the leader.
-             * 
+             *
              * In either case, we are now the leader and we must re-balance the buckets
              * since one of the hosts has gone offline.
              */
index 1616f03..5b7012d 100644 (file)
@@ -2,14 +2,14 @@
  * ============LICENSE_START=======================================================
  * ONAP
  * ================================================================================
- * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-2020 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.
@@ -52,7 +52,7 @@ public class FilterUtils {
 
     /**
      * Makes a filter that verifies that a field equals a value.
-     * 
+     *
      * @param field name of the field to check
      * @param value desired value
      * @return a map representing an "equals" filter
@@ -68,11 +68,11 @@ public class FilterUtils {
 
     /**
      * Makes an "and" filter, where all of the items must be true.
-     * 
+     *
      * @param items items to be checked
      * @return an "and" filter
      */
-    public static Map<String, Object> makeAnd(Map<String, Object>... items) {
+    public static Map<String, Object> makeAnd(@SuppressWarnings("unchecked") Map<String, Object>... items) {
         Map<String, Object> map = new TreeMap<>();
         map.put(JSON_CLASS, CLASS_AND);
         map.put(JSON_FILTERS, items);
@@ -82,11 +82,11 @@ public class FilterUtils {
 
     /**
      * Makes an "or" filter, where at least one of the items must be true.
-     * 
+     *
      * @param items items to be checked
      * @return an "or" filter
      */
-    public static Map<String, Object> makeOr(Map<String, Object>... items) {
+    public static Map<String, Object> makeOr(@SuppressWarnings("unchecked") Map<String, Object>... items) {
         Map<String, Object> map = new TreeMap<>();
         map.put(JSON_CLASS, CLASS_OR);
         map.put(JSON_FILTERS, items);
index 69896d3..d5b397a 100644 (file)
@@ -2,14 +2,14 @@
  * ============LICENSE_START=======================================================
  * ONAP
  * ================================================================================
- * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-2020 AT&T Intellectual Property. All rights reserved.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
- * 
+ *
  *      http://www.apache.org/licenses/LICENSE-2.0
- * 
+ *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -20,6 +20,7 @@
 
 package org.onap.policy.drools.pooling;
 
+import static org.assertj.core.api.Assertions.assertThatCode;
 import static org.assertj.core.api.Assertions.assertThatThrownBy;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
@@ -48,7 +49,7 @@ public class DmaapManagerTest {
     private static final String MY_TOPIC = "my.topic";
     private static final String MSG = "a message";
     private static final String FILTER = "a filter";
-    
+
     private TopicListener listener;
     private FilterableTopicSource source;
     private boolean gotSources;
@@ -58,7 +59,7 @@ public class DmaapManagerTest {
 
     /**
      * Setup.
-     * 
+     *
      * @throws Exception throws an exception
      */
     @Before
@@ -116,11 +117,6 @@ public class DmaapManagerTest {
         assertEquals(MY_TOPIC, mgr.getTopic());
     }
 
-    @Test
-    public void testFindTopicSource() {
-        // getting here means it worked
-    }
-
     @Test(expected = PoolingFeatureException.class)
     public void testFindTopicSource_NotFilterableTopicSource() throws PoolingFeatureException {
 
@@ -158,11 +154,6 @@ public class DmaapManagerTest {
         };
     }
 
-    @Test
-    public void testFindTopicSink() {
-        // getting here means it worked
-    }
-
     @Test(expected = PoolingFeatureException.class)
     public void testFindTopicSink_NotFound() throws PoolingFeatureException {
         // one item in list, and its topic doesn't match
@@ -187,7 +178,7 @@ public class DmaapManagerTest {
 
     @Test
     public void testStartPublisher() throws PoolingFeatureException {
-        
+
         mgr.startPublisher();
 
         // restart should have no effect
@@ -210,7 +201,7 @@ public class DmaapManagerTest {
         mgr.stopPublisher(0);
 
         // re-stopping should have no effect
-        mgr.stopPublisher(0);
+        assertThatCode(() -> mgr.stopPublisher(0)).doesNotThrowAnyException();
     }
 
     @Test
@@ -285,7 +276,7 @@ public class DmaapManagerTest {
 
     @Test
     public void testSetFilter() throws PoolingFeatureException {
-        mgr.setFilter(FILTER);
+        assertThatCode(() -> mgr.setFilter(FILTER)).doesNotThrowAnyException();
     }
 
     @Test(expected = PoolingFeatureException.class)
@@ -337,7 +328,7 @@ public class DmaapManagerTest {
 
         mgr.publish(MSG);
     }
-    
+
     /**
      * Manager with overrides.
      */
@@ -350,7 +341,7 @@ public class DmaapManagerTest {
         @Override
         protected List<TopicSource> getTopicSources() {
             gotSources = true;
-            
+
             // three sources, with the desired one in the middle
             return Arrays.asList(mock(TopicSource.class), source, mock(TopicSource.class));
         }
@@ -358,7 +349,7 @@ public class DmaapManagerTest {
         @Override
         protected List<TopicSink> getTopicSinks() {
             gotSinks = true;
-            
+
             // three sinks, with the desired one in the middle
             return Arrays.asList(mock(TopicSink.class), sink, mock(TopicSink.class));
         }
index 5293b79..bd3d90b 100644 (file)
@@ -2,14 +2,14 @@
  * ============LICENSE_START=======================================================
  * ONAP
  * ================================================================================
- * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-2020 AT&T Intellectual Property. All rights reserved.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
- * 
+ *
  *      http://www.apache.org/licenses/LICENSE-2.0
- * 
+ *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -20,6 +20,7 @@
 
 package org.onap.policy.drools.pooling;
 
+import static org.assertj.core.api.Assertions.assertThatCode;
 import static org.assertj.core.api.Assertions.assertThatThrownBy;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
@@ -286,7 +287,7 @@ public class PoolingManagerImplTest {
         Forward msg = new Forward(mgr.getHost(), CommInfrastructure.UEB, TOPIC2, THE_EVENT, REQUEST_ID);
         mgr.handle(msg);
         verify(dmaap, times(START_PUB + 1)).publish(any());
-        
+
         mgr.beforeStop();
 
         verify(dmaap).stopConsumer(mgr);
@@ -453,7 +454,7 @@ public class PoolingManagerImplTest {
         doThrow(new PoolingFeatureException()).when(dmaap).setFilter(any());
 
         // start should invoke setFilter()
-        startMgr();
+        assertThatCode(() -> startMgr()).doesNotThrowAnyException();
 
         // no exception, means success
     }
@@ -552,7 +553,7 @@ public class PoolingManagerImplTest {
         // generate exception
         doThrow(new PoolingFeatureException()).when(dmaap).publish(any());
 
-        mgr.publish(Message.ADMIN, new Offline(mgr.getHost()));
+        assertThatCode(() -> mgr.publish(Message.ADMIN, new Offline(mgr.getHost()))).doesNotThrowAnyException();
     }
 
     @Test
@@ -578,7 +579,7 @@ public class PoolingManagerImplTest {
     public void testOnTopicEvent_NullEvent() throws Exception {
         startMgr();
 
-        mgr.onTopicEvent(CommInfrastructure.UEB, TOPIC2, null);
+        assertThatCode(() -> mgr.onTopicEvent(CommInfrastructure.UEB, TOPIC2, null)).doesNotThrowAnyException();
     }
 
     @Test
@@ -780,7 +781,7 @@ public class PoolingManagerImplTest {
                 return false;
             }
         };
-        
+
         startMgr();
 
         when(controller.isLocked()).thenReturn(true);
@@ -801,7 +802,7 @@ public class PoolingManagerImplTest {
                 throw new UnsupportedOperationException();
             }
         };
-        
+
         startMgr();
 
         when(controller.isLocked()).thenReturn(true);
@@ -821,7 +822,7 @@ public class PoolingManagerImplTest {
                 throw new IllegalArgumentException();
             }
         };
-        
+
         startMgr();
 
         when(controller.isLocked()).thenReturn(true);
@@ -841,7 +842,7 @@ public class PoolingManagerImplTest {
                 throw new IllegalStateException();
             }
         };
-        
+
         startMgr();
 
         when(controller.isLocked()).thenReturn(true);
@@ -867,19 +868,19 @@ public class PoolingManagerImplTest {
     @Test
     public void testMakeForward() throws Exception {
         startMgr();
-        
+
         // route the message to another host
         mgr.startDistributing(makeAssignments(false));
 
         assertTrue(mgr.beforeInsert(CommInfrastructure.UEB, TOPIC2, THE_EVENT, DECODED_EVENT));
-        
+
         verify(dmaap, times(START_PUB + 1)).publish(any());
     }
 
     @Test
     public void testMakeForward_InvalidMsg() throws Exception {
         startMgr();
-        
+
         // route the message to another host
         mgr.startDistributing(makeAssignments(false));
 
@@ -1136,10 +1137,10 @@ public class PoolingManagerImplTest {
      * Configure the mock controller to act like a real controller, invoking beforeOffer
      * and then beforeInsert, so we can make sure they pass through. We'll keep count to
      * ensure we don't get into infinite recursion.
-     * 
+     *
      * @param invokeBeforeInsert {@code true} if beforeInsert() should be invoked,
      *        {@code false} if it should be skipped
-     * 
+     *
      * @return a latch that will be counted down if both beforeXxx() methods return false
      */
     private CountDownLatch catchRecursion(boolean invokeBeforeInsert) {
@@ -1176,7 +1177,7 @@ public class PoolingManagerImplTest {
 
     /**
      * Makes an assignment with two buckets.
-     * 
+     *
      * @param sameHost {@code true} if the {@link #REQUEST_ID} should hash to the
      *        manager's bucket, {@code false} if it should hash to the other host's bucket
      * @return a new bucket assignment
@@ -1198,7 +1199,7 @@ public class PoolingManagerImplTest {
 
     /**
      * Invokes methods necessary to start the manager.
-     * 
+     *
      * @throws PoolingFeatureException if an error occurs
      */
     private void startMgr() throws PoolingFeatureException {
index cc716a2..b15908d 100644 (file)
@@ -2,14 +2,14 @@
  * ============LICENSE_START=======================================================
  * ONAP
  * ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018, 2020 AT&T Intellectual Property. All rights reserved.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
- * 
+ *
  *      http://www.apache.org/licenses/LICENSE-2.0
- * 
+ *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -20,6 +20,7 @@
 
 package org.onap.policy.drools.pooling;
 
+import static org.assertj.core.api.Assertions.assertThatCode;
 import static org.junit.Assert.assertEquals;
 import static org.onap.policy.drools.pooling.PoolingProperties.ACTIVE_HEARTBEAT_MS;
 import static org.onap.policy.drools.pooling.PoolingProperties.FEATURE_ENABLED;
@@ -60,7 +61,7 @@ public class PoolingPropertiesTest {
 
     /**
      * Setup.
-     * 
+     *
      * @throws Exception throws an exception
      */
     @Before
@@ -73,7 +74,7 @@ public class PoolingPropertiesTest {
     @Test
     public void testPoolingProperties() throws PropertyException {
         // ensure no exceptions
-        new PoolingProperties(CONTROLLER, plain);
+        assertThatCode(() -> new PoolingProperties(CONTROLLER, plain)).doesNotThrowAnyException();
     }
 
     @Test
@@ -130,7 +131,7 @@ public class PoolingPropertiesTest {
      * Tests a particular property. Verifies that the correct value is returned if the
      * specialized property has a value or the property has no value. Also verifies that
      * the property name can be generalized.
-     * 
+     *
      * @param propnm name of the property of interest
      * @param specValue expected specialized value
      * @param dfltValue expected default value
@@ -156,7 +157,7 @@ public class PoolingPropertiesTest {
     /**
      * Makes a set of properties, where all of the properties are specialized for the
      * controller.
-     * 
+     *
      * @return a new property set
      */
     private Properties makeProperties() {
@@ -178,7 +179,7 @@ public class PoolingPropertiesTest {
 
     /**
      * Embeds a specializer within a property name, after the prefix.
-     * 
+     *
      * @param propnm property name into which it should be embedded
      * @param spec specializer to be embedded
      * @return the property name, with the specializer embedded within it
index b51a18f..09e8385 100644 (file)
@@ -2,14 +2,14 @@
  * ============LICENSE_START=======================================================
  * ONAP
  * ================================================================================
- * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-2020 AT&T Intellectual Property. All rights reserved.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
- * 
+ *
  *      http://www.apache.org/licenses/LICENSE-2.0
- * 
+ *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -20,6 +20,7 @@
 
 package org.onap.policy.drools.pooling;
 
+import static org.assertj.core.api.Assertions.assertThatCode;
 import static org.assertj.core.api.Assertions.assertThatThrownBy;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
@@ -39,7 +40,7 @@ public class SerializerTest {
 
     @Test
     public void testSerializer() {
-        new Serializer();
+        assertThatCode(() -> new Serializer()).doesNotThrowAnyException();
     }
 
     @Test
index 5788141..50cab78 100644 (file)
@@ -2,14 +2,14 @@
  * ============LICENSE_START=======================================================
  * ONAP
  * ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018, 2020 AT&T Intellectual Property. All rights reserved.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
- * 
+ *
  *      http://www.apache.org/licenses/LICENSE-2.0
- * 
+ *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -20,6 +20,7 @@
 
 package org.onap.policy.drools.pooling.message;
 
+import static org.assertj.core.api.Assertions.assertThatCode;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertNotNull;
@@ -37,7 +38,7 @@ public class BucketAssignmentsTest {
 
     @Test
     public void testBucketAssignments() {
-        new BucketAssignments();
+        assertThatCode(() -> new BucketAssignments()).doesNotThrowAnyException();
     }
 
     @Test
@@ -172,7 +173,7 @@ public class BucketAssignmentsTest {
 
     /**
      * Gets the hosts, sorted, so that the order is predictable.
-     * 
+     *
      * @param asgn assignment whose hosts are to be retrieved
      * @return a new, sorted set of hosts
      */
@@ -201,7 +202,7 @@ public class BucketAssignmentsTest {
         /*
          * get assignments for consecutive integers, including negative numbers and
          * numbers extending past the length of the array.
-         * 
+         *
          */
         TreeSet<String> seen = new TreeSet<>();
         for (int x = -1; x < arr.length + 2; ++x) {
@@ -342,7 +343,7 @@ public class BucketAssignmentsTest {
 
     /**
      * Expects an exception when checkValidity() is called.
-     * 
+     *
      * @param asgn assignments to be checked
      */
     private void expectException(BucketAssignments asgn) {
index 65d9ee3..5284ed1 100644 (file)
@@ -2,14 +2,14 @@
  * ============LICENSE_START=======================================================
  * ONAP
  * ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018, 2020 AT&T Intellectual Property. All rights reserved.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
- * 
+ *
  *      http://www.apache.org/licenses/LICENSE-2.0
- * 
+ *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -20,6 +20,7 @@
 
 package org.onap.policy.drools.pooling.state;
 
+import static org.assertj.core.api.Assertions.assertThatCode;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertNull;
@@ -136,7 +137,7 @@ public class StateTest extends SupportBasicStateTester {
 
     @Test
     public void testStart() {
-        state.start();
+        assertThatCode(() -> state.start()).doesNotThrowAnyException();
     }
 
     @Test
index 7cdb0e4..0b5e537 100644 (file)
             <artifactId>junit</artifactId>
             <scope>test</scope>
         </dependency>
+        <dependency>
+            <groupId>org.assertj</groupId>
+            <artifactId>assertj-core</artifactId>
+            <scope>test</scope>
+        </dependency>
     </dependencies>
 </project>
index cc82690..a496588 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * feature-session-persistence
  * ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2020 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.
@@ -38,6 +38,7 @@ import javax.transaction.UserTransaction;
 
 import org.apache.commons.dbcp2.BasicDataSource;
 import org.apache.commons.dbcp2.BasicDataSourceFactory;
+import org.hibernate.cfg.AvailableSettings;
 import org.kie.api.KieServices;
 import org.kie.api.runtime.Environment;
 import org.kie.api.runtime.EnvironmentName;
@@ -94,7 +95,7 @@ public class PersistenceFeature implements PolicySessionFeatureApi, PolicyEngine
 
         Object rval = policyContainer.getAdjunct(this);
 
-        if (rval == null || !(rval instanceof ContainerAdjunct)) {
+        if (!(rval instanceof ContainerAdjunct)) {
             // adjunct does not exist, or has the wrong type (should never
             // happen)
             rval = new ContainerAdjunct(policyContainer);
@@ -199,11 +200,7 @@ public class PersistenceFeature implements PolicySessionFeatureApi, PolicyEngine
      **/
     @Override
     public boolean beforeStart(PolicyEngine engine) {
-        synchronized (cleanupLock) {
-            sessInfoCleaned = false;
-        }
-
-        return false;
+        return cleanup();
     }
 
     /**
@@ -211,6 +208,10 @@ public class PersistenceFeature implements PolicySessionFeatureApi, PolicyEngine
      **/
     @Override
     public boolean beforeActivate(PolicyEngine engine) {
+        return cleanup();
+    }
+
+    private boolean cleanup() {
         synchronized (cleanupLock) {
             sessInfoCleaned = false;
         }
@@ -641,7 +642,7 @@ public class PersistenceFeature implements PolicySessionFeatureApi, PolicyEngine
                 try {
                     minSleepTime = Math.max(1, Integer.valueOf(sleepTimeString));
                 } catch (Exception e) {
-                    logger.error(sleepTimeString + ": Illegal value for 'minSleepTime'", e);
+                    logger.error("{}: Illegal value for 'minSleepTime'", sleepTimeString, e);
                 }
             }
 
@@ -652,18 +653,14 @@ public class PersistenceFeature implements PolicySessionFeatureApi, PolicyEngine
                 try {
                     maxSleepTime = Math.max(1, Integer.valueOf(sleepTimeString));
                 } catch (Exception e) {
-                    logger.error(sleepTimeString + ": Illegal value for 'maxSleepTime'", e);
+                    logger.error("{}: Illegal value for 'maxSleepTime'", sleepTimeString, e);
                 }
             }
 
             // swap values if needed
             if (minSleepTime > maxSleepTime) {
-                logger.error(
-                        "minSleepTime("
-                                + minSleepTime
-                                + ") is greater than maxSleepTime("
-                                + maxSleepTime
-                                + ") -- swapping");
+                logger.error("minSleepTime({}) is greater than maxSleepTime({}) -- swapping", minSleepTime,
+                                maxSleepTime);
                 long tmp = minSleepTime;
                 minSleepTime = maxSleepTime;
                 maxSleepTime = tmp;
@@ -791,7 +788,7 @@ public class PersistenceFeature implements PolicySessionFeatureApi, PolicyEngine
         public DsEmf(BasicDataSource bds) {
             try {
                 Map<String, Object> props = new HashMap<>();
-                props.put(org.hibernate.cfg.Environment.JPA_JTA_DATASOURCE, bds);
+                props.put(AvailableSettings.JPA_JTA_DATASOURCE, bds);
 
                 this.bds = bds;
                 this.emf = makeEntMgrFact(props);
index 4091831..31fcfa8 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * feature-session-persistence
  * ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2020 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,10 +22,7 @@ package org.onap.policy.drools.persistence;
 
 import java.util.HashMap;
 import java.util.Map;
-
-import javax.persistence.EntityManagerFactory;
 import javax.persistence.Persistence;
-
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
index 97b6874..20ae13d 100644 (file)
@@ -20,6 +20,7 @@
 
 package org.onap.policy.drools.persistence;
 
+import static org.assertj.core.api.Assertions.assertThatCode;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertNotNull;
@@ -128,7 +129,7 @@ public class PersistenceFeatureTest {
 
     /**
      * Setup before class.
-     * 
+     *
      * @throws Exception exception
      */
     @BeforeClass
@@ -148,7 +149,7 @@ public class PersistenceFeatureTest {
 
     /**
      * Setup.
-     * 
+     *
      * @throws Exception exception
      */
     @Before
@@ -310,7 +311,7 @@ public class PersistenceFeatureTest {
     public void testActivatePolicySession() throws Exception {
         setUpKie(MY_SESS_NAME, 999L, true);
         final PreparedStatement ps = mockDbConn(5);
-        
+
         feat.beforeActivate(null);
 
         KieSession session = feat.activatePolicySession(polcont, MY_SESS_NAME, MY_KIE_BASE);
@@ -432,14 +433,14 @@ public class PersistenceFeatureTest {
     public void testConfigureKieEnv_RtEx() throws Exception {
         setUpKie(MY_SESS_NAME, 999L, false);
         mockDbConn(5);
-        
+
         feat = new PersistenceFeatureMockDb() {
             @Override
             protected UserTransaction getUserTrans() {
                 throw new IllegalArgumentException(EXPECTED);
             }
         };
-        
+
         feat.globalInit(null, SRC_TEST_RESOURCES);
 
         try {
@@ -457,7 +458,7 @@ public class PersistenceFeatureTest {
     public void testLoadKieSession() throws Exception {
         setUpKie(MY_SESS_NAME, 999L, true);
         mockDbConn(5);
-        
+
         KieSession session = feat.activatePolicySession(polcont, MY_SESS_NAME, MY_KIE_BASE);
 
         verify(kiestore).loadKieSession(999L, kiebase, kiecfg, kieenv);
@@ -562,7 +563,7 @@ public class PersistenceFeatureTest {
 
         final ArgumentCaptor<PersistenceFeature.ContainerAdjunct> adjcap =
                 ArgumentCaptor.forClass(PersistenceFeature.ContainerAdjunct.class);
-        
+
         verify(polcont).setAdjunct(any(), adjcap.capture());
 
         when(polcont.getAdjunct(any())).thenReturn(adjcap.getValue());
@@ -579,7 +580,7 @@ public class PersistenceFeatureTest {
     public void testDisposeKieSession_NoAdjunct() throws Exception {
         feat.globalInit(null, SRC_TEST_RESOURCES);
 
-        feat.disposeKieSession(polsess);
+        assertThatCode(() -> feat.disposeKieSession(polsess)).doesNotThrowAnyException();
     }
 
     @Test
@@ -593,7 +594,7 @@ public class PersistenceFeatureTest {
 
         final ArgumentCaptor<PersistenceFeature.ContainerAdjunct> adjcap =
                 ArgumentCaptor.forClass(PersistenceFeature.ContainerAdjunct.class);
-        
+
         verify(polcont).setAdjunct(any(), adjcap.capture());
 
         when(polcont.getAdjunct(any())).thenReturn(adjcap.getValue());
@@ -617,7 +618,7 @@ public class PersistenceFeatureTest {
 
         final ArgumentCaptor<PersistenceFeature.ContainerAdjunct> adjcap =
                 ArgumentCaptor.forClass(PersistenceFeature.ContainerAdjunct.class);
-        
+
         verify(polcont).setAdjunct(any(), adjcap.capture());
 
         when(polcont.getAdjunct(any())).thenReturn(adjcap.getValue());
@@ -634,7 +635,7 @@ public class PersistenceFeatureTest {
     public void testDestroyKieSession_NoAdjunct() throws Exception {
         feat.globalInit(null, SRC_TEST_RESOURCES);
 
-        feat.destroyKieSession(polsess);
+        assertThatCode(() -> feat.destroyKieSession(polsess)).doesNotThrowAnyException();
     }
 
     @Test
@@ -648,7 +649,7 @@ public class PersistenceFeatureTest {
 
         final ArgumentCaptor<PersistenceFeature.ContainerAdjunct> adjcap =
                 ArgumentCaptor.forClass(PersistenceFeature.ContainerAdjunct.class);
-        
+
         verify(polcont).setAdjunct(any(), adjcap.capture());
 
         when(polcont.getAdjunct(any())).thenReturn(adjcap.getValue());
@@ -767,7 +768,7 @@ public class PersistenceFeatureTest {
     @Test
     public void testGetPersistenceTimeout_Invalid() throws Exception {
         props.setProperty(DroolsPersistenceProperties.DB_SESSIONINFO_TIMEOUT, "abc");
-        
+
         setUpKie(MY_SESS_NAME, 999L, true);
         final PreparedStatement s = mockDbConn(0);
 
@@ -869,7 +870,7 @@ public class PersistenceFeatureTest {
     @Test
     public void testCleanUpSessionInfo_NoUrl() throws Exception {
         props.remove(DroolsPersistenceProperties.DB_URL);
-        
+
         setUpKie(MY_SESS_NAME, 999L, true);
         final PreparedStatement statement = mockDbConn(0);
 
@@ -886,7 +887,7 @@ public class PersistenceFeatureTest {
     @Test
     public void testCleanUpSessionInfo_NoUser() throws Exception {
         props.remove(DroolsPersistenceProperties.DB_USER);
-        
+
         setUpKie(MY_SESS_NAME, 999L, true);
         final PreparedStatement statement = mockDbConn(0);
 
@@ -945,7 +946,7 @@ public class PersistenceFeatureTest {
         feat.activatePolicySession(polcont, MY_SESS_NAME, MY_KIE_BASE);
 
         final ArgumentCaptor<DroolsSession> sesscap = ArgumentCaptor.forClass(DroolsSession.class);
-        
+
         verify(jpa).replace(sesscap.capture());
 
         assertEquals(MY_SESS_NAME, sesscap.getValue().getSessionName());
@@ -1312,7 +1313,7 @@ public class PersistenceFeatureTest {
 
         return statement;
     }
-    
+
     /**
      * Feature with a mock DB.
      */
@@ -1323,7 +1324,7 @@ public class PersistenceFeatureTest {
             return bds;
         }
     }
-    
+
     /**
      * Feature supporting newKieSession.
      */
@@ -1341,7 +1342,7 @@ public class PersistenceFeatureTest {
             return jpa;
         }
     }
-    
+
     /**
      * Feature with overrides.
      */
@@ -1364,7 +1365,7 @@ public class PersistenceFeatureTest {
             return null;
         }
     }
-    
+
     /**
      * Feature with <i>some</i> overrides.
      */
index dd0fb7b..819c5f5 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * feature-simulators
  * ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2020 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.
@@ -129,7 +129,7 @@ public class DMaaPSimulatorJaxRs {
     @Consumes(MediaType.TEXT_PLAIN)
     public String publish(@PathParam("topicName") String topicName, String body) {
         BlockingQueue<String> queue = queues.computeIfAbsent(topicName, entry -> new LinkedBlockingQueue<>());
-        queue.offer(body);
+        queue.add(body);
 
         return "";
     }
index 2fa54e6..2252a0f 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * feature-state-management
  * ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2020 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.
@@ -172,11 +172,10 @@ public class DroolsPdpIntegrityMonitor extends IntegrityMonitor {
         try {
             logger.info("init: Starting HTTP server, addr= {}:{}", testHost, testPort);
 
-            IntegrityMonitorRestServer server = new IntegrityMonitorRestServer();
-            server.init(properties);
+            new IntegrityMonitorRestServer(properties);
 
         } catch (Exception e) {
-            logger.error("init: Caught Exception attempting to start server on testPort= {} message:", testPort, e);
+            logger.error("init: Caught Exception attempting to start server on testPort={}", testPort);
             throw new IntegrityMonitorException(e);
         }
     }
@@ -360,10 +359,10 @@ public class DroolsPdpIntegrityMonitor extends IntegrityMonitor {
     }
 
     public static class IntegrityMonitorRestServer implements Startable {
-        protected volatile HttpServletServer server = null;
-        protected volatile Properties integrityMonitorRestServerProperties = null;
+        protected HttpServletServer server = null;
+        protected final Properties integrityMonitorRestServerProperties;
 
-        public void init(Properties props) {
+        public IntegrityMonitorRestServer(Properties props) {
             this.integrityMonitorRestServerProperties = props;
             this.start();
         }
index 66982ef..bf6b2e7 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * feature-state-management
  * ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2020 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.
@@ -268,8 +268,8 @@ public class RepositoryAudit extends DroolsPdpIntegrityMonitor.AuditBase {
             repositoryPassword = getProperty("audit.password", true);
 
             logger.debug("Nexus Repository Information retrieved from 'IntegrityMonitorProperties':");
-            logger.debug("repositoryId: " + repositoryId);
-            logger.debug("repositoryUrl: " + repositoryUrl);
+            logger.debug("repositoryId: {}", repositoryId);
+            logger.debug("repositoryUrl: {}", repositoryUrl);
 
             // Setting upload to be false so that files can no longer be created/deleted
             upload = false;
@@ -419,10 +419,10 @@ public class RepositoryAudit extends DroolsPdpIntegrityMonitor.AuditBase {
                         .resolve(artifact.artifactId + "-" + artifact.version + "." + artifact.type).toFile()
                         .exists()) {
                     // artifact exists, as expected
-                    logger.info("RepositoryAudit: {} : exists", artifact.toString());
+                    logger.info("RepositoryAudit: {} : exists", artifact);
                 } else {
                     // Audit ERROR: artifact download failed for some reason
-                    logger.error("RepositoryAudit: {}: does not exist", artifact.toString());
+                    logger.error("RepositoryAudit: {}: does not exist", artifact);
                     if (!ignoreErrors) {
                         response.append("Failed to download artifact: ").append(artifact).append('\n');
                         setResponse(response.toString());
@@ -470,12 +470,16 @@ public class RepositoryAudit extends DroolsPdpIntegrityMonitor.AuditBase {
             if (fileContents.regionMatches(index, "loading: ", 0, 9)) {
                 index += 9;
                 int endIndex = fileContents.indexOf('\n', index);
-                logger.info("RepositoryAudit: Attempted download: '{}'", fileContents.substring(index, endIndex));
+                if (logger.isInfoEnabled()) {
+                    logger.info("RepositoryAudit: Attempted download: '{}'", fileContents.substring(index, endIndex));
+                }
                 index = endIndex;
             } else if (fileContents.regionMatches(index, "loaded: ", 0, 8)) {
                 index += 8;
                 int endIndex = fileContents.indexOf(' ', index);
-                logger.info("RepositoryAudit: Successful download: '{}'", fileContents.substring(index, endIndex));
+                if (logger.isInfoEnabled()) {
+                    logger.info("RepositoryAudit: Successful download: '{}'", fileContents.substring(index, endIndex));
+                }
                 index = endIndex;
             }
         }
index f88eaea..520d850 100644 (file)
@@ -194,7 +194,7 @@ public class StateManagementFeature implements StateManagementFeatureApi,
         try {
             stateManagement.lock();
         } catch (Exception e) {
-            logger.error("StateManagementFeature.lock() failed with exception: {}", e);
+            logger.error("StateManagementFeature.lock() failed with exception", e);
             return false;
         }
         return true;
@@ -210,7 +210,7 @@ public class StateManagementFeature implements StateManagementFeatureApi,
         try {
             stateManagement.unlock();
         } catch (Exception e) {
-            logger.error("StateManagementFeature.unlock() failed with exception: {}", e);
+            logger.error("StateManagementFeature.unlock() failed with exception", e);
             return false;
         }
         return true;
index e029604..baecdfd 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * ONAP
  * ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019-2020 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.
@@ -116,12 +116,7 @@ public class TtControllerTask implements Runnable {
             logger.info("{}: stopping ...", this, e);
             getCurrentThread().interrupt();
         } catch (final IllegalArgumentException e) {
-            logger.error(
-                    "{}: controller {} has not been enabled for testing: ",
-                    this,
-                    this.controller.getName(),
-                    e.getMessage(),
-                    e);
+            logger.error("{}: controller {} has not been enabled for testing", this, this.controller.getName(), e);
         } catch (final Exception e) {
             logger.error(
                     "Controller: {} is not testable - TestTransaction caught exception: {} ",
index 0fe1f85..fee18a0 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * policy-core
  * ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
  * Modifications Copyright (C) 2018 Samsung Electronics Co., Ltd.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
@@ -74,7 +74,7 @@ public class PolicyContainer implements Startable {
     // (it can block for a long time)
     private boolean scannerStarted = false;
 
-    private static final String ERROR_STRING = "ERROR: Feature API: ";
+    private static final String ERROR_STRING = "ERROR: Feature API: {}";
 
     // packages that are included in all 'KieContainer' instances
     private static Collection<KiePackage> commonPackages = null;
@@ -260,50 +260,52 @@ public class PolicyContainer implements Startable {
     private PolicySession activatePolicySession(String name, String kieBaseName) {
         synchronized (sessions) {
             logger.info("activatePolicySession:name :{}", name);
-            PolicySession session = sessions.get(name);
-            if (session != null) {
-                logger.info("activatePolicySession:session - {} is returned.", session.getFullName());
-                return session;
-            }
-            KieSession kieSession = null;
+            PolicySession session = sessions.computeIfAbsent(name, key -> makeSession(name, kieBaseName));
 
-            // loop through all of the features, and give each one
-            // a chance to create the 'KieSession'
-            for (PolicySessionFeatureApi feature : PolicySessionFeatureApiConstants.getImpl().getList()) {
-                try {
-                    if ((kieSession = feature.activatePolicySession(this, name, kieBaseName)) != null) {
-                        break;
-                    }
-                } catch (Exception e) {
-                    logger.error(ERROR_STRING + feature.getClass().getName(), e);
+            logger.info("activatePolicySession:session - {} is returned.",
+                            session == null ? "null" : session.getFullName());
+            return session;
+        }
+    }
+
+    private PolicySession makeSession(String name, String kieBaseName) {
+        PolicySession session = null;
+        KieSession kieSession = null;
+
+        // loop through all of the features, and give each one
+        // a chance to create the 'KieSession'
+        for (PolicySessionFeatureApi feature : PolicySessionFeatureApiConstants.getImpl().getList()) {
+            try {
+                if ((kieSession = feature.activatePolicySession(this, name, kieBaseName)) != null) {
+                    break;
                 }
+            } catch (Exception e) {
+                logger.error(ERROR_STRING, feature.getClass().getName(), e);
             }
+        }
 
-            // if none of the features created the session, create one now
-            if (kieSession == null) {
-                kieSession = kieContainer.newKieSession(name);
-            }
+        // if none of the features created the session, create one now
+        if (kieSession == null) {
+            kieSession = kieContainer.newKieSession(name);
+        }
+
+        if (kieSession != null) {
+            // creation of 'KieSession' was successful - build
+            // a PolicySession
+            session = new PolicySession(name, this, kieSession);
 
-            if (kieSession != null) {
-                // creation of 'KieSession' was successful - build
-                // a PolicySession
-                session = new PolicySession(name, this, kieSession);
-                sessions.put(name, session);
-
-                // notify features
-                for (PolicySessionFeatureApi feature : PolicySessionFeatureApiConstants.getImpl().getList()) {
-                    try {
-                        feature.newPolicySession(session);
-                    } catch (Exception e) {
-                        logger.error(ERROR_STRING + feature.getClass().getName(), e);
-                    }
+            // notify features
+            for (PolicySessionFeatureApi feature : PolicySessionFeatureApiConstants.getImpl().getList()) {
+                try {
+                    feature.newPolicySession(session);
+                } catch (Exception e) {
+                    logger.error(ERROR_STRING, feature.getClass().getName(), e);
                 }
-                logger.info("activatePolicySession:new session was added in sessions with name {}", name);
             }
-            logger.info("activatePolicySession:session - {} is returned.",
-                    session == null ? "null" : session.getFullName());
-            return session;
+            logger.info("activatePolicySession:new session was added in sessions with name {}", name);
         }
+
+        return session;
     }
 
     /**
@@ -365,7 +367,7 @@ public class PolicyContainer implements Startable {
                 try {
                     feature.newPolicySession(policySession);
                 } catch (Exception e) {
-                    logger.error(ERROR_STRING + feature.getClass().getName(), e);
+                    logger.error(ERROR_STRING, feature.getClass().getName(), e);
                 }
             }
             return policySession;
@@ -562,10 +564,10 @@ public class PolicyContainer implements Startable {
      */
     @Override
     public synchronized boolean stop() {
-        if (!isStarted) {
-            return true;
-        }
+        return (!isStarted || doStop());
+    }
 
+    private boolean doStop() {
         Collection<PolicySession> localSessions;
 
         synchronized (sessions) {
@@ -587,7 +589,7 @@ public class PolicyContainer implements Startable {
                 try {
                     feature.disposeKieSession(session);
                 } catch (Exception e) {
-                    logger.error(ERROR_STRING + feature.getClass().getName(), e);
+                    logger.error(ERROR_STRING, feature.getClass().getName(), e);
                 }
             }
         }
@@ -650,7 +652,7 @@ public class PolicyContainer implements Startable {
                 try {
                     feature.destroyKieSession(session);
                 } catch (Exception e) {
-                    logger.error(ERROR_STRING + feature.getClass().getName(), e);
+                    logger.error(ERROR_STRING, feature.getClass().getName(), e);
                 }
             }
         }
@@ -710,7 +712,7 @@ public class PolicyContainer implements Startable {
             try {
                 feature.globalInit(args, configDir);
             } catch (Exception e) {
-                logger.error(ERROR_STRING + feature.getClass().getName(), e);
+                logger.error(ERROR_STRING, feature.getClass().getName(), e);
             }
         }
     }
@@ -751,7 +753,7 @@ public class PolicyContainer implements Startable {
         synchronized (PolicyContainer.class) {
             if (commonPackages == null) {
                 commonPackages = KieUtils.resourceToPackages(
-                    PolicyContainer.class.getClassLoader(), COMMON_PACKAGES_RESOURCE_NAME);
+                    PolicyContainer.class.getClassLoader(), COMMON_PACKAGES_RESOURCE_NAME).orElse(null);
                 if (commonPackages == null) {
                     // a problem occurred, which has already been logged --
                     // just store an empty collection, so we don't keep doing
index 69ca87c..cee7c36 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * policy-core
  * ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
  * Modifications Copyright (C) 2018 Samsung Electronics Co., Ltd.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
@@ -149,15 +149,14 @@ public class PolicySession
                     break;
                 }
             } catch (Exception e) {
-                logger.error("ERROR: Feature API: "
-                        + feature.getClass().getName(), e);
+                logger.error("ERROR: Feature API: {}", feature.getClass().getName(), e);
             }
         }
         if (threadModel == null) {
             // no feature created a ThreadModel -- select the default
             threadModel = new DefaultThreadModel(this);
         }
-        logger.info("starting ThreadModel for session " + getFullName());
+        logger.info("starting ThreadModel for session {}", getFullName());
         threadModel.start();
     }
 
index 0a4d327..03024f5 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * ONAP
  * ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019-2020 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.
@@ -52,7 +52,7 @@ public class AlwaysFailLock extends LockImpl {
      * Always returns false.
      */
     @Override
-    public boolean free() {
+    public synchronized boolean free() {
         return false;
     }
 
index c260924..bcad792 100644 (file)
@@ -31,6 +31,7 @@ import java.util.Collections;
 import java.util.Enumeration;
 import java.util.HashSet;
 import java.util.List;
+import java.util.Optional;
 import java.util.stream.Collectors;
 
 import lombok.NonNull;
@@ -183,19 +184,19 @@ public class KieUtils {
      * @return a collection of 'KiePackage' instances, or 'null' in case of
      *     failure
      */
-    public static Collection<KiePackage> resourceToPackages(ClassLoader classLoader, String resourceName) {
+    public static Optional<Collection<KiePackage>> resourceToPackages(ClassLoader classLoader, String resourceName) {
 
         // find all resources matching 'resourceName'
         Enumeration<URL> resources;
         try {
             resources = classLoader.getResources(resourceName);
         } catch (IOException e) {
-            logger.error("Exception fetching resources: " + resourceName, e);
-            return null;
+            logger.error("Exception fetching resources: {}", resourceName, e);
+            return Optional.empty();
         }
         if (!resources.hasMoreElements()) {
             // no resources found
-            return null;
+            return Optional.empty();
         }
 
         // generate a 'KieFileSystem' from these resources
@@ -211,8 +212,8 @@ public class KieUtils {
                 // add a new '.drl' entry to the KieFileSystem
                 kfs.write(RESOURCE_PREFIX + index++ + RESOURCE_SUFFIX, drl);
             } catch (IOException e) {
-                logger.error("Couldn't read in " + url, e);
-                return null;
+                logger.error("Couldn't read in {}", url, e);
+                return Optional.empty();
             }
         }
 
@@ -221,13 +222,13 @@ public class KieUtils {
         builder.buildAll();
         List<Message> results = builder.getResults().getMessages();
         if (!results.isEmpty()) {
-            logger.error("Kie build failed:\n" + results);
-            return null;
+            logger.error("Kie build failed:\n{}", results);
+            return Optional.empty();
         }
 
         // generate a KieContainer, and extract the package list
-        return kieServices.newKieContainer(builder.getKieModule().getReleaseId(), classLoader)
-               .getKieBase().getKiePackages();
+        return Optional.of(kieServices.newKieContainer(builder.getKieModule().getReleaseId(), classLoader)
+               .getKieBase().getKiePackages());
     }
 
     /**
index 1ed2789..63c7160 100644 (file)
@@ -20,6 +20,7 @@
 
 package org.onap.policy.drools.core;
 
+import static org.assertj.core.api.Assertions.assertThatCode;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertNull;
 import static org.mockito.Mockito.doAnswer;
@@ -97,7 +98,7 @@ public class PolicySessionTest {
         // re-start
         session.startThread();
 
-        session.stopThread();
+        assertThatCode(() -> session.stopThread()).doesNotThrowAnyException();
     }
 
     @Test
@@ -140,7 +141,7 @@ public class PolicySessionTest {
             }
         };
 
-        model.updated();
+        assertThatCode(() -> model.updated()).doesNotThrowAnyException();
     }
 
     @Test
@@ -156,7 +157,7 @@ public class PolicySessionTest {
     /**
      * Starts a thread and then invokes a function to generate an exception within the
      * fireUntilHalt() method.
-     * 
+     *
      * @param genEx function to generate an exception
      * @throws Exception if an error occurs
      */
index ce4ca5f..06489a5 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * ONAP
  * ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -20,6 +20,7 @@
 
 package org.onap.policy.drools.core.lock;
 
+import static org.assertj.core.api.Assertions.assertThatCode;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertNull;
@@ -77,7 +78,7 @@ public class AlwaysFailLockTest {
     @Test
     public void testAlwaysFailLockNoArgs() {
         // verify that no-arg constructor doesn't throw an exception
-        new AlwaysFailLock();
+        assertThatCode(() -> new AlwaysFailLock()).doesNotThrowAnyException();
     }
 
     @Test
index 902f304..56cd509 100644 (file)
@@ -21,6 +21,7 @@
 package org.onap.policy.drools.core.lock;
 
 import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatCode;
 import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
 import static org.assertj.core.api.Assertions.assertThatThrownBy;
 import static org.junit.Assert.assertEquals;
@@ -193,7 +194,7 @@ public class LockImplTest {
         doThrow(new IllegalArgumentException(EXPECTED_EXCEPTION)).when(callback).lockUnavailable(any());
 
         // should not throw an exception
-        lock.notifyAvailable();
+        assertThatCode(() -> lock.notifyAvailable()).doesNotThrowAnyException();
     }
 
     @Test
@@ -210,7 +211,7 @@ public class LockImplTest {
         doThrow(new IllegalArgumentException(EXPECTED_EXCEPTION)).when(callback).lockUnavailable(any());
 
         // should not throw an exception
-        lock.notifyUnavailable();
+        assertThatCode(() -> lock.notifyUnavailable()).doesNotThrowAnyException();
     }
 
     @Test
index 9711074..f230d4f 100644 (file)
@@ -130,15 +130,15 @@ public class KieUtilsTest {
 
         // test IOException from ClassLoader
         log = new StringBuffer();
-        assertNull(KieUtils.resourceToPackages(new BogusClassLoader(log), "BogusClassLoader"));
+        assertNull(KieUtils.resourceToPackages(new BogusClassLoader(log), "BogusClassLoader").orElse(null));
         assertEquals("IOException(BogusClassLoader)", log.toString());
 
         // test 'null' return when no resources are found
-        assertNull(KieUtils.resourceToPackages(ClassLoader.getSystemClassLoader(), "no/such/url"));
+        assertNull(KieUtils.resourceToPackages(ClassLoader.getSystemClassLoader(), "no/such/url").orElse(null));
 
         // test IOException in 'IOUtils.toByteArray()' -> 'InputStream.read()'
         log = new StringBuffer();
-        assertNull(KieUtils.resourceToPackages(new BogusClassLoader(log), "BogusUrl"));
+        assertNull(KieUtils.resourceToPackages(new BogusClassLoader(log), "BogusUrl").orElse(null));
         assertEquals("", log.toString());
 
         // don't know how to test 'KieBuilder' errors at this point
index 0f53b53..9fa8230 100644 (file)
@@ -22,6 +22,7 @@ package org.onap.policy.drools.domain.models.artifact;
 
 import java.io.Serializable;
 import lombok.Data;
+import lombok.EqualsAndHashCode;
 import lombok.experimental.SuperBuilder;
 import org.onap.policy.drools.domain.models.DroolsPolicy;
 
@@ -31,6 +32,7 @@ import org.onap.policy.drools.domain.models.DroolsPolicy;
 
 @Data
 @SuperBuilder
+@EqualsAndHashCode(callSuper = true)
 public class NativeArtifactPolicy extends DroolsPolicy implements Serializable {
 
     private static final long serialVersionUID = -8171337852833516581L;
index 09236c8..9237276 100644 (file)
@@ -22,6 +22,7 @@ package org.onap.policy.drools.domain.models.controller;
 
 import java.io.Serializable;
 import lombok.Data;
+import lombok.EqualsAndHashCode;
 import lombok.experimental.SuperBuilder;
 import org.onap.policy.drools.domain.models.DroolsPolicy;
 
@@ -31,6 +32,7 @@ import org.onap.policy.drools.domain.models.DroolsPolicy;
 
 @Data
 @SuperBuilder
+@EqualsAndHashCode(callSuper = true)
 public class ControllerPolicy extends DroolsPolicy implements Serializable {
 
     private static final long serialVersionUID = -8171337852833516581L;
index 87af6c3..c4772f3 100644 (file)
@@ -22,6 +22,7 @@ package org.onap.policy.drools.domain.models.controller;
 
 import java.io.Serializable;
 import lombok.Data;
+import lombok.EqualsAndHashCode;
 import lombok.experimental.SuperBuilder;
 
 
@@ -31,6 +32,7 @@ import lombok.experimental.SuperBuilder;
 
 @Data
 @SuperBuilder
+@EqualsAndHashCode(callSuper = true)
 public class ControllerSinkTopic extends ControllerTopic implements Serializable {
     private static final long serialVersionUID = 8770353732981476267L;
 }
index e41f4dc..97a21e6 100644 (file)
@@ -22,6 +22,7 @@ package org.onap.policy.drools.domain.models.controller;
 
 import java.io.Serializable;
 import lombok.Data;
+import lombok.EqualsAndHashCode;
 import lombok.experimental.SuperBuilder;
 
 
@@ -31,6 +32,7 @@ import lombok.experimental.SuperBuilder;
 
 @Data
 @SuperBuilder
+@EqualsAndHashCode(callSuper = true)
 public class ControllerSourceTopic extends ControllerTopic implements Serializable {
     private static final long serialVersionUID = -1732598566914643612L;
 }
index 2954350..fd78da7 100644 (file)
@@ -22,6 +22,7 @@ package org.onap.policy.drools.domain.models.controller;
 
 import java.util.List;
 import lombok.Data;
+import lombok.NoArgsConstructor;
 import lombok.experimental.SuperBuilder;
 
 
@@ -31,6 +32,7 @@ import lombok.experimental.SuperBuilder;
 
 @Data
 @SuperBuilder
+@NoArgsConstructor
 public abstract class ControllerTopic {
     protected String topicName;
     protected List<ControllerEvent> events;
index f4fcb70..d18300d 100644 (file)
@@ -22,6 +22,7 @@ package org.onap.policy.drools.domain.models.legacy;
 
 import java.io.Serializable;
 import lombok.Data;
+import lombok.EqualsAndHashCode;
 import lombok.experimental.SuperBuilder;
 import org.onap.policy.drools.domain.models.DroolsPolicy;
 
@@ -32,6 +33,7 @@ import org.onap.policy.drools.domain.models.DroolsPolicy;
 
 @Data
 @SuperBuilder
+@EqualsAndHashCode(callSuper = true)
 public class LegacyPolicy extends DroolsPolicy implements Serializable {
     private static final long serialVersionUID = 4100092564657497713L;
 
index d158608..433dc3e 100644 (file)
@@ -22,6 +22,7 @@ package org.onap.policy.drools.domain.models.operational;
 
 import java.io.Serializable;
 import lombok.Data;
+import lombok.EqualsAndHashCode;
 import lombok.experimental.SuperBuilder;
 import org.onap.policy.drools.domain.models.DroolsPolicy;
 
@@ -32,6 +33,7 @@ import org.onap.policy.drools.domain.models.DroolsPolicy;
 
 @Data
 @SuperBuilder
+@EqualsAndHashCode(callSuper = true)
 public class OperationalPolicy extends DroolsPolicy implements Serializable {
     private static final long serialVersionUID = 4100092564657497713L;
 
index 993ba02..f41d5c0 100644 (file)
@@ -44,11 +44,13 @@ public class OperationalProperties implements Serializable {
     /**
      * Timeout in seconds.
      */
+    @Builder.Default
     private int timeout = 30;
 
     /**
      * Abatement.
      */
+    @Builder.Default
     private boolean abatement = false;
 
     /**
index c6e8990..98ddd4c 100644 (file)
@@ -32,6 +32,7 @@ import com.openpojo.validation.test.impl.SetterTester;
 import java.io.Serializable;
 import java.util.List;
 import lombok.Data;
+import lombok.EqualsAndHashCode;
 import lombok.NoArgsConstructor;
 import lombok.experimental.SuperBuilder;
 import org.junit.Test;
@@ -41,6 +42,7 @@ public class DroolsPolicyTest {
     @Data
     @SuperBuilder
     @NoArgsConstructor
+    @EqualsAndHashCode(callSuper = true)
     public static class DerivedDomainPolicy extends DroolsPolicy implements Serializable {
         private static final long serialVersionUID = -1027974819756498893L;
     }
index 7eb2532..13e91cc 100644 (file)
@@ -38,7 +38,7 @@ public class LegacyPolicyTest {
     private static final String OPERATIONAL_LEGACY_POLICY_TYPE = "onap.policies.controlloop.Operational";
 
     // Operational vCPE Legacy Policy
-    private static final String OP_POLICY_NAME_VCPE = "operational.restart";
+    public static final String OP_POLICY_NAME_VCPE = "operational.restart";
     public static final String VCPE_OPERATIONAL_LEGACY_POLICY_JSON = "src/test/resources/tosca-legacy-vcpe.json";
 
     @Test
index bf50a3d..8f37b47 100644 (file)
@@ -23,9 +23,6 @@ package org.onap.policy.drools.domain.models.operational;
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertTrue;
 
-import java.io.IOException;
-import java.nio.file.Files;
-import java.nio.file.Paths;
 import java.util.List;
 import org.junit.Before;
 import org.junit.Test;
@@ -102,10 +99,6 @@ public class OperationalPolicyTest {
         assertNotNull(policy);
     }
 
-    private String getJsonFromFile(String filePath) throws IOException {
-        return Files.readString(Paths.get(filePath));
-    }
-
     private String getJsonFromResource(String resourcePath) {
         return ResourceUtils.getResourceAsString(resourcePath);
     }
index 0097dff..58d5052 100644 (file)
@@ -106,7 +106,7 @@ public class DomainMaker {
      * Check policy conformance to its specification providing a list of errors
      * in a ValidationFailedException.
      */
-    public boolean conformance(@NonNull ToscaPolicy policy) throws ValidationFailedException {
+    public boolean conformance(@NonNull ToscaPolicy policy) {
         if (!isRegistered(policy.getTypeIdentifier())) {
             return false;
         }
@@ -134,8 +134,7 @@ public class DomainMaker {
      * Checks a domain policy conformance to its specification providing a list of errors
      * in a ValidationFailedException.
      */
-    public <T> boolean conformance(@NonNull ToscaPolicyTypeIdentifier policyType, T domainPolicy)
-        throws ValidationFailedException {
+    public <T> boolean conformance(@NonNull ToscaPolicyTypeIdentifier policyType, T domainPolicy) {
 
         if (!isRegistered(policyType)) {
             return false;
@@ -144,7 +143,7 @@ public class DomainMaker {
         try {
             validators.get(policyType).encode(domainPolicy);
         } catch (CoderException e) {
-            logger.info("policy {}:{}:{} is not conformant", policyType, domainPolicy.getClass().getName(), e);
+            logger.info("policy {}:{} is not conformant", policyType, domainPolicy.getClass().getName(), e);
             if (e.getCause() instanceof ValidationFailedException) {
                 throw (ValidationFailedException) e.getCause();
             }
index 959e6a2..e6195fa 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * ONAP
  * ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2020 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.
@@ -30,6 +30,7 @@ import java.util.Properties;
 import java.util.Set;
 import java.util.Timer;
 import java.util.TimerTask;
+import java.util.concurrent.atomic.AtomicReference;
 import org.apache.commons.configuration2.Configuration;
 import org.apache.commons.configuration2.ConfigurationConverter;
 import org.apache.commons.configuration2.SystemConfiguration;
@@ -54,13 +55,13 @@ public class PropertyUtil {
 
     private static final Logger logger = LoggerFactory.getLogger(PropertyUtil.class.getName());
 
-    private static volatile CryptoCoder cryptoCoder;
+    private static final AtomicReference<CryptoCoder> cryptoCoder = new AtomicReference<>();
 
     /**
      * Sets a default Crypto Coder.
      */
     public static void setDefaultCryptoCoder(CryptoCoder cryptoCoder) {
-        PropertyUtil.cryptoCoder = cryptoCoder;
+        PropertyUtil.cryptoCoder.set(cryptoCoder);
     }
 
     /**
@@ -186,7 +187,7 @@ public class PropertyUtil {
      * @return Properties - interpolated properties object
      */
     public static Properties getInterpolatedProperties(Properties properties) {
-        return getInterpolatedProperties(properties, cryptoCoder);
+        return getInterpolatedProperties(properties, cryptoCoder.get());
     }
 
     /**
index 04f20b2..4797239 100644 (file)
@@ -27,8 +27,6 @@ import lombok.Data;
 @Data
 @Builder
 public class DomainAPolicy {
-    private static final long serialVersionUID = -8942432000554391455L;
-
     @SerializedName("type")
     public String type;
 
index cfacc7a..47d6c2d 100644 (file)
@@ -45,12 +45,10 @@ import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeIdentifi
 public class DomainMakerTest {
 
     private DomainMaker domainMaker;
-    private StandardCoder nonValCoder;
 
     @Before
     public void setUp() throws Exception {
         domainMaker = new DomainMaker();
-        nonValCoder = new StandardCoder();
     }
 
     @Test
diff --git a/pom.xml b/pom.xml
index f57acdc..0be3bc8 100644 (file)
--- a/pom.xml
+++ b/pom.xml
@@ -26,7 +26,7 @@
     <parent>
         <groupId>org.onap.policy.parent</groupId>
         <artifactId>integration</artifactId>
-        <version>3.1.1</version>
+        <version>3.1.2-SNAPSHOT</version>
         <relativePath />
     </parent>