Fix sonar issues in common 08/138708/1
authorwaynedunican <wayne.dunican@est.tech>
Mon, 12 Aug 2024 20:18:12 +0000 (21:18 +0100)
committerwaynedunican <wayne.dunican@est.tech>
Tue, 13 Aug 2024 08:21:16 +0000 (09:21 +0100)
- SONAR Fix instanceOf issues
- SONAR Remove public modifiers
- SONAR Remove unused imports
- SONAR Remove exceptions that can't be thrown from method body

Issue-ID: POLICY-5106
Change-Id: I745d0101036d3421f02db22481514be0b79f5103
Signed-off-by: waynedunican <wayne.dunican@est.tech>
21 files changed:
common-logging/src/main/java/org/onap/policy/common/logging/eelf/EventData.java
common-logging/src/main/java/org/onap/policy/common/logging/flexlogger/FlexLogger.java
common-logging/src/test/java/org/onap/policy/common/logging/flexlogger/FlexLoggerTest.java
common-parameters/src/main/java/org/onap/policy/common/parameters/BeanValidator.java
gson/src/test/java/org/onap/policy/common/gson/internal/FieldSerializerTest.java
integrity-monitor/src/main/java/org/onap/policy/common/im/jpa/ResourceRegistrationEntity.java
integrity-monitor/src/test/java/org/onap/policy/common/im/IntegrityMonitorTest.java
integrity-monitor/src/test/java/org/onap/policy/common/im/StateManagementEntityTest.java
integrity-monitor/src/test/java/org/onap/policy/common/im/StateManagementTest.java
spring-utils/pom.xml
utils-test/src/main/java/org/onap/policy/common/utils/security/SelfSignedKeyStore.java
utils-test/src/test/java/org/onap/policy/common/utils/io/SerializerTest.java
utils-test/src/test/java/org/onap/policy/common/utils/security/SelfSignedKeyStoreTest.java
utils-test/src/test/java/org/onap/policy/common/utils/time/TestTimeMultiTest.java
utils-test/src/test/java/org/onap/policy/common/utils/time/TestTimeTest.java
utils-test/src/test/java/org/onap/policy/common/utils/time/WorkItemTest.java
utils/src/main/java/org/onap/policy/common/utils/coder/YamlJsonTranslator.java
utils/src/test/java/org/onap/policy/common/utils/coder/StandardCoderTest.java
utils/src/test/java/org/onap/policy/common/utils/coder/StandardYamlCoderTest.java
utils/src/test/java/org/onap/policy/common/utils/properties/PropertyObjectUtilsTest.java
utils/src/test/java/org/onap/policy/common/utils/security/CryptoUtilsTest.java

