Java 17 and sonar fixes. 01/136101/1
authoradheli.tavares <adheli.tavares@est.tech>
Wed, 4 Oct 2023 14:38:04 +0000 (15:38 +0100)
committeradheli.tavares <adheli.tavares@est.tech>
Wed, 4 Oct 2023 14:42:27 +0000 (15:42 +0100)
- change on maven.compiler to new resource property targeting
java 17 version
- sonar bugs on try-resource and some code smells

Issue-ID: POLICY-4677
Issue-ID: POLICY-4837
Change-Id: I50a2170db80619c2ac95131ab5c91a6f767a5c30
Signed-off-by: adheli.tavares <adheli.tavares@est.tech>
controlloop/common/controller-usecases/src/main/java/org/onap/policy/drools/apps/controller/usecases/GetTargetEntityOperation2.java
controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/eventmanager/ClEventManagerWithOutcome.java
controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/eventmanager/ClEventManagerWithSteps.java
controlloop/common/eventmanager/src/main/java/org/onap/policy/controlloop/ophistory/OperationHistoryDataManagerImpl.java
controlloop/common/eventmanager/src/test/java/org/onap/policy/controlloop/eventmanager/ClEventManagerWithStepsTest.java
controlloop/common/feature-controlloop-utils/pom.xml

index f9d90af..29689ed 100644 (file)
@@ -3,6 +3,7 @@
  * ONAP
  * ================================================================================
  * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2023 Nordix Foundation.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -92,16 +93,11 @@ public class GetTargetEntityOperation2 extends OperationPartial {
             throw new IllegalArgumentException("The target type is null");
         }
 
-        switch (targetType) {
-            case PNF:
-                return detmPnfTarget();
-            case VM:
-            case VNF:
-            case VFMODULE:
-                return detmVfModuleTarget();
-            default:
-                throw new IllegalArgumentException("The target type is not supported");
-        }
+        return switch (targetType) {
+            case PNF -> detmPnfTarget();
+            case VM, VNF, VFMODULE -> detmVfModuleTarget();
+            default -> throw new IllegalArgumentException("The target type is not supported");
+        };
     }
 
     /**
index 79fe0b7..84389b8 100644 (file)
@@ -3,6 +3,7 @@
  * ONAP
  * ================================================================================
  * Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2023 Nordix Foundation.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -20,6 +21,7 @@
 
 package org.onap.policy.controlloop.eventmanager;
 
+import java.io.Serial;
 import java.util.Deque;
 import java.util.LinkedList;
 import java.util.UUID;
@@ -40,22 +42,22 @@ import org.onap.policy.drools.domain.models.operational.OperationalTarget;
 /**
  * Manager for a single control loop event, with operation outcomes.
  */
+@Getter
 public abstract class ClEventManagerWithOutcome<T extends Step> extends ClEventManagerWithSteps<T>
                 implements StepContext {
 
+    @Serial
     private static final long serialVersionUID = -1216568161322872641L;
 
     /**
      * Number of attempts, so far, for the current step.
      */
-    @Getter
     private int attempts;
 
     /**
      * Full history of operations that have been processed by the rules. This includes the
      * items in {@link #partialHistory}.
      */
-    @Getter
     private final transient Deque<OperationOutcome2> fullHistory = new LinkedList<>();
 
     /**
@@ -63,7 +65,6 @@ public abstract class ClEventManagerWithOutcome<T extends Step> extends ClEventM
      * When a step is started, its "start" outcome is added. However, once it completes,
      * its "start" outcome is removed and the "completed" outcome is added.
      */
-    @Getter
     private final transient Deque<OperationOutcome2> partialHistory = new LinkedList<>();
 
 
index a449366..511d93b 100644 (file)
@@ -3,6 +3,7 @@
  * ONAP
  * ================================================================================
  * Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2023 Nordix Foundation.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -20,6 +21,7 @@
 
 package org.onap.policy.controlloop.eventmanager;
 
+import java.io.Serial;
 import java.util.ArrayDeque;
 import java.util.Deque;
 import java.util.LinkedHashMap;
@@ -55,6 +57,7 @@ import org.slf4j.LoggerFactory;
 public abstract class ClEventManagerWithSteps<T extends Step> extends ControlLoopEventManager implements StepContext {
 
     private static final Logger logger = LoggerFactory.getLogger(ClEventManagerWithSteps.class);
+    @Serial
     private static final long serialVersionUID = -1216568161322872641L;
 
     /**
@@ -99,7 +102,7 @@ public abstract class ClEventManagerWithSteps<T extends Step> extends ControlLoo
 
     /**
      * Result of the last policy operation. This is just a place where the rules can store
-     * the value for passing to {@link #loadNextPolicy()}.
+     * the value for passing to {@link #loadNextPolicy(OperationResult)}.
      */
     @Getter
     @Setter
@@ -266,6 +269,7 @@ public abstract class ClEventManagerWithSteps<T extends Step> extends ControlLoo
         }
 
         // initialize the step so we can query its properties
+        assert getSteps().peek() != null;
         getSteps().peek().init();
     }
 
