Fix sonar issues 44/105744/3
authorhuaxing <huaxing.jin@est.tech>
Fri, 10 Apr 2020 05:16:12 +0000 (13:16 +0800)
committerhuaxing <huaxing.jin@est.tech>
Wed, 15 Apr 2020 02:39:36 +0000 (10:39 +0800)
Issue-ID: POLICY-1913
Signed-off-by: huaxing <huaxing.jin@est.tech>
Change-Id: Id1a9a6b6f7a9c8c74dd69bd0d30af05162a92cd1

examples/examples-adaptive/src/main/java/org/onap/policy/apex/examples/adaptive/model/java/AnomalyDetectionPolicyDecideTaskSelectionLogic.java
model/basic-model/src/main/java/org/onap/policy/apex/model/basicmodel/concepts/AxKeyInfo.java
plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-grpc/src/main/java/org/onap/policy/apex/plugins/event/carrier/grpc/ApexGrpcProducer.java
testsuites/integration/integration-common/src/main/java/org/onap/policy/apex/testsuites/integration/common/model/java/DefaultTaskLogic.java

index ffbaf59..99dd28d 100644 (file)
@@ -1,6 +1,7 @@
 /*-
  * ============LICENSE_START=======================================================
  *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
+ *  Modifications Copyright (C) 2020 Nordix Foundation.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -37,7 +38,6 @@ import org.slf4j.Logger;
  * The Class AnomalyDetectionPolicyDecideTaskSelectionLogic.
  */
 public class AnomalyDetectionPolicyDecideTaskSelectionLogic {
-    private Logger logger;
 
     // Recurring string constants
     private static final String ANOMALY_DETECTION_ALBUM = "AnomalyDetectionAlbum";
@@ -71,8 +71,6 @@ public class AnomalyDetectionPolicyDecideTaskSelectionLogic {
     }
     // CHECKSTYLE:ON: checkstyle:magicNumber
 
-    private volatile TaskSelectionExecutionContext executionContext;
-
     /**
      * Gets the task.
      *
@@ -80,16 +78,14 @@ public class AnomalyDetectionPolicyDecideTaskSelectionLogic {
      * @return the task
      */
     public boolean getTask(final TaskSelectionExecutionContext executor) {
-        executionContext = executor;
-        logger = executionContext.logger;
         String id = executor.subject.getId();
-        logger.debug(id);
+        executor.logger.debug(id);
         String inFields = executor.inFields.toString();
-        logger.debug(inFields);
+        executor.logger.debug(inFields);
         final double now = (Double) (executor.inFields.get("MonitoredValue"));
         final Integer iteration = (Integer) (executor.inFields.get("Iteration"));
         // get the double[forecastedValue, AnomalyScore, AnomalyProbability]
-        final double[] vals = this.forecastingAndAnomaly(now);
+        final double[] vals = forecastingAndAnomaly(executor, now);
         final double anomalyness = vals[2];
         String task = null;
         for (final Map.Entry<double[], String> i : TASK_INTERVALS.entrySet()) {
@@ -99,17 +95,14 @@ public class AnomalyDetectionPolicyDecideTaskSelectionLogic {
             }
         }
         if (task == null) {
-            executionContext.subject.getDefaultTaskKey().copyTo(executionContext.selectedTask);
+            executor.subject.getDefaultTaskKey().copyTo(executor.selectedTask);
         } else {
-            executionContext.subject.getTaskKey(task).copyTo(executionContext.selectedTask);
-        }
-        if (logger.isDebugEnabled()) {
-            logger.debug(
-                    "TestAnomalyDetectionTSLPolicy0000DecideStateTaskSelectionLogic.getTask():\t************\t\t\t\t"
-                            + "Iteration:\t" + iteration + "\tValue:\t" + now + "\tForecast:\t" + vals[0]
-                            + "\tAnomalyScore:\t" + vals[1] + "\tAnomalyProbability:\t" + vals[2] + "\tInvoking Task:\t"
-                            + executionContext.selectedTask);
+            executor.subject.getTaskKey(task).copyTo(executor.selectedTask);
         }
+        executor.logger.debug(
+            "TestAnomalyDetectionTSLPolicy0000DecideStateTaskSelectionLogic.getTask():\t************\t\t\t\t"
+                + "Iteration:\t{}\tValue:\t{}\tForecast:\t{}\tAnomalyScore:\t{}\tAnomalyProbability:\t{}\t"
+                + "Invoking Task:\t{}", iteration, now, vals[0], vals[1], vals[2], executor.selectedTask);
         return true;
     }
 
@@ -120,20 +113,20 @@ public class AnomalyDetectionPolicyDecideTaskSelectionLogic {
      * @return Null if the function can not be executed correctly, otherwise double[forecastedValue,
      *         AnomalyScore, AnomalyProbability]
      */
-    public double[] forecastingAndAnomaly(final double value) {
+    private double[] forecastingAndAnomaly(final TaskSelectionExecutionContext executor, final double value) {
         try {
-            executionContext.getContextAlbum(ANOMALY_DETECTION_ALBUM).lockForWriting(ANOMALY_DETECTION);
+            executor.getContextAlbum(ANOMALY_DETECTION_ALBUM).lockForWriting(ANOMALY_DETECTION);
         } catch (final ApexException e) {
-            logger.error("Failed to acquire write lock on \"AnomalyDetection\" context", e);
+            executor.logger.error("Failed to acquire write lock on \"AnomalyDetection\" context", e);
             return new double[0];
         }
 
         // Get the context object
         AnomalyDetection anomalyDetection =
-                (AnomalyDetection) executionContext.getContextAlbum(ANOMALY_DETECTION_ALBUM).get(ANOMALY_DETECTION);
+                (AnomalyDetection) executor.getContextAlbum(ANOMALY_DETECTION_ALBUM).get(ANOMALY_DETECTION);
         if (anomalyDetection == null) {
             anomalyDetection = new AnomalyDetection();
-            executionContext.getContextAlbum(ANOMALY_DETECTION_ALBUM).put(ANOMALY_DETECTION, anomalyDetection);
+            executor.getContextAlbum(ANOMALY_DETECTION_ALBUM).put(ANOMALY_DETECTION, anomalyDetection);
         }
 
         // Check the lists are initialized
@@ -186,9 +179,9 @@ public class AnomalyDetectionPolicyDecideTaskSelectionLogic {
         // CHECKSTYLE:ON: checkstyle:magicNumber
 
         try {
-            executionContext.getContextAlbum(ANOMALY_DETECTION_ALBUM).unlockForWriting(ANOMALY_DETECTION);
+            executor.getContextAlbum(ANOMALY_DETECTION_ALBUM).unlockForWriting(ANOMALY_DETECTION);
         } catch (final ApexException e) {
-            logger.error("Failed to release write lock on \"AnomalyDetection\" context", e);
+            executor.logger.error("Failed to release write lock on \"AnomalyDetection\" context", e);
             return new double[0];
         }
 
index a60c609..35010bf 100644 (file)
@@ -37,6 +37,7 @@ import javax.xml.bind.annotation.XmlRootElement;
 import javax.xml.bind.annotation.XmlType;
 import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
 
+import org.apache.commons.lang3.StringUtils;
 import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult.ValidationResult;
 import org.onap.policy.apex.model.basicmodel.dao.converters.CDataConditioner;
 import org.onap.policy.apex.model.basicmodel.dao.converters.Uuid2String;
@@ -64,6 +65,8 @@ public class AxKeyInfo extends AxConcept {
     private static final int MAX_DESCRIPTION_LENGTH_8192 = 8192;
     private static final int UUID_BYTE_LENGTH_16 = 16;
 
+    private static final Random sharedRandom = new Random();
+
     @EmbeddedId
     @XmlElement(name = "key", required = true)
     private AxArtifactKey key;
@@ -331,11 +334,9 @@ public class AxKeyInfo extends AxConcept {
      * @return the uuid
      */
     public static UUID generateReproducibleUuid(final String seed) {
-        final Random random;
-        if (seed != null && seed.length() > 0) {
+        Random random = sharedRandom;
+        if (!StringUtils.isEmpty(seed)) {
             random = new Random(seed.hashCode());
-        } else {
-            random = new Random();
         }
         final byte[] array = new byte[UUID_BYTE_LENGTH_16];
         random.nextBytes(array);
index c98fa41..2e47362 100644 (file)
@@ -176,6 +176,6 @@ public class ApexGrpcProducer extends ApexPluginsEventProducer implements CdsPro
         cdsResponse.set(ExecutionServiceOutput.newBuilder()
             .setStatus(Status.newBuilder().setErrorMessage(errorMsg).setEventType(EventType.EVENT_COMPONENT_FAILURE))
             .build());
-        LOGGER.error("Failed processing blueprint {} {}", errorMsg, throwable);
+        LOGGER.error("Failed processing blueprint {}", errorMsg, throwable);
     }
 }
index 3730bba..33f88bf 100644 (file)
@@ -30,6 +30,7 @@ import org.onap.policy.apex.core.engine.executor.context.TaskExecutionContext;
  */
 public class DefaultTaskLogic {
     private static final int BOUND_FOR_RANDOM_INT = 4;
+    private static final Random rand = new Random();
 
     /**
      * Gets the event.
@@ -46,7 +47,6 @@ public class DefaultTaskLogic {
 
         String inFieldsString = executor.inFields.toString();
         executor.logger.debug(inFieldsString);
-        final Random rand = new Random();
         if (executor.inFields.containsKey("TestDecideCaseSelected")) {
             executor.outFields.put("TestActCaseSelected", (byte) rand.nextInt(BOUND_FOR_RANDOM_INT));
             executor.outFields.put("TestActStateTime", System.nanoTime());