index 87a96a1..bdd67a0 100644 (file)
@@ -3,6 +3,7 @@
  * ONAP-Logging
  * ================================================================================
  * Copyright (C) 2017-2019, 2021 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2024 Nordix Foundation
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -60,8 +61,7 @@ public class EventData {
         if (obj == null) {
             return false;
         }
-        if (obj instanceof String) {
-            String otherRequestId = (String) obj;
+        if (obj instanceof String otherRequestId) {
             return requestId != null && requestId.equals(otherRequestId);
         }
         if (getClass() != obj.getClass()) {
index 6c30171..7bfcb5d 100644 (file)
@@ -3,7 +3,7 @@
  * ONAP-Logging
  * ================================================================================
  * Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2023 Nordix Foundation.
+ * Modifications Copyright (C) 2023-2024 Nordix Foundation.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -36,7 +36,7 @@ import org.onap.policy.common.logging.flexlogger.PropertyUtil.Listener;
 /**
  * FlexLogger acts as factory to generate instances of Logger based on logger type.
  */
-public class FlexLogger extends SecurityManager {
+public class FlexLogger {
 
     private static final String GET_LOGGER_PREFIX = "FlexLogger:getLogger : loggerType = ";
     private static LoggerType loggerType = LoggerType.EELF;
@@ -95,8 +95,11 @@ public class FlexLogger extends SecurityManager {
      * Returns the calling class name.
      */
     public String getClassName() {
-        displayMessage("getClassContext()[3].getName() " + getClassContext()[3].getName());
-        return getClassContext()[3].getName();
+        StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
+        if (stackTrace.length > 3) {
+            return stackTrace[3].getClassName();
+        }
+        return "UnknownClass";
     }
 
     /**
index 547f0a4..3c78785 100644 (file)
@@ -26,7 +26,6 @@ import static org.assertj.core.api.Assertions.assertThatCode;
 import static org.junit.jupiter.api.Assertions.assertNotEquals;
 import static org.junit.jupiter.api.Assertions.assertSame;
 
-import java.io.IOException;
 import java.util.HashSet;
 import java.util.Set;
 import org.junit.jupiter.api.Test;
index 4ed7e42..c4244b2 100644 (file)
@@ -3,6 +3,7 @@
  * ONAP
  * ================================================================================
  * Copyright (C) 2020-2021 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2024 Nordix Foundation
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -307,7 +308,7 @@ public class BeanValidator {
             return true;
         }
 
-        BeanValidationResult result2 = (value instanceof ParameterGroup ? ((ParameterGroup) value).validate()
+        BeanValidationResult result2 = (value instanceof ParameterGroup parameterGroup ? parameterGroup.validate()
                         : validateTop(fieldName, value));
 
         if (result2.isClean()) {
index a55d990..1431f47 100644 (file)
@@ -51,7 +51,7 @@ class FieldSerializerTest {
     private List<Data> listField;
 
     @Test
-    public void testAddToTree() throws Exception {
+    void testAddToTree() throws Exception {
         ser = new FieldSerializer(gson, FieldSerializerTest.class.getDeclaredField(TEXT_FIELD_NAME));
 
         // serialize null value first
index a771ba0..3ee607f 100644 (file)
@@ -3,7 +3,7 @@
  * Integrity Monitor
  * ================================================================================
  * Copyright (C) 2017-2018, 2020-2021 AT&T Intellectual Property. All rights reserved.
- * Modifications Copyright (C) 2023 Nordix Foundation.
+ * Modifications Copyright (C) 2023-2024 Nordix Foundation.
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -26,7 +26,6 @@ import jakarta.persistence.Entity;
 import jakarta.persistence.GeneratedValue;
 import jakarta.persistence.GenerationType;
 import jakarta.persistence.Id;
-import jakarta.persistence.NamedQueries;
 import jakarta.persistence.NamedQuery;
 import jakarta.persistence.Table;
 import java.io.Serial;
index 3c071f1..f866df4 100644 (file)
@@ -559,7 +559,7 @@ class IntegrityMonitorTest extends IntegrityMonitorTestBase {
         @SuppressWarnings("rawtypes")
         List resourceList = query.getResultList();
         if (resourceList.isEmpty()) {
-            logger.debug("Record not found, resourceName: " + resourceName);
+            logger.debug("Record not found, resourceName: {}", resourceName);
             fail("missing record");
         }
 
@@ -626,7 +626,7 @@ class IntegrityMonitorTest extends IntegrityMonitorTestBase {
             assertEquals(StateManagement.HOT_STANDBY, sme1.getStandbyStatus());
             logger.debug("--");
         } else {
-            logger.debug("Record not found, resourceName: " + resourceName);
+            logger.debug("Record not found, resourceName: {}", resourceName);
             fail("record not found");
         }
 
index 2670b70..266b322 100644 (file)
@@ -73,7 +73,7 @@ class StateManagementEntityTest extends IntegrityMonitorTestBase {
     }
 
     @Test
-    void testJpa() throws Exception {
+    void testJpa() {
         logger.debug("\n??? logger.infor StateManagementEntityTest: Entering\n\n");
 
         // Define the resourceName for the StateManagement constructor
index f43322d..5dfd01f 100644 (file)
@@ -99,7 +99,7 @@ class StateManagementTest extends IntegrityMonitorTestBase {
         logger.info("\n\nStateManagementTest: Exit\n\n");
     }
 
-    private void test_1(final StateManagement sm) throws StateManagementException, IntegrityMonitorException {
+    private void test_1(final StateManagement sm) throws IntegrityMonitorException {
         logger.info("\n??? initial state");
         assertEquals(UNLOCKED_ENABLED_NULL_NULL, makeString(sm));
 
@@ -167,7 +167,7 @@ class StateManagementTest extends IntegrityMonitorTestBase {
         assertEquals(UNLOCKED_ENABLED_NULL_HOTSTANDBY, makeString(sm2));
     }
 
-    private void test_2(final StateManagement sm) throws StateManagementException, IntegrityMonitorException {
+    private void test_2(final StateManagement sm) throws IntegrityMonitorException {
         // D3 If demote() is called while standbyStatus is null and
         // adminState is locked or opState is disabled,
         // the state shall transition to coldstandby
@@ -231,8 +231,7 @@ class StateManagementTest extends IntegrityMonitorTestBase {
 
     @Test
     @SuppressWarnings("unchecked")
-    void test_StateManagementInitialization_ThrowException_ifEntityManagerCreateQuerythrowsAnyException()
-            throws Exception {
+    void test_StateManagementInitialization_ThrowException_ifEntityManagerCreateQuerythrowsAnyException() {
         assertThatThrownBy(() -> {
             final EntityManager mockedEm = getMockedEntityManager();
             final EntityManagerFactory mockedEmf = getMockedEntityManagerFactory(mockedEm);
@@ -246,8 +245,7 @@ class StateManagementTest extends IntegrityMonitorTestBase {
 
     @Test
     @SuppressWarnings("unchecked")
-    void test_StateManagementInitialization_ThrowStateManagementException_ifEntityManagerThrowsAnyException()
-            throws Exception {
+    void test_StateManagementInitialization_ThrowStateManagementException_ifEntityManagerThrowsAnyException() {
         assertThatThrownBy(() -> {
             final EntityManager mockedEm = getMockedEntityManager();
             final EntityManagerFactory mockedEmf = getMockedEntityManagerFactory(mockedEm);
index c261093..d5d5d84 100644 (file)
             <groupId>org.hibernate.orm</groupId>
             <artifactId>hibernate-core</artifactId>
         </dependency>
+        <dependency>
+            <groupId>org.mockito</groupId>
+            <artifactId>mockito-junit-jupiter</artifactId>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.assertj</groupId>
+            <artifactId>assertj-core</artifactId>
+        </dependency>
     </dependencies>
 
 </project>
\ No newline at end of file
index 0787872..1cc1626 100644 (file)
@@ -3,6 +3,7 @@
  * ONAP
  * ================================================================================
  * Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2024 Nordix Foundation
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -36,7 +37,6 @@ import java.security.cert.CertificateException;
 import java.util.Arrays;
 import java.util.Date;
 import java.util.concurrent.TimeUnit;
-import java.util.stream.Collectors;
 import lombok.Getter;
 import org.bouncycastle.asn1.x500.X500Name;
 import org.bouncycastle.asn1.x509.Extension;
@@ -77,7 +77,7 @@ public class SelfSignedKeyStore {
      * @throws IOException if an I/O error occurs
      * @throws InterruptedException if an interrupt occurs
      */
-    public SelfSignedKeyStore() throws IOException, InterruptedException {
+    public SelfSignedKeyStore() throws IOException {
         this(RELATIVE_PATH);
     }
 
@@ -89,7 +89,7 @@ public class SelfSignedKeyStore {
      * @throws IOException if an I/O error occurs
      * @throws InterruptedException if an interrupt occurs
      */
-    public SelfSignedKeyStore(String relativePath) throws IOException, InterruptedException {
+    public SelfSignedKeyStore(String relativePath) throws IOException {
         keystoreName = System.getProperty("user.dir") + "/" + relativePath;
 
         // use existing file if it isn't too old
index 25461da..602df35 100644 (file)
@@ -361,7 +361,7 @@ class SerializerTest {
 
     @Test
     void testRoundTrip() throws Exception {
-        MyObject obj1 = new MyObject(3);
+        MyObject obj1 = new MyObject(4);
 
         MyObject obj2 = Serializer.roundTrip(obj1);
         assertEquals(obj1.value, obj2.value);
index 8a3dfe3..1af69cd 100644 (file)
@@ -57,7 +57,7 @@ public class SelfSignedKeyStoreTest {
     }
 
     @Test
-    public void testSelfSignedKeyStore() throws Exception {
+    void testSelfSignedKeyStore() throws Exception {
         SelfSignedKeyStore ks = new SelfSignedKeyStore();
 
         assertThat(ks.getKeystoreName()).isEqualTo(defaultName);
@@ -65,7 +65,7 @@ public class SelfSignedKeyStoreTest {
     }
 
     @Test
-    public void testSelfSignedKeyStoreString() throws IOException, InterruptedException {
+    void testSelfSignedKeyStoreString() throws IOException, InterruptedException {
         String relName = "target/my-keystore";
         String altName = saveUserDir + "/" + relName;
         File altFile = new File(altName);
@@ -82,7 +82,7 @@ public class SelfSignedKeyStoreTest {
      * Tests the constructor, when the keystore already exists.
      */
     @Test
-    public void testSelfSignedKeyStoreStringExists() throws Exception {
+    void testSelfSignedKeyStoreStringExists() throws Exception {
         new SelfSignedKeyStore();
         assertThat(defaultKeystore).exists();
 
@@ -109,7 +109,7 @@ public class SelfSignedKeyStoreTest {
      * Tests the constructor, when the SAN file is not found.
      */
     @Test
-    public void testSelfSignedKeyStoreStringNoSanFile() {
+    void testSelfSignedKeyStoreStringNoSanFile() {
         assertThatThrownBy(() -> new SelfSignedKeyStore() {
             @Override
             protected String getKeystoreSanName() {
@@ -122,13 +122,13 @@ public class SelfSignedKeyStoreTest {
      * Tests the constructor, when write fails.
      */
     @Test
-    public void testSelfSignedKeyStoreStringWriteFailure() {
+    void testSelfSignedKeyStoreStringWriteFailure() {
         assertThatThrownBy(() -> new SelfSignedKeyStore("target/unknown/path/to/keystore"))
                         .isInstanceOf(IOException.class);
     }
 
     @Test
-    public void testGetKeystoreName() throws Exception {
+    void testGetKeystoreName() throws Exception {
         String relpath = SelfSignedKeyStore.RELATIVE_PATH;
 
         // append the first part of the relative path to user.dir
index f6d1e6a..1b9728d 100644 (file)
@@ -115,7 +115,7 @@ class TestTimeMultiTest {
     }
 
     @Test
-    void testDestroy() throws InterruptedException {
+    void testDestroy() {
         // this won't interrupt
         multi.enqueue(new WorkItem(multi, DELAY_MS));
 
@@ -193,7 +193,7 @@ class TestTimeMultiTest {
     }
 
     @Test
-    void testWaitUntilCallable() throws InterruptedException {
+    void testWaitUntilCallable() {
         multi.enqueue(new WorkItem(multi, DELAY_MS));
         multi.enqueue(new WorkItem(multi, DELAY_MS * 2));
         multi.enqueue(new WorkItem(multi, DELAY_MS * 3));
@@ -238,7 +238,7 @@ class TestTimeMultiTest {
     }
 
     @Test
-    void testWaitUntilCallable_ConditionThrowsEx() throws InterruptedException {
+    void testWaitUntilCallable_ConditionThrowsEx() {
         multi = new TestTimeMulti();
 
         Callable<Boolean> callable = () -> {
@@ -253,7 +253,7 @@ class TestTimeMultiTest {
     }
 
     @Test
-    void testWaitUntilCallable_NeverSatisfied() throws InterruptedException {
+    void testWaitUntilCallable_NeverSatisfied() {
         multi = new TestTimeMulti(SHORT_WAIT_MS);
 
         final long realBegin = System.currentTimeMillis();
@@ -263,7 +263,7 @@ class TestTimeMultiTest {
     }
 
     @Test
-    void testWaitUntilLongTimeUnitCallable() throws InterruptedException {
+    void testWaitUntilLongTimeUnitCallable() {
         multi.enqueue(new WorkItem(multi, DELAY_MS));
         multi.enqueue(new WorkItem(multi, DELAY_MS * 2));
         multi.enqueue(new WorkItem(multi, DELAY_MS * 3));
@@ -280,7 +280,7 @@ class TestTimeMultiTest {
     }
 
     @Test
-    void testWaitUntilLongTimeUnitCallable_PseudoTimeExpires() throws InterruptedException {
+    void testWaitUntilLongTimeUnitCallable_PseudoTimeExpires() {
         multi.enqueue(new WorkItem(multi, DELAY_MS));
         multi.enqueue(new WorkItem(multi, DELAY_MS * 2));
         multi.enqueue(new WorkItem(multi, DELAY_MS * 3));
index c3b69eb..dbf077c 100644 (file)
@@ -26,10 +26,10 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
 
 import org.junit.jupiter.api.Test;
 
-public class TestTimeTest {
+class TestTimeTest {
 
     @Test
-    public void test() throws Exception {
+    void test() throws Exception {
         TestTime tm = new TestTime();
         TestTime tm2 = new TestTime();
 
index f0229ca..a5683a6 100644 (file)
@@ -29,7 +29,7 @@ import static org.junit.jupiter.api.Assertions.assertFalse;
 import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.api.Test;
 
-public class WorkItemTest {
+class WorkItemTest {
     private TestTime currentTime;
     private WorkItem item;
 
@@ -40,7 +40,7 @@ public class WorkItemTest {
     }
 
     @Test
-    public void testWorkItem() {
+    void testWorkItem() {
         assertThatIllegalArgumentException().isThrownBy(() -> new WorkItem(currentTime, -1));
 
         // should not throw an exception
@@ -48,22 +48,22 @@ public class WorkItemTest {
     }
 
     @Test
-    public void testGetDelay() {
+    void testGetDelay() {
         assertEquals(1, item.getDelay());
     }
 
     @Test
-    public void testWasCancelled() {
+    void testWasCancelled() {
         assertFalse(item.wasCancelled());
     }
 
     @Test
-    public void testBumpNextTime() {
+    void testBumpNextTime() {
         assertFalse(item.bumpNextTime());
     }
 
     @Test
-    public void testBumpNextTimeLong() {
+    void testBumpNextTimeLong() {
         assertThatIllegalArgumentException().isThrownBy(() -> item.bumpNextTime(-1));
 
         long cur = currentTime.getMillis();
@@ -77,24 +77,24 @@ public class WorkItemTest {
     }
 
     @Test
-    public void testInterrupt() {
+    void testInterrupt() {
         item.interrupt();
         assertFalse(Thread.interrupted());
     }
 
     @Test
-    public void testIsAssociatedWith() {
+    void testIsAssociatedWith() {
         assertFalse(item.isAssociatedWith(this));
     }
 
     @Test
-    public void testFire() {
+    void testFire() {
         // ensure no exception is thrown
         assertThatCode(() -> item.fire()).doesNotThrowAnyException();
     }
 
     @Test
-    public void testGetNextMs() {
+    void testGetNextMs() {
         assertEquals(currentTime.getMillis() + 1, item.getNextMs());
         assertEquals(currentTime.getMillis() + 10, new WorkItem(currentTime, 10).getNextMs());
     }
index 077246b..ffd9d05 100644 (file)
@@ -3,6 +3,7 @@
  * ONAP
  * ================================================================================
  * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2024 Nordix Foundation
  * ================================================================================
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -257,11 +258,11 @@ public class YamlJsonTranslator {
      * @return a gson element corresponding to the node
      */
     protected JsonElement makeJson(Node node) {
-        if (node instanceof MappingNode) {
-            return makeJsonObject((MappingNode) node);
+        if (node instanceof MappingNode mappingNode) {
+            return makeJsonObject(mappingNode);
 
-        } else if (node instanceof SequenceNode) {
-            return makeJsonArray((SequenceNode) node);
+        } else if (node instanceof SequenceNode sequenceNode) {
+            return makeJsonArray(sequenceNode);
 
         } else {
             return makeJsonPrim((ScalarNode) node);
index b4ac039..269893e 100644 (file)
@@ -264,7 +264,7 @@ class StandardCoderTest {
     }
 
     @Test
-    void testToJsonTree_testFromJsonJsonElementClassT() throws Exception {
+    void testToJsonTree_testFromJsonJsonElementClassT() {
         MyMap map = new MyMap();
         map.props = new LinkedHashMap<>();
         map.props.put("jel keyA", "jel valueA");
@@ -314,7 +314,7 @@ class StandardCoderTest {
     }
 
     @Test
-    void testStandardTypeAdapter() throws Exception {
+    void testStandardTypeAdapter() {
         String json = "{'abc':'def'}".replace('\'', '"');
         StandardCoderObject sco = coder.fromJson(json, StandardCoderObject.class);
         assertNotNull(sco.getData());
index ff3f6ef..d504b82 100644 (file)
@@ -104,7 +104,7 @@ class StandardYamlCoderTest {
     }
 
     @Test
-    void testStandardTypeAdapter() throws Exception {
+    void testStandardTypeAdapter() {
         String yaml = "abc: def\n";
         StandardCoderObject sco = coder.fromJson(yaml, StandardCoderObject.class);
         assertNotNull(sco.getData());
index 6c5918c..b62fd1e 100644 (file)
@@ -146,7 +146,7 @@ class PropertyObjectUtilsTest {
 
     @Test
     @SuppressWarnings("unchecked")
-    void testCompressLists() throws IOException, CoderException {
+    void testCompressLists() throws CoderException {
         assertEquals("plain-string", PropertyObjectUtils.compressLists("plain-string").toString());
 
         // @formatter:off
index ee33837..5f8b80e 100644 (file)
@@ -25,7 +25,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertNull;
 import static org.junit.jupiter.api.Assertions.assertTrue;
 
-import java.security.GeneralSecurityException;
 import org.junit.jupiter.api.Test;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -43,7 +42,7 @@ class CryptoUtilsTest {
     private static final String ENCRYPTED_MSG = "original value : {}  encrypted value: {}";
 
     @Test
-    void testEncrypt() throws GeneralSecurityException {
+    void testEncrypt() {
         logger.info("testEncrypt:");
         CryptoCoder cryptoUtils = new CryptoUtils(SECRET_KEY);
         String encryptedValue = cryptoUtils.encrypt(PASS);
@@ -56,7 +55,7 @@ class CryptoUtilsTest {
     }
 
     @Test
-    void testDecrypt() throws GeneralSecurityException {
+    void testDecrypt() {
         logger.info("testDecrypt:");
         CryptoCoder cryptoUtils = new CryptoUtils(SECRET_KEY);
         String decryptedValue = cryptoUtils.decrypt(ENCRYPTED_PASS);