Fix sonars in drools-pdp 42/123642/2
authorJim Hahn <jrh3@att.com>
Thu, 26 Aug 2021 18:36:35 +0000 (14:36 -0400)
committerJim Hahn <jrh3@att.com>
Thu, 26 Aug 2021 19:12:19 +0000 (15:12 -0400)
Fixed sonars:
- use "var"
- override  "equals"
- unused imports

Also changed some of the JPA queries to make them typed queries.

Issue-ID: POLICY-3289
Change-Id: Ib3a00be322d8d00ba492673708439cacfe2c7fc4
Signed-off-by: Jim Hahn <jrh3@att.com>
32 files changed:
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/DroolsPdpEntity.java
feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/DroolsPdpImpl.java
feature-active-standby-management/src/main/java/org/onap/policy/drools/activestandby/DroolsPdpObject.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/main/java/org/onap/policy/drools/activestandby/PmStandbyStateChangeNotifier.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-drools-init/src/main/java/org/onap/policy/drools/droolsinit/DroolsInitFeature.java
feature-eelf/src/main/java/org/onap/policy/drools/eelf/EelfFeature.java
feature-healthcheck/src/main/java/org/onap/policy/drools/healthcheck/HealthCheckManager.java
feature-lifecycle/src/main/java/org/onap/policy/drools/lifecycle/LifecycleFsm.java
feature-lifecycle/src/main/java/org/onap/policy/drools/lifecycle/LifecycleStateRunning.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-no-locking/src/main/java/org/onap/policy/no/locking/NoLockManager.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/PoolingManagerImpl.java
feature-pooling-dmaap/src/main/java/org/onap/policy/drools/pooling/message/BucketAssignments.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/ProcessingState.java
feature-pooling-dmaap/src/main/java/org/onap/policy/drools/pooling/state/StartState.java
feature-session-persistence/src/main/java/org/onap/policy/drools/persistence/JpaDroolsSessionConnector.java
feature-state-management/src/main/java/org/onap/policy/drools/statemanagement/DbAudit.java
feature-state-management/src/main/java/org/onap/policy/drools/statemanagement/IntegrityMonitorRestManager.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-management/src/main/java/org/onap/policy/drools/system/Main.java
policy-management/src/main/java/org/onap/policy/drools/system/PolicyEngineManager.java
policy-utils/src/main/java/org/onap/policy/drools/utils/logging/LoggerUtil.java

index bd3f021..e3125a5 100644 (file)
@@ -23,8 +23,6 @@ package org.onap.policy.drools.activestandby;
 import java.io.IOException;
 import java.util.HashMap;
 import java.util.Map;
-import java.util.Properties;
-import javax.persistence.EntityManagerFactory;
 import javax.persistence.Persistence;
 import org.eclipse.persistence.config.PersistenceUnitProperties;
 import org.onap.policy.common.im.MonitorTime;
@@ -107,7 +105,7 @@ public class ActiveStandbyFeature implements ActiveStandbyFeatureApi,
 
 
         //Create an instance of the Observer
-        PmStandbyStateChangeNotifier pmNotifier = new PmStandbyStateChangeNotifier();
+        var pmNotifier = new PmStandbyStateChangeNotifier();
 
         //Register the PMStandbyStateChangeNotifier Observer
         stateManagementFeature.addObserver(pmNotifier);
