sonars policy-utils and feature-lifecycle 09/121209/1
authorjhh <jorge.hernandez-herrero@att.com>
Fri, 7 May 2021 23:09:13 +0000 (18:09 -0500)
committerjhh <jorge.hernandez-herrero@att.com>
Fri, 7 May 2021 23:09:13 +0000 (18:09 -0500)
Issue-ID: POLICY-3289
Signed-off-by: jhh <jorge.hernandez-herrero@att.com>
Change-Id: Iaf7423f840fb39a27c3e5fd293159d1336d5557a

feature-lifecycle/src/main/java/org/onap/policy/drools/lifecycle/LifecycleFsm.java
feature-lifecycle/src/main/java/org/onap/policy/drools/lifecycle/PolicyTypeNativeDroolsController.java
feature-lifecycle/src/main/java/org/onap/policy/drools/server/restful/RestLifecycleManager.java
feature-lifecycle/src/test/java/org/onap/policy/drools/lifecycle/LifecycleStatePassiveTest.java
policy-management/src/main/java/org/onap/policy/drools/controller/internal/MavenDroolsController.java
policy-management/src/main/java/org/onap/policy/drools/system/IndexedPolicyControllerFactory.java
policy-management/src/main/java/org/onap/policy/drools/system/PolicyEngineManager.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/main/java/org/onap/policy/drools/utils/logging/LoggerUtil.java