index 36d0ba5..16cf527 100644 (file)
@@ -168,15 +168,15 @@ public class OperationHistoryDataManagerImpl implements OperationHistoryDataMana
      * Takes records from {@link #operations} and stores them in the queue. Continues to
      * run until {@link #stop()} is invoked, or the thread is interrupted.
      *
-     * @param emfactory entity manager factory
+     * @param factory entity manager factory
      */
-    private void run(EntityManagerFactory emfactory) {
-        try {
+    private void run(EntityManagerFactory factory) {
+        try (factory) {
             // store records until stopped, continuing if an exception occurs
             while (!stopped) {
                 try {
                     Record triple = operations.take();
-                    storeBatch(emfactory.createEntityManager(), triple);
+                    storeBatch(factory.createEntityManager(), triple);
 
                 } catch (RuntimeException e) {
                     logger.error("failed to save data to operation history table", e);
@@ -188,26 +188,27 @@ public class OperationHistoryDataManagerImpl implements OperationHistoryDataMana
                 }
             }
 
-            storeRemainingRecords(emfactory);
+            storeRemainingRecords(factory);
 
         } finally {
             synchronized (this) {
                 stopped = true;
             }
 
-            emfactory.close();
         }
     }
 
     /**
      * Store any remaining records, but stop at the first exception.
      *
-     * @param emfactory entity manager factory
+     * @param factory entity manager factory
      */
-    private void storeRemainingRecords(EntityManagerFactory emfactory) {
+    private void storeRemainingRecords(EntityManagerFactory factory) {
         try {
             while (!operations.isEmpty()) {
-                storeBatch(emfactory.createEntityManager(), operations.poll());
+                try (var em = factory.createEntityManager()) {
+                    storeBatch(em, operations.poll());
+                }
             }
 
         } catch (RuntimeException e) {
@@ -224,8 +225,8 @@ public class OperationHistoryDataManagerImpl implements OperationHistoryDataMana
     private void storeBatch(EntityManager entityManager, Record firstRecord) {
         logger.info("store operation history record batch");
 
-        try (var emc = new EntityMgrCloser(entityManager);
-            var trans = new EntityTransCloser(entityManager.getTransaction())) {
+        try (var ignored = new EntityMgrCloser(entityManager);
+             var trans = new EntityTransCloser(entityManager.getTransaction())) {
 
             var nrecords = 0;
             var rec = firstRecord;
index 95d4046..5caca45 100644 (file)
@@ -38,9 +38,11 @@ import static org.mockito.Mockito.never;
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 
+import java.io.Serial;
 import java.time.Instant;
 import java.util.ArrayList;
 import java.util.List;
+import java.util.Objects;
 import java.util.UUID;
 import java.util.concurrent.ExecutorService;
 import java.util.concurrent.ForkJoinPool;
@@ -60,9 +62,7 @@ import org.onap.policy.controlloop.actorserviceprovider.Operation;
 import org.onap.policy.controlloop.actorserviceprovider.OperationFinalResult;
 import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
 import org.onap.policy.controlloop.actorserviceprovider.OperationResult;
-import org.onap.policy.controlloop.actorserviceprovider.Operator;
 import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams;
-import org.onap.policy.controlloop.actorserviceprovider.spi.Actor;
 import org.onap.policy.controlloop.drl.legacy.ControlLoopParams;
 import org.onap.policy.drools.core.lock.LockCallback;
 import org.onap.policy.drools.core.lock.LockImpl;
@@ -91,9 +91,7 @@ class ClEventManagerWithStepsTest {
     private final PolicyEngine engineMgr = mock(PolicyEngine.class);
     private final WorkingMemory workMem = mock(WorkingMemory.class);
     private final InternalFactHandle factHandle = mock(InternalFactHandle.class);
-    private final Operator policyOperator = mock(Operator.class);
     private final Operation policyOperation = mock(Operation.class);
-    private final Actor policyActor = mock(Actor.class);
     private final ExecutorService executor = mock(ExecutorService.class);
     private final EventManagerServices services = mock(EventManagerServices.class);
     private final ActorService actors = mock(ActorService.class);
@@ -101,7 +99,6 @@ class ClEventManagerWithStepsTest {
     private final MyStep stepb = mock(MyStep.class);
 
     private List<LockImpl> locks;
-    private ToscaPolicy tosca;
     private ControlLoopParams params;
     private ClEventManagerWithSteps<MyStep> mgr;
 
@@ -231,18 +228,18 @@ class ClEventManagerWithStepsTest {
     }
 
     @Test
-    public void testLoadNextPolicy() throws Exception {
+    void testLoadNextPolicy() throws Exception {
         loadPolicy(EVENT_MGR_MULTI_YAML);
         mgr = new MyManager(services, params, REQ_ID, workMem);
 
         // start and load step for first policy
         mgr.start();
-        assertEquals("OperationA", mgr.getSteps().poll().getOperationName());
+        assertEquals("OperationA", Objects.requireNonNull(mgr.getSteps().poll()).getOperationName());
         assertNull(mgr.getFinalResult());
 
         // indicate success and load next policy
         mgr.loadNextPolicy(OperationResult.SUCCESS);
-        assertEquals("OperationB", mgr.getSteps().poll().getOperationName());
+        assertEquals("OperationB", Objects.requireNonNull(mgr.getSteps().poll()).getOperationName());
         assertNull(mgr.getFinalResult());
 
         // indicate failure - should go to final failure
@@ -378,7 +375,7 @@ class ClEventManagerWithStepsTest {
 
     private void loadPolicy(String fileName) throws CoderException {
         var template = yamlCoder.decode(ResourceUtils.getResourceAsString(fileName), ToscaServiceTemplate.class);
-        tosca = template.getToscaTopologyTemplate().getPolicies().get(0).values().iterator().next();
+        ToscaPolicy tosca = template.getToscaTopologyTemplate().getPolicies().get(0).values().iterator().next();
 
         params.setToscaPolicy(tosca);
     }
@@ -404,6 +401,7 @@ class ClEventManagerWithStepsTest {
 
 
     private class MyManager extends ClEventManagerWithSteps<MyStep> {
+        @Serial
         private static final long serialVersionUID = 1L;
 
         public MyManager(EventManagerServices services, ControlLoopParams params, UUID requestId, WorkingMemory workMem)
@@ -437,6 +435,7 @@ class ClEventManagerWithStepsTest {
 
 
     private static class RealManager extends ClEventManagerWithSteps<MyStep> {
+        @Serial
         private static final long serialVersionUID = 1L;
 
         public RealManager(EventManagerServices services, ControlLoopParams params, UUID requestId,
index fe74bb9..11cf240 100644 (file)
@@ -39,8 +39,7 @@
     </description>
 
     <properties>
-        <maven.compiler.source>1.8</maven.compiler.source>
-        <maven.compiler.target>1.8</maven.compiler.target>
+        <maven.compiler.release>17</maven.compiler.release>
     </properties>
 
     <build>