@@ -132,7 +130,7 @@ public class ActiveStandbyFeature implements ActiveStandbyFeatureApi,
     private static void initializePersistence(String configDir) {
         //Get the Active Standby properties
         try {
-            Properties activeStandbyProperties =
+            var activeStandbyProperties =
                     PropertyUtil.getProperties(configDir + "/feature-active-standby-management.properties");
             ActiveStandbyProperties.initProperties(activeStandbyProperties);
             logger.info("initializePersistence: ActiveStandbyProperties success");
@@ -140,7 +138,7 @@ public class ActiveStandbyFeature implements ActiveStandbyFeatureApi,
             logger.error("ActiveStandbyFeature: initializePersistence ActiveStandbyProperties", e);
         }
 
-        DroolsPdpsConnector conn = getDroolsPdpsConnector("activeStandbyPU");
+        var conn = getDroolsPdpsConnector("activeStandbyPU");
         String resourceName = ActiveStandbyProperties.getProperty(ActiveStandbyProperties.NODE_NAME);
         if (resourceName == null) {
             throw new NullPointerException();
@@ -199,8 +197,7 @@ public class ActiveStandbyFeature implements ActiveStandbyFeatureApi,
         propMap.put(PersistenceUnitProperties.TARGET_DATABASE,
                         ActiveStandbyProperties.getProperty(ActiveStandbyProperties.DB_TYPE));
 
-        EntityManagerFactory emf = Persistence.createEntityManagerFactory(
-                pu, propMap);
+        var emf = Persistence.createEntityManagerFactory(pu, propMap);
         return new JpaDroolsPdpsConnector(emf);
     }
 
index cf610d9..526200f 100644 (file)
@@ -28,6 +28,7 @@ import javax.persistence.Id;
 import javax.persistence.NamedQuery;
 import javax.persistence.Temporal;
 import javax.persistence.TemporalType;
+import lombok.EqualsAndHashCode;
 import lombok.Getter;
 import lombok.Setter;
 import org.onap.policy.common.im.MonitorTime;
@@ -39,6 +40,7 @@ import org.onap.policy.common.im.MonitorTime;
 @NamedQuery(name = "DroolsPdpEntity.deleteAll", query = "DELETE FROM DroolsPdpEntity WHERE 1=1")
 @Getter
 @Setter
+@EqualsAndHashCode(onlyExplicitlyIncluded = true, callSuper = true)
 public class DroolsPdpEntity extends DroolsPdpObject implements Serializable {
 
     private static final long serialVersionUID = 1L;
index f86b1a5..dac35ea 100644 (file)
 package org.onap.policy.drools.activestandby;
 
 import java.util.Date;
+import lombok.EqualsAndHashCode;
 import lombok.Getter;
 import lombok.Setter;
 
 @Getter
 @Setter
+@EqualsAndHashCode(onlyExplicitlyIncluded = true, callSuper = true)
 public class DroolsPdpImpl extends DroolsPdpObject {
 
     private boolean designated;
index fd25a6d..c897113 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-2019, 2021 AT&T Intellectual Property. All rights reserved.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -34,8 +34,8 @@ public abstract class DroolsPdpObject implements DroolsPdp {
 
     @Override
     public int hashCode() {
-        final int prime = 31;
-        int result = 1;
+        final var prime = 31;
+        var result = 1;
         result = prime * result + (this.getPdpId() == null ? 0 : this.getPdpId().hashCode());
         return result;
     }
index 8e6b5ef..ff4b21d 100644 (file)
@@ -25,7 +25,6 @@ import java.util.Collection;
 import java.util.Date;
 import java.util.List;
 import java.util.Objects;
-import java.util.Timer;
 import java.util.TimerTask;
 import lombok.Getter;
 import lombok.Setter;
@@ -104,7 +103,7 @@ public class DroolsPdpsElectionHandler implements ThreadRunningChecker {
         this.isDesignated = false;
 
         // The interval between checks of the DesignationWaiter to be sure it is running.
-        int pdpCheckInterval = 3000;
+        var pdpCheckInterval = 3000;
         try {
             pdpCheckInterval = Integer.parseInt(ActiveStandbyProperties.getProperty(
                     ActiveStandbyProperties.PDP_CHECK_INVERVAL));
@@ -119,14 +118,14 @@ public class DroolsPdpsElectionHandler implements ThreadRunningChecker {
             logger.error("Could not get pdpUpdateInterval property. Using default {} ", pdpUpdateInterval, e);
         }
 
-        Date now = currentTime.getDate();
+        var now = currentTime.getDate();
 
         // Retrieve the ms since the epoch
         final long nowMs = now.getTime();
 
         // Create the timer which will update the updateDate in DroolsPdpEntity table.
         // This is the heartbeat
-        Timer updateWorker = Factory.getInstance().makeTimer();
+        var updateWorker = Factory.getInstance().makeTimer();
 
         // Schedule the TimerUpdateClass to run at 100 ms and run at pdpCheckInterval ms thereafter
         // NOTE: The first run of the TimerUpdateClass results in myPdp being added to the
@@ -134,12 +133,12 @@ public class DroolsPdpsElectionHandler implements ThreadRunningChecker {
         updateWorker.scheduleAtFixedRate(new TimerUpdateClass(), 100, pdpCheckInterval);
 
         // Create the timer which will run the election algorithm
-        Timer waitTimer = Factory.getInstance().makeTimer();
+        var waitTimer = Factory.getInstance().makeTimer();
 
         // Schedule it to start in startMs ms
         // (so it will run after the updateWorker and run at pdpUpdateInterval ms thereafter
         long startMs = getDWaiterStartMs();
-        DesignationWaiter designationWaiter = new DesignationWaiter();
+        var designationWaiter = new DesignationWaiter();
         waitTimer.scheduleAtFixedRate(designationWaiter, startMs, pdpUpdateInterval);
         waitTimerLastRunDate = new Date(nowMs + startMs);
 
@@ -267,7 +266,7 @@ public class DroolsPdpsElectionHandler implements ThreadRunningChecker {
                 logger.debug("DesignatedWaiter.run: myPdp: {}; Returning, isDesignated= {}",
                                 isDesignated, myPdp.getPdpId());
 
-                Date tmpDate = currentTime.getDate();
+                var tmpDate = currentTime.getDate();
                 logger.debug("DesignatedWaiter.run (end of run) waitTimerLastRunDate = {}", tmpDate);
 
                 waitTimerLastRunDate = tmpDate;
@@ -631,8 +630,8 @@ public class DroolsPdpsElectionHandler implements ThreadRunningChecker {
      */
     public List<DroolsPdp> santizeDesignatedList(List<DroolsPdp> listOfDesignated) {
 
-        boolean containsDesignated = false;
-        boolean containsHotStandby = false;
+        var containsDesignated = false;
+        var containsHotStandby = false;
         List<DroolsPdp> listForRemoval = new ArrayList<>();
         for (DroolsPdp pdp : listOfDesignated) {
             logger.debug("DesignatedWaiter.run sanitizing: pdp = {}"
@@ -768,7 +767,7 @@ public class DroolsPdpsElectionHandler implements ThreadRunningChecker {
 
         logger.debug("DesignatedWaiter.run: myPdp: {} listOfDesignated.size(): {}", myPdp.getPdpId(),
                         listOfDesignated.size());
-        DesignatedData data = new DesignatedData();
+        var data = new DesignatedData();
         for (DroolsPdp pdp : listOfDesignated) {
             DroolsPdp rejectedPdp;
 
@@ -922,7 +921,7 @@ public class DroolsPdpsElectionHandler implements ThreadRunningChecker {
         synchronized (checkWaitTimerLock) {
             try {
                 logger.debug("checkWaitTimer: entry");
-                Date now = currentTime.getDate();
+                var now = currentTime.getDate();
                 long nowMs = now.getTime();
                 long waitTimerMs = waitTimerLastRunDate.getTime();
 
@@ -953,7 +952,7 @@ public class DroolsPdpsElectionHandler implements ThreadRunningChecker {
     }
 
     private long getDWaiterStartMs() {
-        Date now = currentTime.getDate();
+        var now = currentTime.getDate();
 
         // Retrieve the ms since the epoch
         long nowMs = now.getTime();
index 471ef49..39386d5 100644 (file)
 package org.onap.policy.drools.activestandby;
 
 import java.util.Collection;
-import java.util.Date;
 import java.util.LinkedList;
 import java.util.List;
 import javax.persistence.EntityManager;
 import javax.persistence.EntityManagerFactory;
 import javax.persistence.FlushModeType;
 import javax.persistence.LockModeType;
-import javax.persistence.Query;
 import lombok.AllArgsConstructor;
 import org.onap.policy.common.im.MonitorTime;
 import org.onap.policy.common.utils.time.CurrentTime;
@@ -50,19 +48,15 @@ public class JpaDroolsPdpsConnector implements DroolsPdpsConnector {
     @Override
     public Collection<DroolsPdp> getDroolsPdps() {
         //return a list of all the DroolsPdps in the database
-        EntityManager em = emf.createEntityManager();
+        var em = emf.createEntityManager();
         try {
             em.getTransaction().begin();
-            Query droolsPdpsListQuery = em.createQuery("SELECT p FROM DroolsPdpEntity p");
-            List<?> droolsPdpsList = droolsPdpsListQuery.setLockMode(LockModeType.NONE)
+            var droolsPdpsListQuery = em.createQuery("SELECT p FROM DroolsPdpEntity p", DroolsPdp.class);
+            List<DroolsPdp> droolsPdpsList = droolsPdpsListQuery.setLockMode(LockModeType.NONE)
                     .setFlushMode(FlushModeType.COMMIT).getResultList();
             LinkedList<DroolsPdp> droolsPdpsReturnList = new LinkedList<>();
-            for (Object o : droolsPdpsList) {
-                if (!(o instanceof DroolsPdp)) {
-                    continue;
-                }
+            for (DroolsPdp droolsPdp : droolsPdpsList) {
                 //Make sure it is not a cached version
-                DroolsPdp droolsPdp = (DroolsPdp) o;
                 em.refresh(droolsPdp);
                 droolsPdpsReturnList.add(droolsPdp);
                 if (logger.isDebugEnabled()) {
@@ -100,18 +94,18 @@ public class JpaDroolsPdpsConnector implements DroolsPdpsConnector {
         logger.debug("update: Entering, pdpId={}", pdp.getPdpId());
 
         //this is to update our own pdp in the database
-        EntityManager em = emf.createEntityManager();
+        var em = emf.createEntityManager();
         try {
             em.getTransaction().begin();
-            Query droolsPdpsListQuery = em.createQuery(SELECT_PDP_BY_ID);
+            var droolsPdpsListQuery = em.createQuery(SELECT_PDP_BY_ID, DroolsPdpEntity.class);
             droolsPdpsListQuery.setParameter(PDP_ID_PARAM, pdp.getPdpId());
-            List<?> droolsPdpsList = droolsPdpsListQuery.setLockMode(LockModeType.NONE)
+            List<DroolsPdpEntity> droolsPdpsList = droolsPdpsListQuery.setLockMode(LockModeType.NONE)
                     .setFlushMode(FlushModeType.COMMIT).getResultList();
             DroolsPdpEntity droolsPdpEntity;
-            if (droolsPdpsList.size() == 1 && (droolsPdpsList.get(0) instanceof DroolsPdpEntity)) {
-                droolsPdpEntity = (DroolsPdpEntity) droolsPdpsList.get(0);
+            if (droolsPdpsList.size() == 1) {
+                droolsPdpEntity = droolsPdpsList.get(0);
                 em.refresh(droolsPdpEntity); //Make sure we have current values
-                Date currentDate = currentTime.getDate();
+                var currentDate = currentTime.getDate();
                 long difference = currentDate.getTime() - droolsPdpEntity.getUpdatedDate().getTime();
                 //just set some kind of default here
                 long pdpTimeout = 15000;
@@ -175,18 +169,18 @@ public class JpaDroolsPdpsConnector implements DroolsPdpsConnector {
 
         boolean isCurrent = isCurrent(pdp);
 
-        EntityManager em = emf.createEntityManager();
+        var em = emf.createEntityManager();
         try {
             if (!isCurrent && pdp.isDesignated()) {
                 em.getTransaction().begin();
-                Query droolsPdpsListQuery = em.createQuery(SELECT_PDP_BY_ID);
+                var droolsPdpsListQuery = em.createQuery(SELECT_PDP_BY_ID, DroolsPdpEntity.class);
                 droolsPdpsListQuery.setParameter(PDP_ID_PARAM, pdp.getPdpId());
-                List<?> droolsPdpsList = droolsPdpsListQuery.setLockMode(LockModeType.NONE)
+                List<DroolsPdpEntity> droolsPdpsList = droolsPdpsListQuery.setLockMode(LockModeType.NONE)
                         .setFlushMode(FlushModeType.COMMIT).getResultList();
-                if (droolsPdpsList.size() == 1 && droolsPdpsList.get(0) instanceof DroolsPdpEntity) {
+                if (droolsPdpsList.size() == 1) {
                     logger.debug("isPdpCurrent: PDP={}  designated but not current; setting designated to false",
                                     pdp.getPdpId());
-                    DroolsPdpEntity droolsPdpEntity = (DroolsPdpEntity) droolsPdpsList.get(0);
+                    var droolsPdpEntity = droolsPdpsList.get(0);
                     droolsPdpEntity.setDesignated(false);
                     em.getTransaction().commit();
                 } else {
@@ -217,15 +211,13 @@ public class JpaDroolsPdpsConnector implements DroolsPdpsConnector {
         try {
             em = emf.createEntityManager();
             em.getTransaction().begin();
-            Query droolsPdpsListQuery = em
-                    .createQuery(SELECT_PDP_BY_ID);
+            var droolsPdpsListQuery = em
+                    .createQuery(SELECT_PDP_BY_ID, DroolsPdpEntity.class);
             droolsPdpsListQuery.setParameter(PDP_ID_PARAM, pdp.getPdpId());
-            List<?> droolsPdpsList = droolsPdpsListQuery.setLockMode(
+            List<DroolsPdpEntity> droolsPdpsList = droolsPdpsListQuery.setLockMode(
                     LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList();
-            if (droolsPdpsList.size() == 1
-                    && droolsPdpsList.get(0) instanceof DroolsPdpEntity) {
-                DroolsPdpEntity droolsPdpEntity = (DroolsPdpEntity) droolsPdpsList
-                        .get(0);
+            if (droolsPdpsList.size() == 1) {
+                var droolsPdpEntity = droolsPdpsList.get(0);
 
                 logger.debug("setDesignated: PDP={}"
                         + " found, designated= {}"
@@ -275,15 +267,13 @@ public class JpaDroolsPdpsConnector implements DroolsPdpsConnector {
              * Get droolspdpentity record for this PDP and mark DESIGNATED as
              * false.
              */
-            Query droolsPdpsListQuery = em
-                    .createQuery(SELECT_PDP_BY_ID);
+            var droolsPdpsListQuery = em
+                    .createQuery(SELECT_PDP_BY_ID, DroolsPdpEntity.class);
             droolsPdpsListQuery.setParameter(PDP_ID_PARAM, pdpId);
-            List<?> droolsPdpsList = droolsPdpsListQuery.setLockMode(
+            List<DroolsPdpEntity> droolsPdpsList = droolsPdpsListQuery.setLockMode(
                     LockModeType.NONE).setFlushMode(FlushModeType.COMMIT).getResultList();
-            DroolsPdpEntity droolsPdpEntity;
-            if (droolsPdpsList.size() == 1
-                    && (droolsPdpsList.get(0) instanceof DroolsPdpEntity)) {
-                droolsPdpEntity = (DroolsPdpEntity) droolsPdpsList.get(0);
+            if (droolsPdpsList.size() == 1) {
+                var droolsPdpEntity = droolsPdpsList.get(0);
                 droolsPdpEntity.setDesignated(false);
                 em.persist(droolsPdpEntity);
                 logger.debug("standDownPdp: PDP={} persisted as non-designated.", pdpId);
@@ -324,8 +314,8 @@ public class JpaDroolsPdpsConnector implements DroolsPdpsConnector {
 
         logger.debug("hasDesignatedPdpFailed: Entering, pdps.size()={}", pdps.size());
 
-        boolean failed = true;
-        boolean foundDesignatedPdp = false;
+        var failed = true;
+        var foundDesignatedPdp = false;
 
         for (DroolsPdp pdp : pdps) {
 
@@ -360,13 +350,13 @@ public class JpaDroolsPdpsConnector implements DroolsPdpsConnector {
 
         logger.debug("isCurrent: Entering, pdpId={}", pdp.getPdpId());
 
-        boolean current = false;
+        var current = false;
 
         // Return if the current PDP is considered "current" based on whatever
         // time box that may be.
         // If the the PDP is not current, we should mark it as not primary in
         // the database
-        Date currentDate = currentTime.getDate();
+        var currentDate = currentTime.getDate();
         long difference = currentDate.getTime()
                 - pdp.getUpdatedDate().getTime();
         // just set some kind of default here
@@ -402,7 +392,7 @@ public class JpaDroolsPdpsConnector implements DroolsPdpsConnector {
         try {
             em = emf.createEntityManager();
             em.getTransaction().begin();
-            Query droolsPdpsListQuery = em
+            var droolsPdpsListQuery = em
                     .createQuery(SELECT_PDP_BY_ID);
             droolsPdpsListQuery.setParameter(PDP_ID_PARAM, pdpId);
             List<?> droolsPdpsList = droolsPdpsListQuery.setLockMode(
@@ -446,14 +436,14 @@ public class JpaDroolsPdpsConnector implements DroolsPdpsConnector {
         /*
          * Start transaction
          */
-        EntityManager em = emf.createEntityManager();
+        var em = emf.createEntityManager();
         try {
             em.getTransaction().begin();
 
             /*
              * Insert record.
              */
-            DroolsPdpEntity droolsPdpEntity = new DroolsPdpEntity();
+            var droolsPdpEntity = new DroolsPdpEntity();
             em.persist(droolsPdpEntity);
             droolsPdpEntity.setPdpId(pdp.getPdpId());
             droolsPdpEntity.setDesignated(pdp.isDesignated());
@@ -484,11 +474,11 @@ public class JpaDroolsPdpsConnector implements DroolsPdpsConnector {
         /*
          * Start transaction
          */
-        EntityManager em = emf.createEntityManager();
+        var em = emf.createEntityManager();
         try {
             em.getTransaction().begin();
 
-            Query droolsPdpsListQuery = em
+            var droolsPdpsListQuery = em
                     .createQuery("SELECT p FROM DroolsPdpEntity p");
             @SuppressWarnings("unchecked")
             List<DroolsPdp> droolsPdpsList = droolsPdpsListQuery.setLockMode(
@@ -521,14 +511,14 @@ public class JpaDroolsPdpsConnector implements DroolsPdpsConnector {
         /*
          * Start transaction
          */
-        EntityManager em = emf.createEntityManager();
+        var em = emf.createEntityManager();
         try {
             em.getTransaction().begin();
 
             /*
              * Delete record.
              */
-            DroolsPdpEntity droolsPdpEntity = em.find(DroolsPdpEntity.class, pdpId);
+            var droolsPdpEntity = em.find(DroolsPdpEntity.class, pdpId);
             if (droolsPdpEntity != null) {
                 logger.debug("deletePdp: Removing PDP");
                 em.remove(droolsPdpEntity);
index 776b70e..1756246 100644 (file)
@@ -82,7 +82,7 @@ public class PmStandbyStateChangeNotifier extends StateChangeNotifier {
      *
      */
     public PmStandbyStateChangeNotifier() {
-        int pdpUpdateInterval =
+        var pdpUpdateInterval =
             Integer.parseInt(ActiveStandbyProperties.getProperty(ActiveStandbyProperties.PDP_UPDATE_INTERVAL));
         isWaitingForActivation = false;
         startTimeWaitingForActivationMs = currentTime.getMillis();
index 30f9076..6cca9ce 100755 (executable)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * feature-controller-logging
  * ================================================================================
- * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -31,7 +31,6 @@ import org.onap.policy.drools.protocol.configuration.PdpdConfiguration;
 import org.onap.policy.drools.system.PolicyController;
 import org.onap.policy.drools.system.PolicyControllerConstants;
 import org.onap.policy.drools.system.PolicyEngine;
-import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 /**
@@ -64,7 +63,7 @@ public class ControllerLoggingFeature
      */
     @Override
     public boolean beforeOffer(PolicyController controller, CommInfrastructure protocol, String topic, String event) {
-        Logger controllerLogger = LoggerFactory.getLogger(controller.getName());
+        var controllerLogger = LoggerFactory.getLogger(controller.getName());
         controllerLogger.info("[IN|{}|{}]{}{}", protocol, topic, LINE_SEP, event);
         return false;
     }
@@ -77,7 +76,7 @@ public class ControllerLoggingFeature
     public boolean afterDeliver(DroolsController controller, TopicSink sink, Object fact, String json,
                     boolean success) {
         if (success) {
-            Logger controllerLogger = LoggerFactory
+            var controllerLogger = LoggerFactory
                             .getLogger(PolicyControllerConstants.getFactory().get(controller).getName());
             controllerLogger.info("[OUT|{}|{}]{}{}", sink.getTopicCommInfrastructure(), sink.getTopic(),
                             LINE_SEP, json);
@@ -93,7 +92,7 @@ public class ControllerLoggingFeature
     public boolean afterOnTopicEvent(PolicyEngine engine, PdpdConfiguration configuration, CommInfrastructure commType,
                     String topic, String event) {
         for (ControllerConfiguration controller : configuration.getControllers()) {
-            Logger controllerLogger = LoggerFactory.getLogger(controller.getName());
+            var controllerLogger = LoggerFactory.getLogger(controller.getName());
             controllerLogger.info("[IN|{}|{}]{}{}", commType, topic, LINE_SEP, event);
         }
         return false;
index 93a6375..04138ee 100644 (file)
@@ -22,7 +22,6 @@ package org.onap.policy.distributed.locking;
 
 import java.sql.Connection;
 import java.sql.PreparedStatement;
-import java.sql.ResultSet;
 import java.sql.SQLException;
 import java.sql.SQLTransientException;
 import java.util.HashSet;
@@ -181,7 +180,7 @@ public class DistributedLockManager extends LockManager<DistributedLockManager.D
      * @throws Exception exception
      */
     protected BasicDataSource makeDataSource() throws Exception {
-        Properties props = new Properties();
+        var props = new Properties();
         props.put("driverClassName", featProps.getDbDriver());
         props.put("url", featProps.getDbUrl());
         props.put("username", featProps.getDbUser());
@@ -200,9 +199,8 @@ public class DistributedLockManager extends LockManager<DistributedLockManager.D
     private void deleteExpiredDbLocks() {
         logger.info("deleting all expired locks from the DB");
 
-        try (Connection conn = dataSource.getConnection();
-                        PreparedStatement stmt = conn
-                                        .prepareStatement("DELETE FROM pooling.locks WHERE expirationTime <= now()")) {
+        try (var conn = dataSource.getConnection();
+                var stmt = conn.prepareStatement("DELETE FROM pooling.locks WHERE expirationTime <= now()")) {
 
             int ndel = stmt.executeUpdate();
             logger.info("deleted {} expired locks from the DB", ndel);
@@ -299,7 +297,7 @@ public class DistributedLockManager extends LockManager<DistributedLockManager.D
          */
 
         // @formatter:off
-        try (Connection conn = dataSource.getConnection();
+        try (var conn = dataSource.getConnection();
                     PreparedStatement stmt = conn.prepareStatement(
                         "SELECT resourceId FROM pooling.locks WHERE host=? AND owner=? AND expirationTime > now()")) {
             // @formatter:on
@@ -307,9 +305,9 @@ public class DistributedLockManager extends LockManager<DistributedLockManager.D
             stmt.setString(1, pdpName);
             stmt.setString(2, uuidString);
 
-            try (ResultSet resultSet = stmt.executeQuery()) {
+            try (var resultSet = stmt.executeQuery()) {
                 while (resultSet.next()) {
-                    String resourceId = resultSet.getString(1);
+                    var resourceId = resultSet.getString(1);
 
                     // we have now seen this resource id
                     expiredIds.remove(resourceId);
@@ -424,7 +422,7 @@ public class DistributedLockManager extends LockManager<DistributedLockManager.D
                 return false;
             }
 
-            AtomicBoolean result = new AtomicBoolean(false);
+            var result = new AtomicBoolean(false);
 
             feature.resource2lock.computeIfPresent(getResourceId(), (resourceId, curlock) -> {
                 if (curlock == this && !isUnavailable()) {
@@ -455,7 +453,7 @@ public class DistributedLockManager extends LockManager<DistributedLockManager.D
                 return;
             }
 
-            AtomicBoolean success = new AtomicBoolean(false);
+            var success = new AtomicBoolean(false);
 
             feature.resource2lock.computeIfPresent(getResourceId(), (resourceId, curlock) -> {
                 if (curlock == this && !isUnavailable()) {
@@ -627,8 +625,8 @@ public class DistributedLockManager extends LockManager<DistributedLockManager.D
              */
 
             logger.debug("doLock {}", this);
-            try (Connection conn = feature.dataSource.getConnection()) {
-                boolean success = false;
+            try (var conn = feature.dataSource.getConnection()) {
+                var success = false;
                 try {
                     success = doDbInsert(conn);
 
@@ -655,7 +653,7 @@ public class DistributedLockManager extends LockManager<DistributedLockManager.D
          */
         private void doUnlock() throws SQLException {
             logger.debug("unlock {}", this);
-            try (Connection conn = feature.dataSource.getConnection()) {
+            try (var conn = feature.dataSource.getConnection()) {
                 doDbDelete(conn);
             }
 
@@ -683,7 +681,7 @@ public class DistributedLockManager extends LockManager<DistributedLockManager.D
              */
 
             logger.debug("doExtend {}", this);
-            try (Connection conn = feature.dataSource.getConnection()) {
+            try (var conn = feature.dataSource.getConnection()) {
                 /*
                  * invoker may have called extend() before free() had a chance to insert
                  * the record, thus we have to try to insert, if the update fails
@@ -707,8 +705,7 @@ public class DistributedLockManager extends LockManager<DistributedLockManager.D
          */
         protected boolean doDbInsert(Connection conn) throws SQLException {
             logger.debug("insert lock record {}", this);
-            try (PreparedStatement stmt =
-                            conn.prepareStatement("INSERT INTO pooling.locks (resourceId, host, owner, expirationTime) "
+            try (var stmt = conn.prepareStatement("INSERT INTO pooling.locks (resourceId, host, owner, expirationTime) "
                                             + "values (?, ?, ?, timestampadd(second, ?, now()))")) {
 
                 stmt.setString(1, getResourceId());
@@ -735,8 +732,7 @@ public class DistributedLockManager extends LockManager<DistributedLockManager.D
          */
         protected boolean doDbUpdate(Connection conn) throws SQLException {
             logger.debug("update lock record {}", this);
-            try (PreparedStatement stmt =
-                            conn.prepareStatement("UPDATE pooling.locks SET resourceId=?, host=?, owner=?,"
+            try (var stmt = conn.prepareStatement("UPDATE pooling.locks SET resourceId=?, host=?, owner=?,"
                                             + " expirationTime=timestampadd(second, ?, now()) WHERE resourceId=?"
                                             + " AND ((host=? AND owner=?) OR expirationTime < now())")) {
 
@@ -768,7 +764,7 @@ public class DistributedLockManager extends LockManager<DistributedLockManager.D
          */
         protected void doDbDelete(Connection conn) throws SQLException {
             logger.debug("delete lock record {}", this);
-            try (PreparedStatement stmt = conn
+            try (var stmt = conn
                             .prepareStatement("DELETE FROM pooling.locks WHERE resourceId=? AND host=? AND owner=?")) {
 
                 stmt.setString(1, getResourceId());
index c1e9aed..923083c 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * feature-drools-init
  * ================================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -22,7 +22,6 @@ package org.onap.policy.drools.droolsinit;
 
 import java.io.Serializable;
 import java.util.concurrent.TimeUnit;
-import org.kie.api.runtime.rule.FactHandle;
 import org.onap.policy.drools.core.PolicySession;
 import org.onap.policy.drools.core.PolicySessionFeatureApi;
 import org.onap.policy.drools.system.PolicyEngineConstants;
@@ -68,7 +67,7 @@ public class DroolsInitFeature implements PolicySessionFeatureApi {
          */
         public Init(final PolicySession policySession) {
             // insert this instance into Drools memory
-            final FactHandle factHandle = policySession.getKieSession().insert(this);
+            final var factHandle = policySession.getKieSession().insert(this);
 
             // after 10 minutes, remove the object from Drools memory (if needed)
             PolicyEngineConstants.getManager().getExecutorService().schedule(() -> {
index 57728dd..58679d4 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * feature-eelf
  * ================================================================================
- * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019, 2021 AT&T Intellectual Property. All rights reserved.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -21,7 +21,6 @@
 package org.onap.policy.drools.eelf;
 
 import com.att.eelf.configuration.Configuration;
-import java.nio.file.Path;
 import java.nio.file.Paths;
 import org.onap.policy.common.logging.flexlogger.FlexLogger;
 import org.onap.policy.common.logging.flexlogger.Logger;
@@ -39,7 +38,7 @@ public class EelfFeature implements PolicyEngineFeatureApi {
 
         String logback = System.getProperty(LoggerUtil.LOGBACK_CONFIGURATION_FILE_SYSTEM_PROPERTY,
                 LoggerUtil.LOGBACK_CONFIGURATION_FILE_DEFAULT);
-        Path logbackPath = Paths.get(logback);
+        var logbackPath = Paths.get(logback);
 
         if (System.getProperty(Configuration.PROPERTY_LOGGING_FILE_PATH) == null) {
             System.setProperty(Configuration.PROPERTY_LOGGING_FILE_PATH,
@@ -51,7 +50,7 @@ public class EelfFeature implements PolicyEngineFeatureApi {
                     logbackPath.getFileName().toString());
         }
 
-        Logger logger = FlexLogger.getLogger(this.getClass(), true);
+        var logger = FlexLogger.getLogger(this.getClass(), true);
 
         if (logger.isInfoEnabled()) {
             logProperty(logger, LoggerUtil.LOGBACK_CONFIGURATION_FILE_SYSTEM_PROPERTY);
index 418fe8e..8bbd19a 100644 (file)
@@ -74,11 +74,11 @@ public class HealthCheckManager implements HealthCheck {
      */
     @Override
     public Reports healthCheck() {
-        Reports reports = new Reports();
+        var reports = new Reports();
         boolean thisEngineIsAlive = getEngineManager().isAlive();
         reports.setHealthy(thisEngineIsAlive);
 
-        HealthCheck.Report engineReport = new Report();
+        var engineReport = new Report();
         engineReport.setHealthy(thisEngineIsAlive);
         engineReport.setName("PDP-D");
         engineReport.setUrl("self");
@@ -87,12 +87,12 @@ public class HealthCheckManager implements HealthCheck {
         reports.getDetails().add(engineReport);
 
         for (HttpClient client : clients) {
-            HealthCheck.Report report = new Report();
+            var report = new Report();
             report.setName(client.getName());
             report.setUrl(client.getBaseUrl());
             report.setHealthy(true);
             try {
-                Response response = client.get();
+                var response = client.get();
                 report.setCode(response.getStatus());
                 if (report.getCode() != 200) {
                     report.setHealthy(false);
index 8e97d3e..e0ac880 100644 (file)
@@ -109,9 +109,6 @@ public class LifecycleFsm implements Startable {
     @Getter
     protected TopicSinkClient client;
 
-    @Getter
-    protected final String name = PolicyEngineConstants.PDP_NAME;
-
     protected LifecycleState state = new LifecycleStateTerminated(this);
 
     @GsonJsonIgnore
@@ -180,6 +177,10 @@ public class LifecycleFsm implements Startable {
         stats.setPdpInstanceId(PolicyEngineConstants.PDP_NAME);
     }
 
+    public String getName() {
+        return PolicyEngineConstants.PDP_NAME;
+    }
+
     @GsonJsonIgnore
     public DomainMaker getDomainMaker() {
         return PolicyEngineConstants.getManager().getDomainMaker();
@@ -625,7 +626,7 @@ public class LifecycleFsm implements Startable {
 
     protected PdpStatus statusPayload(@NonNull PdpState state) {
         var status = new PdpStatus();
-        status.setName(name);
+        status.setName(getName());
         status.setPdpGroup(group);
         status.setPdpSubgroup(subGroup);
         status.setState(state);
index 4c92b67..db4f23d 100644 (file)
@@ -31,7 +31,6 @@ import lombok.NonNull;
 import org.apache.commons.lang3.tuple.Pair;
 import org.onap.policy.common.utils.coder.CoderException;
 import org.onap.policy.drools.domain.models.artifact.NativeArtifactPolicy;
-import org.onap.policy.drools.policies.DomainMaker;
 import org.onap.policy.models.pdp.concepts.PdpResponseDetails;
 import org.onap.policy.models.pdp.concepts.PdpStateChange;
 import org.onap.policy.models.pdp.concepts.PdpUpdate;
@@ -326,7 +325,7 @@ public abstract class LifecycleStateRunning extends LifecycleStateDefault {
     protected List<ToscaPolicy> syncPolicies(List<ToscaPolicy> policies,
                                    BiPredicate<PolicyTypeController, ToscaPolicy> sync) {
         List<ToscaPolicy> failedPolicies = new ArrayList<>();
-        DomainMaker domain = fsm.getDomainMaker();
+        var domain = fsm.getDomainMaker();
         for (ToscaPolicy policy : policies) {
             ToscaConceptIdentifier policyType = policy.getTypeIdentifier();
             PolicyTypeController controller = fsm.getController(policyType);
@@ -357,7 +356,7 @@ public abstract class LifecycleStateRunning extends LifecycleStateDefault {
     }
 
     protected PdpResponseDetails response(String requestId, PdpResponseStatus responseStatus, String message) {
-        PdpResponseDetails response = new PdpResponseDetails();
+        var response = new PdpResponseDetails();
         response.setResponseTo(requestId);
         response.setResponseStatus(responseStatus);
         if (message != null) {
index fa87617..5f12a2a 100644 (file)
@@ -140,7 +140,7 @@ public class PolicyTypeDroolsController implements PolicyTypeController {
     private boolean perform(ToscaPolicy policy, Predicate<PolicyController> operation) {
         try {
             List<PolicyController> selected = selectControllers(policy);
-            boolean success = true;
+            var success = true;
             for (PolicyController controller : selected) {
                 success = modifyController(operation, controller) && success;
             }
index fd98eed..7532dd5 100644 (file)
@@ -53,7 +53,7 @@ public class PolicyTypeNativeArtifactController implements PolicyTypeController
         PolicyController controller;
         try {
             nativePolicy = fsm.getDomainMaker().convertTo(policy, NativeArtifactPolicy.class);
-            DroolsConfiguration droolsConfig =
+            var droolsConfig =
                     new DroolsConfiguration(
                             nativePolicy.getProperties().getRulesArtifact().getArtifactId(),
                             nativePolicy.getProperties().getRulesArtifact().getGroupId(),
@@ -77,7 +77,7 @@ public class PolicyTypeNativeArtifactController implements PolicyTypeController
     public boolean undeploy(ToscaPolicy policy) {
         try {
             NativeArtifactPolicy nativePolicy = fsm.getDomainMaker().convertTo(policy, NativeArtifactPolicy.class);
-            DroolsConfiguration noConfig =
+            var noConfig =
                     new DroolsConfiguration(
                             DroolsControllerConstants.NO_ARTIFACT_ID,
                             DroolsControllerConstants.NO_GROUP_ID,
@@ -91,7 +91,7 @@ public class PolicyTypeNativeArtifactController implements PolicyTypeController
     }
 
     private boolean update(NativeArtifactPolicy nativePolicy, DroolsConfiguration droolsConfig) {
-        ControllerConfiguration controllerConfig =
+        var controllerConfig =
                 new ControllerConfiguration(nativePolicy.getProperties().getController().getName(),
                         ControllerConfiguration.CONFIG_CONTROLLER_OPERATION_UPDATE, droolsConfig);
         return PolicyEngineConstants.getManager().updatePolicyController(controllerConfig) != null;
index 1fa4439..49ea0af 100644 (file)
@@ -44,7 +44,7 @@ public class NoLockManager implements PolicyResourceLockManager, PolicyEngineFea
     @Override
     public Lock createLock(String resourceId, String ownerKey, int holdSec,
             LockCallback callback, boolean waitForLock) {
-        AlwaysSuccessLock successLock =  new AlwaysSuccessLock(resourceId, ownerKey, holdSec, callback);
+        var successLock =  new AlwaysSuccessLock(resourceId, ownerKey, holdSec, callback);
         successLock.notifyAvailable();
         return successLock;
     }
index ca7b6e2..5c61fb8 100644 (file)
@@ -138,12 +138,12 @@ public class PoolingFeature implements PolicyEngineFeatureApi, PolicyControllerF
 
         String name = controller.getName();
 
-        SpecProperties specProps = new SpecProperties(PoolingProperties.PREFIX, name, featProps);
+        var specProps = new SpecProperties(PoolingProperties.PREFIX, name, featProps);
 
         if (FeatureEnabledChecker.isFeatureEnabled(specProps, PoolingProperties.FEATURE_ENABLED)) {
             try {
                 // get & validate the properties
-                PoolingProperties props = new PoolingProperties(name, featProps);
+                var props = new PoolingProperties(name, featProps);
 
                 logger.info("pooling enabled for {}", name);
                 ctlr2pool.computeIfAbsent(name, xxx -> makeManager(host, controller, props, activeLatch));
index 769e703..a50997c 100644 (file)
@@ -22,7 +22,6 @@ package org.onap.policy.drools.pooling;
 
 import com.google.gson.JsonParseException;
 import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
 import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.ScheduledFuture;
 import java.util.concurrent.ScheduledThreadPoolExecutor;
@@ -516,7 +515,7 @@ public class PoolingManagerImpl implements PoolingManager, TopicListener {
 
             msg.checkValidity();
 
-            Method meth = current.getClass().getMethod("process", msg.getClass());
+            var meth = current.getClass().getMethod("process", msg.getClass());
             changeState((State) meth.invoke(current, msg));
 
         } catch (JsonParseException e) {
index d559a6d..584edce 100644 (file)
@@ -172,7 +172,7 @@ public class BucketAssignments {
             throw new PoolingFeatureException("too many hosts in message bucket assignments");
         }
 
-        for (int x = 0; x < hostArray.length; ++x) {
+        for (var x = 0; x < hostArray.length; ++x) {
             if (hostArray[x] == null) {
                 throw new PoolingFeatureException("bucket " + x + " has no assignment");
             }
@@ -181,8 +181,8 @@ public class BucketAssignments {
 
     @Override
     public int hashCode() {
-        final int prime = 31;
-        int result = 1;
+        final var prime = 31;
+        var result = 1;
         result = prime * result + Arrays.hashCode(hostArray);
         return result;
     }
index 9726c72..a53e757 100644 (file)
@@ -176,7 +176,7 @@ public class ActiveState extends ProcessingState {
      * Generates a heart beat for this host and its successor.
      */
     private void genHeartbeat() {
-        Heartbeat msg = makeHeartbeat(System.currentTimeMillis());
+        var msg = makeHeartbeat(System.currentTimeMillis());
         publish(getHost(), msg);
 
         if (succHost != null) {
index 02d5ab6..8bbb6ad 100644 (file)
@@ -124,7 +124,7 @@ public class ProcessingState extends State {
             throw new IllegalArgumentException(newLeader + " cannot replace " + alive.first());
         }
 
-        Leader msg = makeLeader(alive);
+        var msg = makeLeader(alive);
         logger.info("{}/{} hosts have an assignment", msg.getAssignments().getAllHosts().size(), alive.size());
 
         publish(msg);
@@ -193,7 +193,7 @@ public class ProcessingState extends State {
             return new String[BucketAssignments.MAX_BUCKETS];
         }
 
-        String[] newArray = new String[oldArray.length];
+        var newArray = new String[oldArray.length];
         System.arraycopy(oldArray, 0, newArray, 0, oldArray.length);
 
         return newArray;
@@ -231,7 +231,7 @@ public class ProcessingState extends State {
     private void addIndicesToHostBuckets(String[] bucket2host, Map<String, HostBucket> host2data) {
         LinkedList<Integer> nullBuckets = new LinkedList<>();
 
-        for (int x = 0; x < bucket2host.length; ++x) {
+        for (var x = 0; x < bucket2host.length; ++x) {
             String host = bucket2host[x];
             if (host == null) {
                 nullBuckets.add(x);
index 59bc4fd..c582d6e 100644 (file)
@@ -55,7 +55,7 @@ public class StartState extends State {
 
         super.start();
 
-        Heartbeat hb = makeHeartbeat(hbTimestampMs);
+        var hb = makeHeartbeat(hbTimestampMs);
         publish(getHost(), hb);
 
         /*
index 8fcbc79..14c7270 100644 (file)
@@ -36,10 +36,10 @@ public class JpaDroolsSessionConnector implements DroolsSessionConnector {
     @Override
     public DroolsSession get(String sessName) {
 
-        EntityManager em = emf.createEntityManager();
+        var em = emf.createEntityManager();
         DroolsSessionEntity entity = null;
 
-        try (EntityMgrTrans trans = new EntityMgrTrans(em)) {
+        try (var trans = new EntityMgrTrans(em)) {
 
             entity = em.find(DroolsSessionEntity.class, sessName);
             if (entity != null) {
@@ -58,9 +58,9 @@ public class JpaDroolsSessionConnector implements DroolsSessionConnector {
 
         logger.info("replace: Entering and manually updating session name= {}", sessName);
 
-        EntityManager em = emf.createEntityManager();
+        var em = emf.createEntityManager();
 
-        try (EntityMgrTrans trans = new EntityMgrTrans(em)) {
+        try (var trans = new EntityMgrTrans(em)) {
 
             if (!update(em, sess)) {
                 add(em, sess);
@@ -81,7 +81,7 @@ public class JpaDroolsSessionConnector implements DroolsSessionConnector {
     private void add(EntityManager em, DroolsSession sess) {
         logger.info("add: Inserting session id={}", sess.getSessionId());
 
-        DroolsSessionEntity ent = new DroolsSessionEntity(sess.getSessionName(), sess.getSessionId());
+        var ent = new DroolsSessionEntity(sess.getSessionName(), sess.getSessionId());
 
         em.persist(ent);
     }
index 0c75006..de37893 100644 (file)
@@ -94,7 +94,7 @@ public class DbAudit extends DroolsPdpIntegrityMonitor.AuditBase {
         // create connection to DB
         phase = "creating connection";
         logger.debug("DbAudit: Creating connection to {}", url);
-        try (Connection connection = DriverManager.getConnection(url, user, password)) {
+        try (var connection = DriverManager.getConnection(url, user, password)) {
 
             // create audit table, if needed
             if (doCreate) {
@@ -104,7 +104,7 @@ public class DbAudit extends DroolsPdpIntegrityMonitor.AuditBase {
 
             // insert an entry into the table
             phase = "insert entry";
-            String key = UUID.randomUUID().toString();
+            var key = UUID.randomUUID().toString();
             insertEntry(connection, key);
 
             phase = "fetch entry";
index b2878da..8dd735e 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-2019, 2021 AT&T Intellectual Property. All rights reserved.
  * Modifications Copyright (C) 2021 Nordix Foundation.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
@@ -68,10 +68,10 @@ public class IntegrityMonitorRestManager {
         // request.
         synchronized (IntegrityMonitorRestManager.class) {
             // will include messages associated with subsystem failures
-            StringBuilder body = new StringBuilder();
+            var body = new StringBuilder();
 
             // 200=SUCCESS, 500=failure
-            int responseValue = 200;
+            var responseValue = 200;
 
             if (im == null) {
                 try {
index 29576c4..f592258 100644 (file)
@@ -35,7 +35,6 @@ import java.util.Properties;
 import java.util.Set;
 import java.util.TreeSet;
 import java.util.concurrent.TimeUnit;
-import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 import lombok.AllArgsConstructor;
 import lombok.Getter;
@@ -79,14 +78,14 @@ public class RepositoryAudit extends DroolsPdpIntegrityMonitor.AuditBase {
      */
     private static TreeSet<Integer> countAdditionalNexusRepos() {
         TreeSet<Integer> returnIndices = new TreeSet<>();
-        Properties properties = StateManagementProperties.getProperties();
+        var properties = StateManagementProperties.getProperties();
         Set<String> propertyNames = properties.stringPropertyNames();
 
         for (String currName : propertyNames) {
-            Matcher matcher = repoPattern.matcher(currName);
+            var matcher = repoPattern.matcher(currName);
 
             if (matcher.matches()) {
-                int currRepoNum = Integer.parseInt(matcher.group(2));
+                var currRepoNum = Integer.parseInt(matcher.group(2));
                 if (propertyNames.contains(matcher.group(1) + ".audit.url")) {
                     returnIndices.add(currRepoNum);
                 }
@@ -104,7 +103,7 @@ public class RepositoryAudit extends DroolsPdpIntegrityMonitor.AuditBase {
     public void invoke(Properties properties) throws IntegrityMonitorException {
         logger.debug("Running 'RepositoryAudit.invoke'");
 
-        InvokeData data = new InvokeData();
+        var data = new InvokeData();
 
         logger.debug("RepositoryAudit.invoke: repoAuditIsActive = {}" + ", repoAuditIgnoreErrors = {}",
                 data.repoAuditIsActive, data.repoAuditIgnoreErrors);
@@ -179,7 +178,7 @@ public class RepositoryAudit extends DroolsPdpIntegrityMonitor.AuditBase {
          */
 
         // output file = ${dir}/out (this supports step '4a')
-        File output = data.dir.resolve("out").toFile();
+        var output = data.dir.resolve("out").toFile();
 
         // invoke process, and wait for response
         int rval = data.runMaven(output);
@@ -319,7 +318,7 @@ public class RepositoryAudit extends DroolsPdpIntegrityMonitor.AuditBase {
         }
 
         public void initTimeout() {
-            String timeoutString = getProperty("audit.timeout", true);
+            var timeoutString = getProperty("audit.timeout", true);
             if (timeoutString != null && !timeoutString.isEmpty()) {
                 try {
                     timeoutInSeconds = Long.valueOf(timeoutString);
@@ -345,7 +344,7 @@ public class RepositoryAudit extends DroolsPdpIntegrityMonitor.AuditBase {
             }
 
             // create text file to write
-            try (FileOutputStream fos = new FileOutputStream(dir.resolve("repository-audit.txt").toFile())) {
+            try (var fos = new FileOutputStream(dir.resolve("repository-audit.txt").toFile())) {
                 fos.write(version.getBytes());
             }
 
@@ -372,7 +371,7 @@ public class RepositoryAudit extends DroolsPdpIntegrityMonitor.AuditBase {
 
             artifacts.add(new Artifact("org.apache.maven/maven-embedder/3.2.2"));
 
-            StringBuilder sb = new StringBuilder();
+            var sb = new StringBuilder();
             sb.append(
                     "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
                             + "         xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n"
@@ -399,7 +398,7 @@ public class RepositoryAudit extends DroolsPdpIntegrityMonitor.AuditBase {
                     + "           </execution>\n" + "         </executions>\n" + "      </plugin>\n"
                     + "    </plugins>\n" + "  </build>\n" + "</project>\n");
 
-            try (FileOutputStream fos = new FileOutputStream(pom.toFile())) {
+            try (var fos = new FileOutputStream(pom.toFile())) {
                 fos.write(sb.toString().getBytes());
             }
         }
@@ -455,9 +454,9 @@ public class RepositoryAudit extends DroolsPdpIntegrityMonitor.AuditBase {
     private void generateDownloadLogs(File output) throws IOException {
         // place output in 'fileContents' (replacing the Return characters
         // with Newline)
-        byte[] outputData = new byte[(int) output.length()];
+        var outputData = new byte[(int) output.length()];
         String fileContents;
-        try (FileInputStream fis = new FileInputStream(output)) {
+        try (var fis = new FileInputStream(output)) {
             //
             // Ideally this should be in a loop or even better use
             // Java 8 nio functionality.
@@ -469,7 +468,7 @@ public class RepositoryAudit extends DroolsPdpIntegrityMonitor.AuditBase {
 
         // generate log messages from 'Downloading' and 'Downloaded'
         // messages within the 'mvn' output
-        int index = 0;
+        var index = 0;
         while ((index = fileContents.indexOf("\nDown", index)) > 0) {
             index += 5;
             if (fileContents.regionMatches(index, "loading: ", 0, 9)) {
@@ -502,7 +501,7 @@ public class RepositoryAudit extends DroolsPdpIntegrityMonitor.AuditBase {
      */
     static int runProcess(long timeoutInSeconds, File directory, File stdout, String... command)
             throws IOException, InterruptedException {
-        ProcessBuilder pb = new ProcessBuilder(command);
+        var pb = new ProcessBuilder(command);
         if (directory != null) {
             pb.directory(directory);
         }
@@ -510,7 +509,7 @@ public class RepositoryAudit extends DroolsPdpIntegrityMonitor.AuditBase {
             pb.redirectOutput(stdout);
         }
 
-        Process process = pb.start();
+        var process = pb.start();
         if (process.waitFor(timeoutInSeconds, TimeUnit.SECONDS)) {
             // process terminated before the timeout
             return process.exitValue();
index 3dbb8d3..8f5e4e3 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * feature-state-management
  * ================================================================================
- * Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -21,7 +21,6 @@
 package org.onap.policy.drools.statemanagement;
 
 import java.io.IOException;
-import java.util.Properties;
 import org.onap.policy.common.im.AllSeemsWellException;
 import org.onap.policy.common.im.IntegrityMonitorException;
 import org.onap.policy.common.im.StateChangeNotifier;
@@ -238,8 +237,7 @@ public class StateManagementFeature implements StateManagementFeatureApi,
     private static void initializeProperties(String configDir) {
         //Get the state management properties
         try {
-            Properties props =
-                    PropertyUtil.getProperties(configDir + "/feature-state-management.properties");
+            var props = PropertyUtil.getProperties(configDir + "/feature-state-management.properties");
             StateManagementProperties.initProperties(props);
             logger.info("initializeProperties: resourceName= {}",
                     StateManagementProperties.getProperty(StateManagementProperties.NODE_NAME));
index bfd94df..c9af746 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * ONAP
  * ================================================================================
- * Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -165,7 +165,7 @@ public class TtControllerTask implements Runnable {
 
     @Override
     public String toString() {
-        final StringBuilder builder = new StringBuilder();
+        final var builder = new StringBuilder();
         builder.append("TTControllerTask [controller=");
         builder.append(this.controller);
         builder.append(", alive=");
index e92d05d..3d16735 100644 (file)
@@ -34,7 +34,6 @@ import org.onap.policy.common.utils.security.CryptoUtils;
 import org.onap.policy.drools.persistence.SystemPersistenceConstants;
 import org.onap.policy.drools.properties.DroolsPropertyConstants;
 import org.onap.policy.drools.utils.PropertyUtil;
-import org.onap.policy.drools.utils.logging.LoggerUtil;
 import org.onap.policy.drools.utils.logging.MdcTransaction;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
index d5f7ae0..7252179 100644 (file)
@@ -82,7 +82,6 @@ import org.onap.policy.drools.server.restful.aaf.AafTelemetryAuthFilter;
 import org.onap.policy.drools.stats.PolicyStatsManager;
 import org.onap.policy.drools.system.internal.SimpleLockManager;
 import org.onap.policy.drools.utils.PropertyUtil;
-import org.onap.policy.drools.utils.logging.LoggerUtil;
 import org.onap.policy.drools.utils.logging.MdcTransaction;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
index 9c6dad7..10788eb 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * ONAP
  * ================================================================================
- * Copyright (C) 2017-2019,2021 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019, 2021 AT&T Intellectual Property. All rights reserved.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -22,8 +22,6 @@ package org.onap.policy.drools.utils.logging;
 
 import lombok.AccessLevel;
 import lombok.NoArgsConstructor;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
 
 /**
  * Loger Utils.
@@ -31,8 +29,6 @@ import org.slf4j.LoggerFactory;
 @NoArgsConstructor(access = AccessLevel.PRIVATE)
 public final class LoggerUtil {
 
-    private static final Logger LOGGER = LoggerFactory.getLogger(LoggerUtil.class);
-
     /**
      * Logback configuration file system property.
      */
@@ -44,4 +40,3 @@ public final class LoggerUtil {
     public static final String LOGBACK_CONFIGURATION_FILE_DEFAULT = "config/logback.xml";
 
 }
-