index c4f2f87..5882025 100644 (file)
@@ -595,7 +595,7 @@ public class LifecycleFsm implements Startable {
     }
 
     private boolean stopTimers() {
-        boolean success = true;
+        var success = true;
         if (statusTask != null) {
             success = statusTask.cancel(false);
         }
@@ -613,7 +613,7 @@ public class LifecycleFsm implements Startable {
     }
 
     protected PdpStatus statusPayload(@NonNull PdpState state) {
-        PdpStatus status = new PdpStatus();
+        var status = new PdpStatus();
         status.setName(name);
         status.setPdpGroup(group);
         status.setPdpSubgroup(subGroup);
@@ -629,7 +629,7 @@ public class LifecycleFsm implements Startable {
      * It provides a snapshot of the current statistics.
      */
     public PdpStatistics statisticsPayload() {
-        PdpStatistics updateStats = new PdpStatistics(stats);
+        var updateStats = new PdpStatistics(stats);
         updateStats.setTimeStamp(Instant.now());
 
         try {
@@ -754,7 +754,7 @@ public class LifecycleFsm implements Startable {
     // these may be overridden by junit tests
 
     protected ScheduledExecutorService makeExecutor() {
-        ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor(1);
+        var exec = new ScheduledThreadPoolExecutor(1);
         exec.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
         exec.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
         exec.setRemoveOnCancelPolicy(true);
index cb7da95..361b4b1 100644 (file)
@@ -63,8 +63,8 @@ public class PolicyTypeNativeDroolsController implements PolicyTypeController {
 
     @Override
     public boolean deploy(ToscaPolicy policy) {
-        Properties controllerProps = new Properties();
-        ControllerPolicy controllerPolicy = toDomainPolicy(policy);
+        var controllerProps = new Properties();
+        var controllerPolicy = toDomainPolicy(policy);
         if (controllerPolicy == null) {
             return false;
         }
index 381fd60..494c708 100644 (file)
@@ -151,7 +151,7 @@ public class RestLifecycleManager {
     public Response updateState(
         @ApiParam(value = "state", required = true) @PathParam("state") String state) {
 
-        PdpStateChange change = new PdpStateChange();
+        var change = new PdpStateChange();
         change.setPdpGroup(LifecycleFeature.getFsm().getGroup());
         change.setPdpSubgroup(LifecycleFeature.getFsm().getSubGroup());
         change.setState(PdpState.valueOf(state));
@@ -273,12 +273,12 @@ public class RestLifecycleManager {
     public Response deployTrackedPolicy(
             @ApiParam(value = "Tosca Policy", required = true) String policy) {
 
-        ToscaPolicy toscaPolicy = getToscaPolicy(policy);
+        var toscaPolicy = getToscaPolicy(policy);
         if (toscaPolicy == null) {
             return Response.status(Response.Status.NOT_ACCEPTABLE).build();
         }
 
-        PolicyTypeController typeController = getPolicyTypeController(toscaPolicy);
+        var typeController = getPolicyTypeController(toscaPolicy);
         if (typeController == null) {
             return Response.status(Response.Status.NOT_FOUND).build();
         }
@@ -386,7 +386,7 @@ public class RestLifecycleManager {
     @Path("policies/operations/validation")
     @ApiOperation(value = "Validates a policy", responseContainer = "List")
     public Response validateOperation(@ApiParam(value = "Tosca Policy", required = true) String policy) {
-        ToscaPolicy toscaPolicy = getToscaPolicy(policy);
+        var toscaPolicy = getToscaPolicy(policy);
         if (toscaPolicy == null) {
             return Response.status(Response.Status.NOT_ACCEPTABLE).build();
         }
@@ -413,12 +413,12 @@ public class RestLifecycleManager {
     }
 
     private Response deployUndeployOperation(String policy, boolean deploy) {
-        ToscaPolicy toscaPolicy = getToscaPolicy(policy);
+        var toscaPolicy = getToscaPolicy(policy);
         if (toscaPolicy == null) {
             return Response.status(Response.Status.NOT_ACCEPTABLE).build();
         }
 
-        PolicyTypeController typeController = getPolicyTypeController(toscaPolicy);
+        var typeController = getPolicyTypeController(toscaPolicy);
         if (typeController == null) {
             return Response.status(Response.Status.NOT_FOUND).build();
         }
@@ -441,7 +441,7 @@ public class RestLifecycleManager {
     }
 
     private PdpUpdate getPolicyUpdate() {
-        PdpUpdate update = new PdpUpdate();
+        var update = new PdpUpdate();
         update.setName(LifecycleFeature.getFsm().getName());
         update.setPdpGroup(LifecycleFeature.getFsm().getGroup());
         update.setPdpSubgroup(LifecycleFeature.getFsm().getSubGroup());
index 13d6591..f4772eb 100644 (file)
@@ -29,7 +29,6 @@ import static org.junit.Assert.assertNull;
 import static org.junit.Assert.assertSame;
 import static org.junit.Assert.assertTrue;
 
-import java.io.IOException;
 import java.util.List;
 import java.util.concurrent.TimeUnit;
 import org.junit.Before;
@@ -254,7 +253,7 @@ public class LifecycleStatePassiveTest extends LifecycleStateRunningTest {
     }
 
     @Test
-    public void testStateChange() throws CoderException, IOException {
+    public void testStateChange() throws CoderException {
         /* no name */
         PdpStateChange change = new PdpStateChange();
         change.setPdpGroup("A");
index 6ddcc36..3bd339a 100644 (file)
@@ -34,7 +34,6 @@ import org.kie.api.definition.KiePackage;
 import org.kie.api.definition.rule.Query;
 import org.kie.api.runtime.KieSession;
 import org.kie.api.runtime.rule.FactHandle;
-import org.kie.api.runtime.rule.QueryResults;
 import org.kie.api.runtime.rule.QueryResultsRow;
 import org.onap.policy.common.endpoints.event.comm.TopicSink;
 import org.onap.policy.common.gson.annotation.GsonJsonIgnore;
@@ -71,7 +70,7 @@ public class MavenDroolsController implements DroolsController {
     /**
      * logger.
      */
-    private static Logger  logger = LoggerFactory.getLogger(MavenDroolsController.class);
+    private static final Logger logger = LoggerFactory.getLogger(MavenDroolsController.class);
 
     /**
      * Policy Container, the access object to the policy-core layer.
@@ -262,7 +261,7 @@ public class MavenDroolsController implements DroolsController {
         for (TopicCoderFilterConfiguration coderConfig: coderConfigurations) {
             String topic = coderConfig.getTopic();
 
-            CustomGsonCoder customGsonCoder = getCustomCoder(coderConfig);
+            var customGsonCoder = getCustomCoder(coderConfig);
 
             List<PotentialCoderFilter> coderFilters = coderConfig.getCoderFilters();
             if (coderFilters == null || coderFilters.isEmpty()) {
@@ -301,7 +300,7 @@ public class MavenDroolsController implements DroolsController {
     }
 
     private CustomGsonCoder getCustomCoder(TopicCoderFilterConfiguration coderConfig) {
-        CustomGsonCoder customGsonCoder = coderConfig.getCustomGsonCoder();
+        var customGsonCoder = coderConfig.getCustomGsonCoder();
         if (customGsonCoder != null
                 && customGsonCoder.getClassContainer() != null
                 && !customGsonCoder.getClassContainer().isEmpty()) {
@@ -745,8 +744,8 @@ public class MavenDroolsController implements DroolsController {
 
         Map<String, Integer> classNames = new HashMap<>();
 
-        PolicySession session = getSession(sessionName);
-        KieSession kieSession = session.getKieSession();
+        var session = getSession(sessionName);
+        var kieSession = session.getKieSession();
 
         Collection<FactHandle> facts = kieSession.getFactHandles();
         for (FactHandle fact : facts) {
@@ -775,8 +774,7 @@ public class MavenDroolsController implements DroolsController {
     public long factCount(String sessionName) {
         validateSessionName(sessionName);
 
-        PolicySession session = getSession(sessionName);
-        return session.getKieSession().getFactCount();
+        return getSession(sessionName).getKieSession().getFactCount();
     }
 
     @Override
@@ -793,8 +791,8 @@ public class MavenDroolsController implements DroolsController {
             throw new IllegalArgumentException("Class cannot be fetched in model's classloader: " + className);
         }
 
-        PolicySession session = getSession(sessionName);
-        KieSession kieSession = session.getKieSession();
+        var session = getSession(sessionName);
+        var kieSession = session.getKieSession();
 
         List<Object> factObjects = new ArrayList<>();
 
@@ -835,14 +833,14 @@ public class MavenDroolsController implements DroolsController {
             throw new IllegalArgumentException("Invalid Queried Entity: " + queriedEntity);
         }
 
-        PolicySession session = getSession(sessionName);
-        KieSession kieSession = session.getKieSession();
+        var session = getSession(sessionName);
+        var kieSession = session.getKieSession();
 
         validateQueryName(kieSession, queryName);
 
         List<Object> factObjects = new ArrayList<>();
 
-        QueryResults queryResults = kieSession.getQueryResults(queryName, queryParams);
+        var queryResults = kieSession.getQueryResults(queryName, queryParams);
         for (QueryResultsRow row : queryResults) {
             try {
                 factObjects.add(row.get(queriedEntity));
@@ -871,11 +869,11 @@ public class MavenDroolsController implements DroolsController {
 
     @Override
     public <T> boolean delete(@NonNull String sessionName, @NonNull T objFact) {
-        KieSession kieSession = getSession(sessionName).getKieSession();
+        var kieSession = getSession(sessionName).getKieSession();
 
         // try first to get the object to delete first by reference
 
-        FactHandle quickFact = kieSession.getFactHandle(objFact);
+        var quickFact = kieSession.getFactHandle(objFact);
         if (quickFact != null) {
             logger.info("Fast delete of {} from {}", objFact, sessionName);
             kieSession.delete(quickFact);
@@ -906,10 +904,10 @@ public class MavenDroolsController implements DroolsController {
 
     @Override
     public <T> boolean delete(@NonNull String sessionName, @NonNull Class<T> fact) {
-        PolicySession session = getSession(sessionName);
-        KieSession kieSession = session.getKieSession();
+        var session = getSession(sessionName);
+        var kieSession = session.getKieSession();
 
-        boolean success = true;
+        var success = true;
         Collection<FactHandle> factHandles = kieSession.getFactHandles(new ClassObjectFilter(fact));
         for (FactHandle factHandle : factHandles) {
             try {
@@ -929,7 +927,7 @@ public class MavenDroolsController implements DroolsController {
 
     @Override
     public <T> boolean exists(@NonNull String sessionName, @NonNull T objFact) {
-        KieSession kieSession = getSession(sessionName).getKieSession();
+        var kieSession = getSession(sessionName).getKieSession();
         if (kieSession.getFactHandle(objFact) != null) {
             return true;
         }
@@ -965,7 +963,7 @@ public class MavenDroolsController implements DroolsController {
     @Override
     public Object[] getRecentSourceEvents() {
         synchronized (this.recentSourceEvents) {
-            Object[] events = new Object[recentSourceEvents.size()];
+            var events = new Object[recentSourceEvents.size()];
             return recentSourceEvents.toArray(events);
         }
     }
@@ -978,7 +976,7 @@ public class MavenDroolsController implements DroolsController {
     @Override
     public String[] getRecentSinkEvents() {
         synchronized (this.recentSinkEvents) {
-            String[] events = new String[recentSinkEvents.size()];
+            var events = new String[recentSinkEvents.size()];
             return recentSinkEvents.toArray(events);
         }
     }
@@ -991,18 +989,8 @@ public class MavenDroolsController implements DroolsController {
 
     @Override
     public String toString() {
-        StringBuilder builder = new StringBuilder();
-        builder
-            .append("MavenDroolsController [policyContainer=")
-            .append(policyContainer.getName())
-            .append(":")
-            .append(", alive=")
-            .append(alive)
-            .append(", locked=")
-            .append(", modelClassLoaderHash=")
-            .append(modelClassLoaderHash)
-            .append("]");
-        return builder.toString();
+        return "MavenDroolsController [policyContainer=" + policyContainer.getName() + ":" + ", alive=" + alive
+                        + ", locked=" + ", modelClassLoaderHash=" + modelClassLoaderHash + "]";
     }
 
     // these may be overridden by junit tests
index 84247ef..56e3f3f 100644 (file)
@@ -76,7 +76,7 @@ class IndexedPolicyControllerFactory implements PolicyControllerFactory {
 
         /* A PolicyController does not exist */
 
-        PolicyController controller = newPolicyController(name, properties);
+        var controller = newPolicyController(name, properties);
 
         String coordinates = toKey(controller.getDrools().getGroupId(),
                                    controller.getDrools().getArtifactId());
index 25601c8..ec24286 100644 (file)
@@ -56,7 +56,6 @@ import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties;
 import org.onap.policy.common.gson.annotation.GsonJsonIgnore;
 import org.onap.policy.common.gson.annotation.GsonJsonProperty;
 import org.onap.policy.common.utils.services.FeatureApiUtils;
-import org.onap.policy.drools.controller.DroolsController;
 import org.onap.policy.drools.controller.DroolsControllerConstants;
 import org.onap.policy.drools.core.PolicyContainer;
 import org.onap.policy.drools.core.jmx.PdpJmxListener;
@@ -227,7 +226,7 @@ class PolicyEngineManager implements PolicyEngine {
 
     @Override
     public final Properties defaultTelemetryConfig() {
-        final Properties defaultConfig = new Properties();
+        final var defaultConfig = new Properties();
 
         defaultConfig.put(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES, "TELEMETRY");
         defaultConfig.put(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + TELEMETRY_SERVER_DEFAULT_NAME
@@ -379,7 +378,7 @@ class PolicyEngineManager implements PolicyEngine {
 
         final String entity = config.getEntity();
 
-        MdcTransaction mdcTrans = MdcTransaction.newTransaction(config.getRequestId(), "brmsgw");
+        var mdcTrans = MdcTransaction.newTransaction(config.getRequestId(), "brmsgw");
         if (this.getSources().size() == 1) {
             Topic topic = this.getSources().get(0);
             mdcTrans.setServiceName(topic.getTopic()).setRemoteHost(topic.getServers().toString())
@@ -459,7 +458,7 @@ class PolicyEngineManager implements PolicyEngine {
                     .setTargetServiceName(configController.getOperation())
                     .setTargetVirtualEntity("" + configController.getDrools());
             try {
-                final PolicyController policyController = this.updatePolicyController(configController);
+                var policyController = this.updatePolicyController(configController);
                 policyControllers.add(policyController);
                 mdcTrans.setStatusCode(true).transaction();
             } catch (final Exception e) {
@@ -493,7 +492,7 @@ class PolicyEngineManager implements PolicyEngine {
                 throw new IllegalArgumentException("operation must be provided");
             }
 
-            PolicyController policyController = getController(controllerName);
+            var policyController = getController(controllerName);
             if (policyController == null) {
                 policyController = findController(controllerName, operation);
 
@@ -533,7 +532,7 @@ class PolicyEngineManager implements PolicyEngine {
 
         logger.warn("controller {} does not exist. Attempting recovery from disk", controllerName);
 
-        final Properties controllerProperties =
+        var controllerProperties =
                 getPersistenceManager().getControllerProperties(controllerName);
 
         /*
@@ -795,7 +794,7 @@ class PolicyEngineManager implements PolicyEngine {
          * ..) are stuck
          */
 
-        Thread exitThread = makeShutdownThread();
+        var exitThread = makeShutdownThread();
         exitThread.start();
 
         /* policy-engine dispatch pre shutdown hook */
@@ -940,7 +939,7 @@ class PolicyEngineManager implements PolicyEngine {
 
         this.locked = true;
 
-        boolean success = true;
+        var success = true;
         final List<PolicyController> controllers = getControllerFactory().inventory();
         for (final PolicyController controller : controllers) {
             try {
@@ -1201,7 +1200,7 @@ class PolicyEngineManager implements PolicyEngine {
          * additional processing
          */
         try {
-            final DroolsController droolsController = getProtocolCoder().getDroolsController(topic, event);
+            var droolsController = getProtocolCoder().getDroolsController(topic, event);
             final PolicyController controller = getControllerFactory().get(droolsController);
             if (controller != null) {
                 return controller.deliver(busType, topic, event);
@@ -1246,7 +1245,7 @@ class PolicyEngineManager implements PolicyEngine {
         }
 
         try {
-            final TopicSink sink = getTopicEndpointManager().getTopicSink(busType, topic);
+            var sink = getTopicEndpointManager().getTopicSink(busType, topic);
 
             if (sink == null) {
                 throw new IllegalStateException("Inconsistent State: " + this);
@@ -1411,7 +1410,7 @@ class PolicyEngineManager implements PolicyEngine {
     }
 
     protected ScheduledExecutorService makeScheduledExecutor(int nthreads) {
-        ScheduledThreadPoolExecutor exsvc = new ScheduledThreadPoolExecutor(nthreads);
+        var exsvc = new ScheduledThreadPoolExecutor(nthreads);
         exsvc.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
         exsvc.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
         exsvc.setRemoveOnCancelPolicy(true);
index 3796665..6266f17 100644 (file)
@@ -162,7 +162,7 @@ public class DomainMaker {
         // A known schema is one that embedded in a .jar in the classpath as a resource
         // matching the following syntax: <policy-type-name>-<policy-type-version>.schema.json.
         //
-        String schema =
+        var schema =
                 ResourceUtils
                         .getResourceAsString("schemas/"
                             + policyType.getName() + "-" + policyType.getVersion() + ".schema.json");
index 4d28717..10871e7 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * ONAP
  * ================================================================================
- * 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.
@@ -31,7 +31,6 @@ 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;
 import org.onap.policy.common.utils.security.CryptoCoder;
@@ -50,8 +49,7 @@ public class PropertyUtil {
     private static Timer timer = null;
 
     // this table maps canonical file into a 'ListenerRegistration' instance
-    private static HashMap<File, ListenerRegistration> registrations =
-            new HashMap<>();
+    private static final HashMap<File, ListenerRegistration> registrations = new HashMap<>();
 
     private static final Logger logger = LoggerFactory.getLogger(PropertyUtil.class.getName());
 
@@ -137,7 +135,7 @@ public class PropertyUtil {
      *     a problem loading the properties file.
      */
     public static Properties getProperties(File file, Listener listener) throws IOException {
-        File propFile = file;
+        var propFile = file;
         if (listener == null) {
             // no listener specified -- just fetch the properties
             return getProperties(propFile);
@@ -198,7 +196,7 @@ public class PropertyUtil {
      * @return Properties - interpolated properties object
      */
     public static Properties getInterpolatedProperties(Properties properties, CryptoCoder cryptoCoder) {
-        Configuration config = ConfigurationConverter.getConfiguration(properties);
+        var config = ConfigurationConverter.getConfiguration(properties);
         config.getInterpolator()
             .registerLookup(ENV_WITH_DEFAULT_PROPERTY_PREFIX, new EnvironmentVariableWithDefaultLookup());
 
@@ -207,7 +205,7 @@ public class PropertyUtil {
         }
 
         config.getInterpolator().registerLookup(CRYPTO_CODER_PROPERTY_PREFIX, new CryptoCoderValueLookup(cryptoCoder));
-        Properties props = ConfigurationConverter.getProperties(config);
+        var props = ConfigurationConverter.getProperties(config);
         props.stringPropertyNames().forEach(key -> props.setProperty(key, cryptoCoder.decrypt(props.getProperty(key))));
         return props;
     }
@@ -223,8 +221,8 @@ public class PropertyUtil {
      */
     protected static Properties getPropertiesFile(File file) throws IOException {
         // create an InputStream (may throw a FileNotFoundException)
-        Properties rval = new Properties();
-        try (FileInputStream fis = new FileInputStream(file)) {
+        var rval = new Properties();
+        try (var fis = new FileInputStream(file)) {
             // create the properties instance
 
             // load properties (may throw an IOException)
@@ -381,7 +379,7 @@ public class PropertyUtil {
                 lastModified = timestamp;
 
                 // Save old set, and initial set of changed properties.
-                Properties oldProperties = properties;
+                var oldProperties = properties;
                 HashSet<String> changedProperties =
                         new HashSet<>(oldProperties.stringPropertyNames());
 
@@ -418,19 +416,12 @@ public class PropertyUtil {
                     for (final Listener notify : listeners) {
                         // Copy 'properties' and 'changedProperties', so it doesn't
                         // cause problems if the recipient makes changes.
-                        final Properties tmpProperties =
-                                (Properties) properties.clone();
-                        final HashSet<String> tmpChangedProperties =
-                                new HashSet<>(changedProperties);
+                        final var tmpProperties = (Properties) properties.clone();
+                        final HashSet<String> tmpChangedProperties = new HashSet<>(changedProperties);
 
                         // Do the notification in a separate thread, so blocking
                         // won't cause any problems.
-                        new Thread() {
-                            @Override
-                            public void run() {
-                                notify.propertiesChanged(tmpProperties, tmpChangedProperties);
-                            }
-                        }.start();
+                        new Thread(() -> notify.propertiesChanged(tmpProperties, tmpChangedProperties)).start();
                     }
                 }
             }
index 1697f69..6086752 100644 (file)
@@ -2,7 +2,7 @@
  * ============LICENSE_START=======================================================
  * ONAP
  * ================================================================================
- * 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.
@@ -81,7 +81,7 @@ public class LoggerUtil {
         }
 
         final LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
-        final ch.qos.logback.classic.Logger logger = context.getLogger(loggerName);
+        final var logger = context.getLogger(loggerName);
         if (logger == null) {
             throw new IllegalArgumentException("no logger " + loggerName);
         }