More fixes suggested by Project-wide Inspect Code... 91/141991/1
authorToineSiebelink <toine.siebelink@est.tech>
Thu, 4 Sep 2025 14:28:04 +0000 (15:28 +0100)
committerToineSiebelink <toine.siebelink@est.tech>
Thu, 4 Sep 2025 16:34:41 +0000 (17:34 +0100)
- Removed some code duplication highlighted by Inspect
- Refactored some logging duplication
- Corrected suspected duplicate logging by correcting the message (copy&paste error)
- Added 1 or 2 null checks as suggested by Inspect (might need test for coverage)

Issue-ID: CPS-2941
Change-Id: I2119535ecb2fc377309da3bd9e3777f71b711b9a
Signed-off-by: ToineSiebelink <toine.siebelink@est.tech>
cps-ri/src/main/java/org/onap/cps/ri/CpsModulePersistenceServiceImpl.java
cps-ri/src/main/java/org/onap/cps/ri/repository/FragmentRepositoryCpsPathQueryImpl.java
cps-service/src/main/java/org/onap/cps/api/parameters/FetchDescendantsOption.java
cps-service/src/main/java/org/onap/cps/events/EventsProducer.java
cps-service/src/main/java/org/onap/cps/init/AbstractModelLoader.java
cps-service/src/main/java/org/onap/cps/utils/JsonObjectMapper.java
cps-service/src/main/java/org/onap/cps/yang/YangTextSchemaSourceSetBuilder.java
policy-executor-stub/src/main/java/org/onap/cps/policyexecutor/stub/controller/PolicyExecutorStubController.java

index ef3a4c3..5e6faba 100755 (executable)
@@ -26,13 +26,10 @@ package org.onap.cps.ri;
 import static com.google.common.base.Preconditions.checkNotNull;
 import static org.opendaylight.yangtools.yang.common.YangConstants.RFC6020_YANG_FILE_EXTENSION;
 
-import com.google.common.base.MoreObjects;
 import com.google.common.collect.ImmutableSet;
 import io.micrometer.core.annotation.Timed;
 import jakarta.transaction.Transactional;
-import java.io.ByteArrayInputStream;
 import java.io.IOException;
-import java.io.InputStream;
 import java.nio.charset.StandardCharsets;
 import java.util.ArrayList;
 import java.util.Collection;
@@ -64,6 +61,7 @@ import org.onap.cps.ri.repository.ModuleReferenceRepository;
 import org.onap.cps.ri.repository.SchemaSetRepository;
 import org.onap.cps.ri.repository.YangResourceRepository;
 import org.onap.cps.spi.CpsModulePersistenceService;
+import org.onap.cps.yang.YangTextSchemaSourceSetBuilder;
 import org.opendaylight.yangtools.yang.common.Revision;
 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
@@ -294,23 +292,8 @@ public class CpsModulePersistenceServiceImpl implements CpsModulePersistenceServ
         final RevisionSourceIdentifier revisionSourceIdentifier =
             createIdentifierFromSourceName(checkNotNull(sourceName));
 
-        final YangTextSchemaSource tempYangTextSchemaSource = new YangTextSchemaSource(revisionSourceIdentifier) {
-            @Override
-            public Optional<String> getSymbolicName() {
-                return Optional.empty();
-            }
-
-            @Override
-            protected MoreObjects.ToStringHelper addToStringAttributes(
-                final MoreObjects.ToStringHelper toStringHelper) {
-                return toStringHelper;
-            }
-
-            @Override
-            public InputStream openStream() {
-                return new ByteArrayInputStream(source.getBytes(StandardCharsets.UTF_8));
-            }
-        };
+        final YangTextSchemaSource tempYangTextSchemaSource =
+            YangTextSchemaSourceSetBuilder.getYangTextSchemaSource(source, revisionSourceIdentifier);
         try {
             final YangModelDependencyInfo yangModelDependencyInfo
                 = YangModelDependencyInfo.forYangText(tempYangTextSchemaSource);
index ac9939c..4b30dcd 100644 (file)
@@ -89,7 +89,8 @@ public class FragmentRepositoryCpsPathQueryImpl implements FragmentRepositoryCps
 
     @Override
     @Transactional
-    public List<Long> findAnchorIdsForPagination(final DataspaceEntity dataspaceEntity, final CpsPathQuery cpsPathQuery,
+    public List<Long> findAnchorIdsForPagination(final DataspaceEntity dataspaceEntity,
+                                                 final CpsPathQuery cpsPathQuery,
                                                  final PaginationOption paginationOption) {
         final Query query = fragmentQueryBuilder.getQueryForAnchorIdsForPagination(
                 dataspaceEntity, cpsPathQuery, paginationOption);
index 05fa366..4e57609 100644 (file)
@@ -46,9 +46,7 @@ public class FetchDescendantsOption {
         Pattern.compile("^$|^all$|^none$|^direct$|^[0-9]+$|^-1$|^1$");
 
     /**
-     * Get depth.
-     *
-     * @return depth: -1 for all descendants, 0 for no descendants, or positive value for fixed level of descendants
+     * depth : -1 for all descendants, 0 for no descendants, or positive value for fixed level of descendants.
      */
     @Getter
     private final int depth;
index ee65e3a..77a2cd0 100644 (file)
@@ -60,15 +60,7 @@ public class EventsProducer<T> {
     public void sendCloudEvent(final String topicName, final String eventKey, final CloudEvent event) {
         final CompletableFuture<SendResult<String, CloudEvent>> eventFuture =
                 cloudEventKafkaTemplate.send(topicName, eventKey, event);
-        eventFuture.whenComplete((result, e) -> {
-            if (e == null) {
-                log.debug("Successfully sent event to topic : {} , Event : {}", result.getRecordMetadata().topic(),
-                        result.getProducerRecord().value());
-
-            } else {
-                log.error("Unable to send event to topic : {} due to {}", topicName, e.getMessage());
-            }
-        });
+        eventFuture.whenComplete((result, e) -> logOutcome(topicName, result, e));
     }
 
     /**
@@ -94,7 +86,6 @@ public class EventsProducer<T> {
      * @param event        message payload
      */
     public void sendEvent(final String topicName, final String eventKey, final Headers eventHeaders, final T event) {
-
         final ProducerRecord<String, T> producerRecord =
                 new ProducerRecord<>(topicName, null, eventKey, event, eventHeaders);
         final CompletableFuture<SendResult<String, T>> eventFuture = legacyKafkaEventTemplate.send(producerRecord);
@@ -111,20 +102,12 @@ public class EventsProducer<T> {
      */
     public void sendEvent(final String topicName, final String eventKey, final Map<String, Object> eventHeaders,
                           final T event) {
-
         sendEvent(topicName, eventKey, convertToKafkaHeaders(eventHeaders), event);
     }
 
     private void handleLegacyEventCallback(final String topicName,
-            final CompletableFuture<SendResult<String, T>> eventFuture) {
-        eventFuture.whenComplete((result, e) -> {
-            if (e == null) {
-                log.debug("Successfully sent event to topic : {} , Event : {}", result.getRecordMetadata().topic(),
-                        result.getProducerRecord().value());
-            } else {
-                log.error("Unable to send event to topic : {} due to {}", topicName, e.getMessage());
-            }
-        });
+                                           final CompletableFuture<SendResult<String, T>> eventFuture) {
+        eventFuture.whenComplete((result, e) -> logOutcome(topicName, result, e));
     }
 
     private Headers convertToKafkaHeaders(final Map<String, Object> eventMessageHeaders) {
@@ -133,4 +116,13 @@ public class EventsProducer<T> {
         return eventHeaders;
     }
 
+    private static void logOutcome(final String topicName, final SendResult<String, ?> result, final Throwable e) {
+        if (e == null) {
+            final Object event = result.getProducerRecord().value();
+            log.debug("Successfully sent event to topic : {} , Event : {}", topicName, event);
+        } else {
+            log.error("Unable to send event to topic : {} due to {}", topicName, e.getMessage());
+        }
+    }
+
 }
index f1bf78a..18f999a 100644 (file)
@@ -202,7 +202,7 @@ public abstract class AbstractModelLoader implements ModelLoader {
 
     private String getFileContentAsString(final String fileName) {
         try (final InputStream inputStream = getClass().getClassLoader().getResourceAsStream(fileName)) {
-            return new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);
+            return new String(inputStream != null ? inputStream.readAllBytes() : null, StandardCharsets.UTF_8);
         } catch (final Exception exception) {
             final String message = String.format("Onboarding failed as unable to read file: %s", fileName);
             log.debug(message);
index 16c6828..eec99c5 100644 (file)
@@ -138,7 +138,7 @@ public class JsonObjectMapper {
                 objectMapper.getTypeFactory().constructCollectionType(List.class, collectionEntryType);
             return objectMapper.readValue(jsonContent, collectionType);
         } catch (final JsonProcessingException e) {
-            log.error("Parsing error occurred while converting JSON content to specific class type.");
+            log.error("Parsing error occurred while converting JSON content to json array.");
             throw new DataValidationException("Parsing error occurred while converting "
                 + "JSON content to specific class type.", e.getMessage());
         }
index b33d7a8..a98e01d 100644 (file)
@@ -104,6 +104,36 @@ public final class YangTextSchemaSourceSetBuilder {
         generateSchemaContext(yangResourceNameToContent);
     }
 
+    /**
+     * Create a new YangTextSchemaSource.
+     *
+     * @param source                   Yang (module) source as string
+     * @param revisionSourceIdentifier Revision of the source
+     * @return a YangTextSchemaSource created from the given source
+     */
+    public static YangTextSchemaSource getYangTextSchemaSource(final String source,
+                                                               final RevisionSourceIdentifier
+                                                                   revisionSourceIdentifier) {
+        return new YangTextSchemaSource(revisionSourceIdentifier) {
+            @Override
+            public Optional<String> getSymbolicName() {
+                return Optional.empty();
+            }
+
+            @Override
+            protected MoreObjects.ToStringHelper addToStringAttributes(
+                final MoreObjects.ToStringHelper toStringHelper) {
+                return toStringHelper;
+            }
+
+            @Override
+            public InputStream openStream() {
+                return new ByteArrayInputStream(source.getBytes(StandardCharsets.UTF_8));
+            }
+        };
+    }
+
+
     private record YangTextSchemaSourceSetImpl(SchemaContext schemaContext) implements YangTextSchemaSourceSet {
 
         @Override
@@ -159,23 +189,7 @@ public final class YangTextSchemaSourceSetBuilder {
         final RevisionSourceIdentifier revisionSourceIdentifier =
             createIdentifierFromSourceName(checkNotNull(sourceName));
 
-        return new YangTextSchemaSource(revisionSourceIdentifier) {
-            @Override
-            public Optional<String> getSymbolicName() {
-                return Optional.empty();
-            }
-
-            @Override
-            protected MoreObjects.ToStringHelper addToStringAttributes(
-                final MoreObjects.ToStringHelper toStringHelper) {
-                return toStringHelper;
-            }
-
-            @Override
-            public InputStream openStream() {
-                return new ByteArrayInputStream(source.getBytes(StandardCharsets.UTF_8));
-            }
-        };
+        return getYangTextSchemaSource(source, revisionSourceIdentifier);
     }
 
     private static RevisionSourceIdentifier createIdentifierFromSourceName(final String sourceName) {
index 6f3fb95..ea5b5a1 100644 (file)
@@ -44,7 +44,8 @@ public class PolicyExecutorStubController implements OperationPermissionApi {
     private final Sleeper sleeper;
     private static final Pattern ERROR_CODE_PATTERN = Pattern.compile("(\\d{3})");
     private int decisionCounter = 0;
-    @SuppressWarnings("CanBeFinal") // Do NOT change below to final as it needs to be set during test
+    @SuppressWarnings({"CanBeFinal", "FieldCanBeLocal"})
+    // Do NOT change below to final as it needs to be set during test
     private static int slowResponseTimeInSeconds = 40;
 
     @Override