From ee0c7bcdb71ce3e87e20afc0931751c4340adbfa Mon Sep 17 00:00:00 2001
From: David Walluck
Date: Fri, 21 Feb 2025 09:45:36 -0500
Subject: [PATCH] style: Fix some more sonar issues with service
---
.../core/features/sbom/utils/SbomUtils.java | 9 +-
service/pom.xml | 1 -
.../sbomer/service/feature/FeatureFlags.java | 25 ++---
.../service/feature/s3/S3ClientFacade.java | 17 +--
.../service/feature/s3/S3StorageHandler.java | 12 +-
.../feature/sbom/errata/ErrataClient.java | 6 +-
.../sbom/errata/ErrataMessageHelper.java | 9 +-
.../feature/sbom/errata/dto/Errata.java | 15 +--
.../dto/enums/ErrataCDNContentType.java | 2 +-
.../dto/enums/ErrataCDNReleaseType.java | 2 +-
.../sbom/errata/event/AdvisoryEventUtils.java | 49 ++++----
.../event/EventNotificationFiringUtil.java | 3 +
...mmentAdvisoryOnRelevantEventsListener.java | 15 +--
...ReleaseStandardAdvisoryEventsListener.java | 63 +++++------
...ReleaseTextOnlyAdvisoryEventsListener.java | 16 +--
.../sbom/errors/AbstractExceptionMapper.java | 6 +-
.../generator/AbstractController.java | 53 ++++-----
.../rpm/controller/BrewRPMController.java | 22 ++--
...skRunBrewRPMGenerateDependentResource.java | 4 +-
.../umb/consumer/AmqpMessageConsumer.java | 10 +-
.../umb/consumer/PncNotificationHandler.java | 11 +-
.../umb/producer/AmqpMessageProducer.java | 2 +-
...enerationFinishedMessageBodyValidator.java | 8 +-
.../umb/producer/NotificationService.java | 8 +-
.../model/GenerationFinishedMessageBody.java | 4 +-
.../sbom/k8s/model/GenerationRequest.java | 9 +-
.../k8s/model/GenerationRequestFluent.java | 2 +
.../sbom/k8s/reconciler/BuildController.java | 52 +++++----
.../k8s/reconciler/OperationController.java | 24 ++--
.../k8s/reconciler/TektonResourceUtils.java | 9 +-
.../OperationConfigMissingCondition.java | 9 +-
...TaskRunGenerateBuildDependentResource.java | 15 +--
.../TaskRunInitDependentResource.java | 2 +-
...RunOperationGenerateDependentResource.java | 12 +-
...TaskRunOperationInitDependentResource.java | 2 +-
.../ErrataCachingKerberosClientSupport.java | 21 ++--
.../PyxisCachingKerberosClientSupport.java | 21 ++--
.../feature/sbom/model/RequestEvent.java | 49 ++++++--
.../service/feature/sbom/model/Sbom.java | 39 ++++++-
.../sbom/model/SbomGenerationRequest.java | 57 ++++++++--
.../feature/sbom/pyxis/PyxisClient.java | 24 ++--
.../sbom/pyxis/dto/PyxisRepository.java | 7 +-
.../pyxis/dto/PyxisRepositoryDetails.java | 4 +-
.../feature/sbom/service/AdvisoryService.java | 106 ++++++++++--------
.../sbom/service/RequestEventRepository.java | 52 +++++----
.../feature/sbom/service/SbomService.java | 23 ++--
.../image/controller/SyftImageController.java | 29 +++--
...RunSyftImageGenerateDependentResource.java | 2 +-
.../rest/v1alpha3/SyftImageApiV1Alpha3.java | 7 +-
.../jboss/sbomer/service/rest/RestUtils.java | 12 +-
.../rest/api/v1alpha3/ApiV1Alpha3.java | 12 +-
.../rest/api/v1alpha3/S3ApiV1Alpha3.java | 13 +--
.../rest/api/v1beta1/ManifestsV1Beta1.java | 6 +-
.../rest/api/v1beta1/RequestsV1Beta1.java | 4 +-
.../AbstractCriteriaAwareRepository.java | 8 +-
.../criteria/CriteriaAwareRepository.java | 16 +--
.../predicate/CustomPredicateBuilder.java | 28 +++--
.../predicate/CustomPredicateSortBuilder.java | 13 +--
.../CustomizedJpaPredicateSortVisitor.java | 18 ++-
.../CustomizedPredicateBuilderStrategy.java | 8 +-
.../SbomGenerationRequestRepositoryTest.java | 16 +--
.../feature/sbom/messaging/PncBuildTest.java | 8 +-
.../errata/ErrataMessageHelperTestCase.java | 1 +
.../errata/ErrataNotificationHandlerTest.java | 1 +
.../ReleaseAdvisoryEventsListenerTest.java | 36 ++----
.../reconciler/TektonResourceUtilsTest.java | 2 +-
.../service/test/utils/AmqpMessageHelper.java | 2 +-
.../test/utils/InMemoryLogHandler.java | 9 +-
68 files changed, 609 insertions(+), 553 deletions(-)
diff --git a/core/src/main/java/org/jboss/sbomer/core/features/sbom/utils/SbomUtils.java b/core/src/main/java/org/jboss/sbomer/core/features/sbom/utils/SbomUtils.java
index bd2f4f0ac..7c9996f5c 100644
--- a/core/src/main/java/org/jboss/sbomer/core/features/sbom/utils/SbomUtils.java
+++ b/core/src/main/java/org/jboss/sbomer/core/features/sbom/utils/SbomUtils.java
@@ -101,6 +101,7 @@
import com.github.packageurl.PackageURLBuilder;
public class SbomUtils {
+ public static final String PROTOCOL = "https://";
private SbomUtils() {
// This is a utility class
@@ -205,7 +206,7 @@ public static Component setPncBuildMetadata(Component component, Build pncBuild,
addExternalReference(
component,
ExternalReference.Type.BUILD_SYSTEM,
- "https://" + pncApiUrl + "/pnc-rest/v2/builds/" + pncBuild.getId(),
+ PROTOCOL + pncApiUrl + "/pnc-rest/v2/builds/" + pncBuild.getId(),
SBOM_RED_HAT_PNC_BUILD_ID);
addExternalReference(
@@ -249,7 +250,7 @@ public static Component setArtifactMetadata(Component component, Artifact artifa
addExternalReference(
component,
ExternalReference.Type.BUILD_SYSTEM,
- "https://" + pncApiUrl + "/pnc-rest/v2/artifacts/" + artifact.getId(),
+ PROTOCOL + pncApiUrl + "/pnc-rest/v2/artifacts/" + artifact.getId(),
SBOM_RED_HAT_PNC_ARTIFACT_ID);
return component;
}
@@ -263,7 +264,7 @@ public static Component setPncOperationMetadata(
addExternalReference(
component,
ExternalReference.Type.BUILD_SYSTEM,
- "https://" + pncApiUrl + "/pnc-rest/v2/operations/deliverable-analyzer/" + operation.getId(),
+ PROTOCOL + pncApiUrl + "/pnc-rest/v2/operations/deliverable-analyzer/" + operation.getId(),
SBOM_RED_HAT_PNC_OPERATION_ID);
}
@@ -705,7 +706,7 @@ public static void addPedigreeCommit(Component c, String url, String uid) {
"Found URL to be added as pedigree commit with the 'git@' protocol: '{}', trying to convert it into 'https://'",
url);
- url = "https://" + matcher.group(1) + "/" + matcher.group(2);
+ url = PROTOCOL + matcher.group(1) + "/" + matcher.group(2);
log.debug("Converted into: '{}'", url);
diff --git a/service/pom.xml b/service/pom.xml
index 0567ac1e2..1b0749f43 100644
--- a/service/pom.xml
+++ b/service/pom.xml
@@ -32,7 +32,6 @@
../pom.xml
- org.jboss.sbomer1.0.0-SNAPSHOTsbomer-service
diff --git a/service/src/main/java/org/jboss/sbomer/service/feature/FeatureFlags.java b/service/src/main/java/org/jboss/sbomer/service/feature/FeatureFlags.java
index 91a149e01..e4ece7bd7 100644
--- a/service/src/main/java/org/jboss/sbomer/service/feature/FeatureFlags.java
+++ b/service/src/main/java/org/jboss/sbomer/service/feature/FeatureFlags.java
@@ -172,9 +172,9 @@ public boolean standardErrataImageManifestGenerationEnabled() {
}
/**
- * Returns {@code true} if the manifest generation of text only Errata is enabled.
+ * Returns {@code true} if the manifest generation of text-only Errata is enabled.
*
- * @return {@code true} if the manifest generation of text only Errata is enabled, {@code false} otherwise
+ * @return {@code true} if the manifest generation of text-only Errata is enabled, {@code false} otherwise
*/
public boolean textOnlyErrataManifestGenerationEnabled() {
return unleash.isEnabled(TOGGLE_TEXTONLY_ERRATA_MANIFEST_GENERATION, textonlyErrataGeneration);
@@ -214,9 +214,9 @@ public boolean standardErrataImageReleaseManifestGenerationEnabled() {
}
/**
- * Returns {@code true} if the release manifest generation of text only Errata is enabled.
+ * Returns {@code true} if the release manifest generation of text-only Errata is enabled.
*
- * @return {@code true} if the release manifest generation of text only Errata is enabled, {@code false} otherwise
+ * @return {@code true} if the release manifest generation of text-only Errata is enabled, {@code false} otherwise
*/
public boolean textOnlyErrataReleaseManifestGenerationEnabled() {
return unleash.isEnabled(TOGGLE_TEXTONLY_ERRATA_RELEASE_MANIFEST_GENERATION, textonlyErrataReleaseGeneration);
@@ -257,18 +257,11 @@ private void updateToggles(final FeatureToggleResponse toggleResponse) {
TOGGLE_STANDARD_ERRATA_IMAGE_RELEASE_MANIFEST_GENERATION,
TOGGLE_TEXTONLY_ERRATA_RELEASE_MANIFEST_GENERATION)) {
FeatureToggle toggle = toggleResponse.getToggleCollection().getToggle(toggleName);
+ Boolean previousValue = toggleValues.put(toggleName, toggle.isEnabled());
- // FIXME: toggle != null is always 'true'
- if (toggle != null) {
- Boolean previousValue = toggleValues.put(toggleName, toggle.isEnabled());
-
- if (previousValue == null || previousValue != toggle.isEnabled()) {
- log.info("Feature toggle {} was just {}", toggleName, toggle.isEnabled() ? "enabled" : "disabled");
- bus.publish(EVENT_NAME, Map.of(toggleName, toggle.isEnabled()));
- }
- } else {
- log.debug("Feature toggle {} was disabled", toggleName);
- toggleValues.remove(toggleName);
+ if (previousValue == null || previousValue != toggle.isEnabled()) {
+ log.info("Feature toggle {} was just {}", toggleName, toggle.isEnabled() ? "enabled" : "disabled");
+ bus.publish(EVENT_NAME, Map.of(toggleName, toggle.isEnabled()));
}
}
@@ -280,7 +273,7 @@ private void updateToggles(final FeatureToggleResponse toggleResponse) {
}
/**
- * A callback which will be called when feature flags will be retreieved.
+ * A callback which will be called when feature flags are retrieved.
*/
@Override
public void togglesFetched(FeatureToggleResponse toggleResponse) {
diff --git a/service/src/main/java/org/jboss/sbomer/service/feature/s3/S3ClientFacade.java b/service/src/main/java/org/jboss/sbomer/service/feature/s3/S3ClientFacade.java
index 7be76b779..e9b3ced6e 100644
--- a/service/src/main/java/org/jboss/sbomer/service/feature/s3/S3ClientFacade.java
+++ b/service/src/main/java/org/jboss/sbomer/service/feature/s3/S3ClientFacade.java
@@ -73,9 +73,9 @@ void init(@Observes StartupEvent ev) {
/**
* Event listener for the {@link FeatureFlags#TOGGLE_S3_STORAGE} toggle. In case it is enabled, the S3 client is
- * instantiated. When the toggle is disabled, client is closed.
+ * instantiated. When the toggle is disabled, the client is closed.
*
- * @param flag
+ * @param flag the flags
*/
@ConsumeEvent(FeatureFlags.EVENT_NAME)
void featureFlag(Map flag) {
@@ -93,7 +93,7 @@ void featureFlag(Map flag) {
ensureClient();
} else {
- // And it was disabled, close the client, if there is one.
+ // And it was disabled, close the client if there is one.
if (client != null) {
log.debug("Disabling S3 storage handler");
client.close();
@@ -108,7 +108,7 @@ void featureFlag(Map flag) {
*/
public void ensureClient() {
if (client != null) {
- // In case the client it available, will assume it's valid.
+ // In case the client is available, will assume it's valid.
return;
}
@@ -116,6 +116,7 @@ public void ensureClient() {
log.debug("Instantiating new S3 client");
+ // TODO: Set the credentials explicitly on this builder
client = S3Client.builder().region(Region.of(bucketRegion())).build();
log.info("S3 client instantiated");
@@ -188,8 +189,8 @@ public void upload(Path path, String key) {
/**
* Returns list of paths within the S3 bucket to log files for a given {@link GenerationRequest} identifier.
*
- * @param generationRequestId
- * @return
+ * @param generationRequestId the generation request identifier
+ * @return the list of paths
*/
public List logFileNames(String generationRequestId) {
ListObjectsV2Request req = ListObjectsV2Request.builder()
@@ -215,8 +216,8 @@ public List logFileNames(String generationRequestId) {
/**
* Returns list of paths within the S3 bucket to log files for a given {@link GenerationRequest} identifier.
*
- * @param generationRequestId
- * @return
+ * @param generationRequestId the generation request identifier
+ * @return the path
*/
public String log(String generationRequestId, String path) {
diff --git a/service/src/main/java/org/jboss/sbomer/service/feature/s3/S3StorageHandler.java b/service/src/main/java/org/jboss/sbomer/service/feature/s3/S3StorageHandler.java
index 5e65d2b12..501c77eac 100644
--- a/service/src/main/java/org/jboss/sbomer/service/feature/s3/S3StorageHandler.java
+++ b/service/src/main/java/org/jboss/sbomer/service/feature/s3/S3StorageHandler.java
@@ -58,7 +58,7 @@ public class S3StorageHandler {
/**
* Returns all paths to files found under a given {@code rootDirectory}.
*
- * @param rootDirectory
+ * @param rootDirectory the root directory to scan for files
* @return List of paths to all files.
*/
private List getFilePaths(Path rootDirectory) {
@@ -147,8 +147,8 @@ public void storeFiles(GenerationRequest generationRequest) {
/**
* Returns list of paths within the S3 bucket to log files for a given {@link GenerationRequest} identifier.
*
- * @param generationRequestId
- * @return
+ * @param generationRequestId the generation request identifier
+ * @return the list of log file names
*/
public List listLogFilesInBucket(String generationRequestId) {
SbomGenerationRequest generationRequest = SbomGenerationRequest.findById(generationRequestId); // NOSONAR
@@ -167,10 +167,10 @@ public List listLogFilesInBucket(String generationRequestId) {
}
/**
- * Get log file for a given {@link GenerationRequest} and the requested path.
+ * Gets the log file for a given {@link GenerationRequest} and the requested path.
*
- * @param generationRequestId
- * @return
+ * @param generationRequestId the generation request identifier
+ * @return the log file content
*/
public String getLog(String generationRequestId, String path) {
SbomGenerationRequest generationRequest = SbomGenerationRequest.findById(generationRequestId); // NOSONAR
diff --git a/service/src/main/java/org/jboss/sbomer/service/feature/sbom/errata/ErrataClient.java b/service/src/main/java/org/jboss/sbomer/service/feature/sbom/errata/ErrataClient.java
index 2714208af..d8f0f6c92 100644
--- a/service/src/main/java/org/jboss/sbomer/service/feature/sbom/errata/ErrataClient.java
+++ b/service/src/main/java/org/jboss/sbomer/service/feature/sbom/errata/ErrataClient.java
@@ -140,7 +140,7 @@ default Collection getVariantOfProductAndProductVersi
.filter(
variant -> productVersionId
.equals(variant.getAttributes().getRelationships().getProductVersion().getId()))
- .collect(Collectors.toList());
+ .toList();
}
default Map> getCDNReposOfVariant(
@@ -152,7 +152,6 @@ default Map> getCDNReposOfVariant(
}
default Collection getCDNReposOfVariant(String variantName, String shortProductName) {
-
Collection allCDNRepos = getAllEntities(
Map.of("filter[variant_name]", variantName),
this::getAllCDNRepos);
@@ -163,14 +162,13 @@ default Collection getCDNReposOfVariant(String variantN
&& !cdn.getAttributes().getContentType().equalsIgnoreCase("docker"))
.map(cdn -> new ErrataCDNRepoNormalized(cdn, variantName, !"rhel".equalsIgnoreCase(shortProductName)))
.distinct()
- .collect(Collectors.toList());
+ .toList();
}
// Default method for handling pagination logic with a generic type `T` and a function `getPageFunction`
default Collection getAllEntities(
Map filters,
Function> getPageFunction) {
-
ErrataQueryParameters parameters = ErrataQueryParameters.builder().withFilters(filters).build();
Collection entities = new ArrayList<>();
diff --git a/service/src/main/java/org/jboss/sbomer/service/feature/sbom/errata/ErrataMessageHelper.java b/service/src/main/java/org/jboss/sbomer/service/feature/sbom/errata/ErrataMessageHelper.java
index 8df8ff2bd..f5e0de9c3 100644
--- a/service/src/main/java/org/jboss/sbomer/service/feature/sbom/errata/ErrataMessageHelper.java
+++ b/service/src/main/java/org/jboss/sbomer/service/feature/sbom/errata/ErrataMessageHelper.java
@@ -35,8 +35,11 @@
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
public class ErrataMessageHelper {
+ private ErrataMessageHelper() {
+ throw new IllegalStateException("This is a utility class that should not be instantiated");
+ }
- static final ObjectMapper jsonObjectMapper = new ObjectMapper().registerModule(new JavaTimeModule())
+ private static final ObjectMapper JSON_OBJECT_MAPPER = new ObjectMapper().registerModule(new JavaTimeModule())
.registerModule(new SimpleModule().addDeserializer(Instant.class, new CustomInstantDeserializer()))
.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
.setPropertyNamingStrategy(PropertyNamingStrategies.LOWER_CAMEL_CASE)
@@ -50,11 +53,11 @@ public static String decode(byte[] encodedJson) {
}
public static ErrataStatusChangeMessageBody fromStatusChangeMessage(String json) throws JsonProcessingException {
- return jsonObjectMapper.readValue(json, ErrataStatusChangeMessageBody.class);
+ return JSON_OBJECT_MAPPER.readValue(json, ErrataStatusChangeMessageBody.class);
}
public static ErrataStatusChangeMessageBody fromStatusChangeMessage(JsonNode jsonNode) throws IOException {
- return jsonObjectMapper.readValue(
+ return JSON_OBJECT_MAPPER.readValue(
jsonNode.isTextual() ? jsonNode.textValue().getBytes() : jsonNode.toString().getBytes(),
ErrataStatusChangeMessageBody.class);
}
diff --git a/service/src/main/java/org/jboss/sbomer/service/feature/sbom/errata/dto/Errata.java b/service/src/main/java/org/jboss/sbomer/service/feature/sbom/errata/dto/Errata.java
index ed01fa33e..1232c8c3e 100644
--- a/service/src/main/java/org/jboss/sbomer/service/feature/sbom/errata/dto/Errata.java
+++ b/service/src/main/java/org/jboss/sbomer/service/feature/sbom/errata/dto/Errata.java
@@ -139,16 +139,11 @@ public static class Content {
private WrappedContent content;
public Optional getDetails() {
- switch (originalType) {
- case RHSA:
- return Optional.of(errata.rhsa);
- case RHBA:
- return Optional.of(errata.rhba);
- case RHEA:
- return Optional.of(errata.rhea);
- default:
- return Optional.empty();
- }
+ return switch (originalType) {
+ case RHSA -> Optional.of(errata.rhsa);
+ case RHBA -> Optional.of(errata.rhba);
+ case RHEA -> Optional.of(errata.rhea);
+ };
}
public Optional getNotesMapping() {
diff --git a/service/src/main/java/org/jboss/sbomer/service/feature/sbom/errata/dto/enums/ErrataCDNContentType.java b/service/src/main/java/org/jboss/sbomer/service/feature/sbom/errata/dto/enums/ErrataCDNContentType.java
index a57c7a796..2d1ce42f4 100644
--- a/service/src/main/java/org/jboss/sbomer/service/feature/sbom/errata/dto/enums/ErrataCDNContentType.java
+++ b/service/src/main/java/org/jboss/sbomer/service/feature/sbom/errata/dto/enums/ErrataCDNContentType.java
@@ -19,11 +19,11 @@
import lombok.Getter;
+@Getter
public enum ErrataCDNContentType {
BINARY("Binary"), DEBUGINFO("Debuginfo"), SOURCE("Source");
- @Getter
final String type;
ErrataCDNContentType(String type) {
diff --git a/service/src/main/java/org/jboss/sbomer/service/feature/sbom/errata/dto/enums/ErrataCDNReleaseType.java b/service/src/main/java/org/jboss/sbomer/service/feature/sbom/errata/dto/enums/ErrataCDNReleaseType.java
index 74ea2b185..f5d7ab8a4 100644
--- a/service/src/main/java/org/jboss/sbomer/service/feature/sbom/errata/dto/enums/ErrataCDNReleaseType.java
+++ b/service/src/main/java/org/jboss/sbomer/service/feature/sbom/errata/dto/enums/ErrataCDNReleaseType.java
@@ -19,11 +19,11 @@
import lombok.Getter;
+@Getter
public enum ErrataCDNReleaseType {
PRIMARY("Primary"), EUS("EUS"), FASTTRACK("FastTrack"), LONGLIFE("LongLife");
- @Getter
final String type;
ErrataCDNReleaseType(String type) {
diff --git a/service/src/main/java/org/jboss/sbomer/service/feature/sbom/errata/event/AdvisoryEventUtils.java b/service/src/main/java/org/jboss/sbomer/service/feature/sbom/errata/event/AdvisoryEventUtils.java
index b7fa74e2c..b66e07fca 100644
--- a/service/src/main/java/org/jboss/sbomer/service/feature/sbom/errata/event/AdvisoryEventUtils.java
+++ b/service/src/main/java/org/jboss/sbomer/service/feature/sbom/errata/event/AdvisoryEventUtils.java
@@ -21,6 +21,7 @@
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
+import java.util.LinkedHashSet;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
@@ -47,17 +48,20 @@
@Slf4j
public class AdvisoryEventUtils {
+ private AdvisoryEventUtils() {
+ throw new IllegalStateException("This is a utility class that should not be instantiated");
+ }
/*
- * In case of mainline RHEL releases if the ProductVersion contains a major.minor, augment the CPE. e.g. in case of
- * ProductVersion 'RHEL-9.4.0.Z.EUS', change
+ * In the case of mainline RHEL releases, if the ProductVersion contains a major.minor, augment the CPE, e.g., in
+ * the case of ProductVersion 'RHEL-9.4.0.Z.EUS', change
*
* cpe:/a:redhat:enterprise_linux:9::highavailability -> cpe:/a:redhat:enterprise_linux:9.4::highavailability
* cpe:/a:redhat:enterprise_linux:9::server -> cpe:/a:redhat:enterprise_linux:9.4::server
*/
/**
- * In case of mainline RHEL releases if the ProductVersion contains a {major}.{minor} pattern, augment the original
- * CPEs with the {minor} value, if not present already.
+ * In the case of mainline RHEL releases, if the ProductVersion contains a {major}.{minor} pattern, augment the
+ * original CPEs with the {minor} value, if not present already.
*
* @param productVersion {@link ProductVersionEntry} to analyze
* @param originalCPEs the set of original CPEs to augment with more granular {minor} value
@@ -130,7 +134,7 @@ public static List extractPurlUrisFromManifestNode(JsonNode manifestNode
* Creates a set of purls from the given list of {@link RepositoryCoordinates} and with a specified version
*
* @param repositories the list of {@link RepositoryCoordinates} which contain registry, repository and tag values
- * @param version the version to setup on the purls
+ * @param version the version to set up on the purls
* @param includeRepositoryQualifiers the flag which specifies whether the purls should contain the repository
* coordinates as qualifiers
* @return The list of purls as strings.
@@ -139,19 +143,22 @@ public static Set createPurls(
List repositories,
String version,
boolean includeRepositoryQualifiers) {
-
- return repositories.stream()
+ Set set = repositories.stream()
.map(repository -> createPurl(repository, version, includeRepositoryQualifiers))
.filter(Objects::nonNull)
- .sorted(Comparator.comparingInt(String::length).reversed()) // longest first
- .collect(Collectors.toSet());
+ .sorted(
+ Comparator.comparingInt(String::length)
+ .reversed() // longest first
+ .thenComparing(Comparator.naturalOrder()))
+ .collect(Collectors.toCollection(LinkedHashSet::new));
+ return Collections.unmodifiableSet(set);
}
/**
* Creates a purl from the given {@link RepositoryCoordinates} and with a specified version
*
- * @param repositories the {@link RepositoryCoordinates} which contains registry, repository and tag values
- * @param version the version to setup on the purl
+ * @param repository the {@link RepositoryCoordinates} which contains registry, repository and tag values
+ * @param version the version to set up on the purl
* @param includeRepositoryQualifiers the flag which specifies whether the purl should contain the repository
* coordinates as qualifiers
* @return The purl as string.
@@ -180,7 +187,7 @@ public static String createPurl(
/**
* Creates a set of purls from the starting purl and the list of {@link ErrataCDNRepoNormalized} this build is
- * publised to
+ * published to
*
* @param purl the purl to modify
* @param cdns the list of {@link ErrataCDNRepoNormalized} which contain the CDN information
@@ -209,7 +216,7 @@ public static Set createPurls(
.map(cdn -> rebuildPurl(purl, cdn))
.collect(Collectors.toSet());
} else if (componentArch.equals("noarch")) {
- // Select the "-rpms" CDN repositories (excluding -source-rpms and -debug-rpms) and include all the
+ // Select the "-rpms" CDN repositories (excluding "-source-rpms" and "-debug-rpms") and include all the
// archs provided
return cdns.stream()
.filter(
@@ -252,7 +259,7 @@ public static Set createPurls(
/**
* Given an input purl, creates a new purl with the same name, namespace, subpath, type, version and qualifiers.
* Additionally, add the new qualifier "repository_id" with the values provided in the
- * {@link ErrataCDNRepoNormalized}. Finally rebuilds the purl to make sure it is valid and qualifiers are properly
+ * {@link ErrataCDNRepoNormalized}. Finally, rebuilds the purl to make sure it is valid and qualifiers are properly
* sorted.
*
* @param originalPurl the input purl string
@@ -288,7 +295,7 @@ public static String rebuildPurl(String originalPurl, ErrataCDNRepoNormalized cd
/**
* Given an input purl, creates a new purl with the same name, namespace, subpath, type, version and qualifiers.
* Additionally, add new qualifiers "tag" and "repository_url" with the values provided in the
- * {@link RepositoryCoordinates}. Finally rebuilds the purl to make sure it is valid and qualifiers are properly
+ * {@link RepositoryCoordinates}. Finally, rebuilds the purl to make sure it is valid and qualifiers are properly
* sorted.
*
* @param originalPurl the input purl string
@@ -325,11 +332,11 @@ public static String rebuildPurl(String originalPurl, RepositoryCoordinates repo
/**
* Given an input purl, creates a set of new purls with the same name, namespace, subpath, type, version and
* qualifiers. Additionally, add new qualifiers "tag" and "repository_url" with the values provided in the
- * {@link RepositoryCoordinates}. Finally rebuilds the purls to make sure they are valid and qualifiers are properly
- * sorted.
+ * {@link RepositoryCoordinates}. Finally, rebuilds the purls to make sure they are valid and qualifiers are
+ * properly sorted.
*
* @param originalPurl the input purl string
- * @param repository the list of {@link RepositoryCoordinates} which contain registry, repository and tag values
+ * @param repositories the list of {@link RepositoryCoordinates} which contain registry, repository and tag values
* @return The new validated set of purls as string.
*/
public static Set rebuildPurls(String originalPurl, List repositories) {
@@ -338,9 +345,9 @@ public static Set rebuildPurls(String originalPurl, List repositories) {
@@ -357,7 +364,7 @@ public static RepositoryCoordinates findPreferredRepo(List> productVersionToCPEs = mapProductVersionToCPEs(advisoryBuildDetails);
// Associate each build (NVR) in an advisory to its build manifest generation
@@ -248,7 +248,7 @@ protected void releaseManifestsForRPMBuilds(
generationToCDNs);
// FIXME: 'Optional.get()' without 'isPresent()' check
log.info(
- "Saved and modified SBOM '{}' for generation '{}' for ProductVersion '{}' of errata '{}'",
+ "Saved and modified SBOM '{}' for generation '{}' for ProductVersion '{}' of errata '{}' for RPM builds",
sbom,
releaseGeneration.getId(),
productVersion.getName(),
@@ -317,7 +317,7 @@ protected void releaseManifestsForDockerBuilds(
generationToRepositories);
// FIXME: 'Optional.get()' without 'isPresent()' check
log.info(
- "Saved and modified SBOM '{}' for generation '{}' for ProductVersion '{}' of errata '{}'",
+ "Saved and modified SBOM '{}' for generation '{}' for ProductVersion '{}' of errata '{}' for Docker builds",
sbom,
releaseGeneration.getId(),
productVersion.getName(),
@@ -360,7 +360,7 @@ protected Component createRootComponentForRPMBuildItem(
Map> generationToCDNs) {
// From the generation triggered from this build (NVR), find the single manifest created and get the manifest
- // content, we need to copy the main component
+ // content that we need to copy the main component
V1Beta1RequestManifestRecord manifestRecord = advisoryManifestsRecord.manifests()
.stream()
.filter(manifest -> manifest.generation().id().equals(generation.id()))
@@ -382,7 +382,7 @@ protected Component createRootComponentForRPMBuildItem(
Set evidencePurls = AdvisoryEventUtils
.createPurls(manifestMainComponent.getPurl(), allCDNs, manifestArches);
- // Finally create the root component for this build (NVR) from the manifest
+ // Finally, create the root component for this build (NVR) from the manifest
Component nvrRootComponent = SbomUtils.createComponent(
null,
manifestMainComponent.getName(),
@@ -406,8 +406,8 @@ protected Component createRootComponentForDockerBuildItem(
V1Beta1RequestRecord advisoryManifestsRecord,
Map> generationToRepositories) {
- // From the generation triggered from this build (NVR), find the image index manifest and get the manifest
- // content, we need to copy the main component
+ // From the generation triggered from this build (NVR), find the image-index manifest and get the manifest
+ // content that we need to copy the main component
V1Beta1RequestManifestRecord imageIndexManifest = findImageIndexManifest(advisoryManifestsRecord, generation);
Sbom imageIndexSbom = sbomService.get(imageIndexManifest.id());
Component imageIndexMainComponent = SbomUtils.fromJsonNode(imageIndexSbom.getSbom()).getComponents().get(0);
@@ -422,7 +422,7 @@ protected Component createRootComponentForDockerBuildItem(
Set evidencePurls = AdvisoryEventUtils
.createPurls(repositories, imageIndexMainComponent.getVersion(), true);
- // Finally create the root component for this build (NVR) from the image index manifest
+ // Finally, create the root component for this build (NVR) from the image index manifest
Component nvrRootComponent = SbomUtils.createComponent(
null,
imageIndexMainComponent.getName(),
@@ -473,18 +473,17 @@ protected Sbom saveReleaseManifestForRPMGeneration(
requestEvent.getId(),
erratum,
productVersion,
- toolVersion,
productVersionBom);
sbom.setReleaseMetadata(metadataNode);
sbom = sbomService.save(sbom);
- // 2 - For every generation, find all the existing manifests and update the with release repo
+ // 2 - For every generation, find all the existing manifests and update them with release repo
// data
- log.debug("Processing {} generations...", generationToCDNs.size());
- for (String generationId : generationToCDNs.keySet()) {
-
+ log.debug("Processing {} generations for RPMs...", generationToCDNs.size());
+ for (Map.Entry> entry : generationToCDNs.entrySet()) {
+ String generationId = entry.getKey();
// 2.1 Get all the CDNs associated with this request
- Collection generationCDNs = generationToCDNs.get(generationId);
+ List generationCDNs = entry.getValue();
// 2.2 - For every manifest previously generated from this generation
Collection buildManifests = advisoryManifestsRecord.manifests()
@@ -527,7 +526,6 @@ protected Sbom saveReleaseManifestForRPMGeneration(
requestEvent.getId(),
erratum,
productVersion,
- toolVersion,
manifestBom);
buildManifest.setReleaseMetadata(buildManifestMetadataNode);
}
@@ -551,6 +549,7 @@ protected Sbom saveReleaseManifestForRPMGeneration(
}
}
+ // TODO: Refactor
// Add a very long timeout because this method could potentially need to update hundreds of manifests
@Retry(maxRetries = 10)
protected Sbom saveReleaseManifestForDockerGeneration(
@@ -584,22 +583,21 @@ protected Sbom saveReleaseManifestForDockerGeneration(
requestEvent.getId(),
erratum,
productVersion,
- toolVersion,
productVersionBom);
sbom.setReleaseMetadata(metadataNode);
sbom = sbomService.save(sbom);
- // 2 - For every generation, find all the existing manifests and update the with release repo
+ // 2 - For every generation, find all the existing manifests and update them with release repo
// data
- log.debug("Processing {} generations...", generationToRepositories.size());
- for (String generationId : generationToRepositories.keySet()) {
-
+ log.debug("Processing {} generations for Docker...", generationToRepositories.size());
+ for (Map.Entry> entry : generationToRepositories.entrySet()) {
+ String generationId = entry.getKey();
// 2.1 - Select the repository with longest repoFragment + tag
- List repositories = generationToRepositories.get(generationId);
+ List repositories = entry.getValue();
RepositoryCoordinates preferredRepo = AdvisoryEventUtils.findPreferredRepo(repositories);
- // 2.2 - Regenerate the manifest purls using the preferredRepo and keep track of the updates, we need
- // them to update the index manifest variants
+ // 2.2 - Regenerate the manifest purls using the preferredRepo and keep track of the updates.
+ // We need them to update the index manifest variants
Collection buildManifests = advisoryManifestsRecord.manifests()
.stream()
.filter(manifest -> manifest.generation().id().equals(generationId))
@@ -629,11 +627,13 @@ protected Sbom saveReleaseManifestForDockerGeneration(
.getComponent()
.getDescription()
.contains(buildManifest.getRootPurl())) {
- // FIXME: Result of String.replace() is ignored
manifestBom.getMetadata()
.getComponent()
- .getDescription()
- .replace(buildManifest.getRootPurl(), rebuiltPurl);
+ .setDescription(
+ manifestBom.getMetadata()
+ .getComponent()
+ .getDescription()
+ .replace(buildManifest.getRootPurl(), rebuiltPurl));
}
}
if (manifestBom.getComponents() != null && !manifestBom.getComponents().isEmpty()) {
@@ -675,7 +675,6 @@ protected Sbom saveReleaseManifestForDockerGeneration(
requestEvent.getId(),
erratum,
productVersion,
- toolVersion,
manifestBom);
buildManifest.setReleaseMetadata(buildManifestMetadataNode);
}
@@ -711,7 +710,7 @@ protected Map> getAdvisoryBuildDetails(Stri
productVersionEntry -> productVersionEntry.getBuilds()
.stream()
.flatMap(build -> build.getBuildItems().values().stream())
- .collect(Collectors.toList())));
+ .toList()));
}
@Retry(maxRetries = 10)
@@ -756,7 +755,7 @@ protected List getRepositoriesDetails(String nvr) {
repository.getRepository(),
tag.getName())))
.filter(repoCoordinate -> repoCoordinate.getRepositoryFragment() != null)
- .collect(Collectors.toList());
+ .toList();
}
@Retry(maxRetries = 10)
@@ -765,7 +764,7 @@ protected List getCDNDetails(BuildItem buildItem, Strin
buildItem.getVariantArch()
.keySet()
.forEach(variant -> allCDNs.addAll(errataClient.getCDNReposOfVariant(variant, productShortName)));
- return allCDNs.stream().distinct().collect(Collectors.toList());
+ return allCDNs.stream().distinct().toList();
}
/*
@@ -790,9 +789,7 @@ protected ObjectNode collectReleaseInfo(
String requestEventId,
Errata erratum,
ProductVersionEntry versionEntry,
- String toolVersion,
Bom manifest) {
-
ObjectNode releaseMetadata = ObjectMapperProvider.json().createObjectNode();
releaseMetadata.put(REQUEST_ID, requestEventId);
// FIXME: 'Optional.get()' without 'isPresent()' check
@@ -921,7 +918,7 @@ private Map mapNVRToBuildGeneration(V1Beta1Requ
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
}
- // Helper method to get the all the architectures in the manifest
+ // Helper method to get all the architectures in the manifest
private Set getAllArchitectures(Bom bom) {
Set manifestArches = new HashSet<>();
for (Component component : bom.getComponents()) {
diff --git a/service/src/main/java/org/jboss/sbomer/service/feature/sbom/errata/event/release/ReleaseTextOnlyAdvisoryEventsListener.java b/service/src/main/java/org/jboss/sbomer/service/feature/sbom/errata/event/release/ReleaseTextOnlyAdvisoryEventsListener.java
index 10c508c73..48e1d35ec 100644
--- a/service/src/main/java/org/jboss/sbomer/service/feature/sbom/errata/event/release/ReleaseTextOnlyAdvisoryEventsListener.java
+++ b/service/src/main/java/org/jboss/sbomer/service/feature/sbom/errata/event/release/ReleaseTextOnlyAdvisoryEventsListener.java
@@ -113,7 +113,7 @@ public void onReleaseAdvisoryEvent(@ObservesAsync TextOnlyAdvisoryReleaseEvent e
erratum.getDetails().get().getId());
// If the notes contain a "manifest" field, search the successful generations for all the purls listed
- // (there are no generations associated to the requestevent because no generations were triggered)
+ // (there are no generations associated with the request event because no generations were triggered)
manifestsPurls = AdvisoryEventUtils.extractPurlUrisFromManifestNode(notes);
} else {
log.debug(
@@ -149,13 +149,13 @@ public void onReleaseAdvisoryEvent(@ObservesAsync TextOnlyAdvisoryReleaseEvent e
productType);
} catch (Exception e) {
log.error(
- "An error occured during the creation of release manifests for event '{}'",
+ "An error occurred during the creation of release manifests for event '{}'",
requestEvent.getId(),
e);
markRequestFailed(
requestEvent,
event.getReleaseGenerations().values(),
- "An error occured during the creation of the release manifest");
+ "An error occurred during the creation of the release manifest");
}
// Let's trigger the update of statuses and advisory comments
@@ -239,8 +239,8 @@ protected void doUpdateGenerationsStatus(Collection relea
}
}
+ // FIXME: 'Optional.get()' without 'isPresent()' check
private Bom createProductVersionBom(Component.Type productType, Errata erratum, String toolVersion) {
- // FIXME: 'Optional.get()' without 'isPresent()' check
String productName = erratum.getDetails().get().getProduct().getName();
String productVersion = erratum.getContent().getContent().getProductVersionText();
String cpe = erratum.getContent().getContent().getTextOnlyCpe();
@@ -281,7 +281,7 @@ protected Component createRootComponentForSbom(Sbom sbom) {
Map.of("repository_url", Constants.MRRC_URL),
!SbomUtils.hasProperty(manifestMainComponent, "deliverable-url"));
- // Finally create the root component for this build (NVR) from the manifest
+ // Finally, create the root component for this build (NVR) from the manifest
Component sbomRootComponent = SbomUtils.createComponent(manifestMainComponent);
sbomRootComponent.setSupplier(manifestMainComponent.getSupplier());
@@ -327,7 +327,6 @@ protected Sbom saveReleaseManifestForTextOnlyAdvisories(
erratum,
productName,
productVersion,
- toolVersion,
productVersionBom);
releaseSbom.setReleaseMetadata(metadataNode);
releaseSbom = sbomService.save(releaseSbom);
@@ -359,7 +358,6 @@ protected Sbom saveReleaseManifestForTextOnlyAdvisories(
erratum,
productName,
productVersion,
- toolVersion,
manifestBom);
buildManifest.setReleaseMetadata(buildManifestMetadataNode);
}
@@ -391,17 +389,15 @@ protected Sbom saveReleaseManifestForTextOnlyAdvisories(
public static final String PRODUCT_VERSION = "product_version";
public static final String PURL_LIST = "purl_list";
+ // FIXME: 'Optional.get()' without 'isPresent()' check
protected ObjectNode collectReleaseInfo(
String requestEventId,
Errata erratum,
String product,
String productVersion,
- String toolVersion,
Bom manifest) {
-
ObjectNode releaseMetadata = ObjectMapperProvider.json().createObjectNode();
releaseMetadata.put(REQUEST_ID, requestEventId);
- // FIXME: 'Optional.get()' without 'isPresent()' check
releaseMetadata.put(ERRATA, erratum.getDetails().get().getFulladvisory());
releaseMetadata.put(ERRATA_ID, erratum.getDetails().get().getId());
if (erratum.getDetails().get().getActualShipDate() != null) {
diff --git a/service/src/main/java/org/jboss/sbomer/service/feature/sbom/errors/AbstractExceptionMapper.java b/service/src/main/java/org/jboss/sbomer/service/feature/sbom/errors/AbstractExceptionMapper.java
index ea45fa69d..0064b0bee 100644
--- a/service/src/main/java/org/jboss/sbomer/service/feature/sbom/errors/AbstractExceptionMapper.java
+++ b/service/src/main/java/org/jboss/sbomer/service/feature/sbom/errors/AbstractExceptionMapper.java
@@ -56,11 +56,11 @@ String generateErrorId() {
return UUID.randomUUID().toString();
}
- Status getStatus(T ex) {
+ Status getStatus(T ex) { // NOSONAR: This is an abstract class, the implementation may use ex
return Status.INTERNAL_SERVER_ERROR;
}
- String errorMessage(T ex) {
+ String errorMessage(T ex) { // NOSONAR: This is an abstract class, the implementation may use ex
return "An error occurred while processing your request, please contact administrator providing the 'errorId'";
}
@@ -82,7 +82,7 @@ List customErrors() {
/**
*
- * A hook that is executed before the response is returned. It can be used for example to help audit things (log
+ * A hook that is executed before the response is returned. It can be used, for example, to help audit things (log
* messages).
*
*
diff --git a/service/src/main/java/org/jboss/sbomer/service/feature/sbom/features/generator/AbstractController.java b/service/src/main/java/org/jboss/sbomer/service/feature/sbom/features/generator/AbstractController.java
index 3768d8e34..c9a0b1164 100644
--- a/service/src/main/java/org/jboss/sbomer/service/feature/sbom/features/generator/AbstractController.java
+++ b/service/src/main/java/org/jboss/sbomer/service/feature/sbom/features/generator/AbstractController.java
@@ -111,8 +111,8 @@ protected abstract UpdateControl updateRequest(
* Returns the {@link TaskRun} having the specified {@link SbomGenerationPhase} from the given {@link TaskRun}
* {@link Set}.
*
- * @param taskRuns
- * @param phase
+ * @param taskRuns the task runs
+ * @param phase the phase
* @return The {@link TaskRun} or {@code null} if not found.
*/
protected TaskRun findTaskRun(Set taskRuns, SbomGenerationPhase phase) {
@@ -125,8 +125,8 @@ protected TaskRun findTaskRun(Set taskRuns, SbomGenerationPhase phase)
* Returns a set of {@link TaskRun}s having the specified {@link SbomGenerationPhase} from the given {@link TaskRun}
* {@link Set}.
*
- * @param taskRuns
- * @param phase
+ * @param taskRuns the task runs
+ * @param phase the phase
* @return The {@link Set} containing {@link TaskRun} or empty set if not found.
*/
protected Set findTaskRuns(Set taskRuns, SbomGenerationPhase phase) {
@@ -151,7 +151,7 @@ protected Set findTaskRuns(Set taskRuns, SbomGenerationPhase p
*
* @param generationRequest the generation request
* @param boms the BOMs to store
- * @return
+ * @return the list of stored {@link Sbom}s
*/
@Transactional
protected List storeBoms(GenerationRequest generationRequest, List boms) {
@@ -211,7 +211,7 @@ protected boolean isFinished(TaskRun taskRun) {
protected Boolean isSuccessful(TaskRun taskRun) {
if (!isFinished(taskRun)) {
log.trace("TaskRun '{}' still in progress", taskRun.getMetadata().getName());
- return null;
+ return null; // FIXME: This is not really binary, but trinary state
}
if (taskRun.getStatus() != null && taskRun.getStatus().getConditions() != null
@@ -273,10 +273,10 @@ public UpdateControl reconcile(
action = reconcileGenerating(generationRequest, secondaryResources);
break;
case FINISHED:
- action = reconcileFinished(generationRequest, secondaryResources);
+ action = reconcileFinished(generationRequest);
break;
case FAILED:
- action = reconcileFailed(generationRequest, secondaryResources);
+ action = reconcileFailed(generationRequest);
break;
default:
break;
@@ -321,17 +321,12 @@ protected UpdateControl reconcileNew(
}
/**
- *
* Handling of failed generation.
- *
*
- * @param generationRequest
- * @param secondaryResources
- * @return
+ * @param generationRequest the generation request
+ * @return the update control for the generation request
*/
- protected UpdateControl reconcileFailed(
- GenerationRequest generationRequest,
- Set secondaryResources) {
+ protected UpdateControl reconcileFailed(GenerationRequest generationRequest) {
log.debug("Reconcile FAILED for '{}'...", generationRequest.getName());
s3LogHandler.storeFiles(generationRequest);
@@ -348,21 +343,17 @@ protected UpdateControl reconcileFailed(
* Handles finished generation.
*
*
- * @param generationRequest
- * @param secondaryResources
- * @return
+ * @param generationRequest the generation request
+ * @return the update control for the generation request
*/
@ActivateRequestContext
- protected UpdateControl reconcileFinished(
- GenerationRequest generationRequest,
- Set secondaryResources) {
-
+ protected UpdateControl reconcileFinished(GenerationRequest generationRequest) {
log.debug("Reconcile FINISHED for '{}'...", generationRequest.getName());
// Store files in S3
try {
s3LogHandler.storeFiles(generationRequest);
- } catch (Throwable e) {
+ } catch (Exception e) {
// This is not fatal
log.warn("Storing files in S3 failed", e);
}
@@ -373,14 +364,14 @@ protected UpdateControl reconcileFinished(
return UpdateControl.noUpdate();
}
- protected void performPost(List sboms, GenerationRequest generationRequest) {
+ protected void performPost(List sboms) {
CompletableFuture publishToUmb = CompletableFuture.runAsync(() -> {
try {
notificationService.notifyCompleted(sboms);
} catch (FeatureDisabledException e) {
log.warn(e.getMessage(), e);
}
- }).exceptionally((e) -> {
+ }).exceptionally(e -> {
throw new ApplicationException("UMB notification failed: {}", e.getMessage(), e);
});
@@ -390,7 +381,7 @@ protected void performPost(List sboms, GenerationRequest generationRequest
} catch (FeatureDisabledException e) {
log.warn(e.getMessage(), e);
}
- }).exceptionally((e) -> {
+ }).exceptionally(e -> {
throw new ApplicationException("Atlas upload failed: {}", e.getMessage(), e);
});
@@ -410,9 +401,9 @@ protected void performPost(List sboms, GenerationRequest generationRequest
* Handles updates to {@link GenerationRequest} being in progress.
*
*
- * @param generationRequest
- * @param secondaryResources
- * @return
+ * @param generationRequest the generation request
+ * @param secondaryResources the secondary resources
+ * @return the update control for the generation request
*/
@Transactional
protected abstract UpdateControl reconcileGenerating(
@@ -422,7 +413,7 @@ protected abstract UpdateControl reconcileGenerating(
/**
* Removes related to finished {@link GenerationRequest} and its instance as well.
*
- * @param generationRequest
+ * @param generationRequest the generation request
*/
private void cleanupFinishedGenerationRequest(GenerationRequest generationRequest) {
if (!controllerConfig.cleanup()) {
diff --git a/service/src/main/java/org/jboss/sbomer/service/feature/sbom/features/generator/rpm/controller/BrewRPMController.java b/service/src/main/java/org/jboss/sbomer/service/feature/sbom/features/generator/rpm/controller/BrewRPMController.java
index e1772b541..a8395ae0c 100644
--- a/service/src/main/java/org/jboss/sbomer/service/feature/sbom/features/generator/rpm/controller/BrewRPMController.java
+++ b/service/src/main/java/org/jboss/sbomer/service/feature/sbom/features/generator/rpm/controller/BrewRPMController.java
@@ -52,7 +52,7 @@
*
*
*
- * This reconciler acts only on resources marked with following labels (all of them must exist on the resource):
+ * This reconciler acts only on resources marked with the following labels (all of them must exist on the resource):
*
*
*
{@code app.kubernetes.io/part-of=sbomer}
@@ -101,9 +101,9 @@ protected UpdateControl updateRequest(
* Handles updates to {@link GenerationRequest} being in progress.
*
*
- * @param generationRequest
- * @param secondaryResources
- * @return
+ * @param generationRequest the generation request
+ * @param secondaryResources the secondary resources
+ * @return the update control for the generation request
*/
@Override
protected UpdateControl reconcileGenerating(
@@ -124,13 +124,13 @@ protected UpdateControl reconcileGenerating(
"Generation failed. Unable to find related TaskRun. See logs for more information.");
}
- // In case the TaskRun hasn't finished yet, wait for next update.
+ // In case the TaskRun hasn't finished yet, wait for the next update.
if (!isFinished(generateTaskRun)) {
return UpdateControl.noUpdate();
}
- // In case the Task Run is not successfull, fail thge generation
- if (!isSuccessful(generateTaskRun)) {
+ // In case the Task Run is not successful, fail the generation
+ if (!Boolean.TRUE.equals(isSuccessful(generateTaskRun))) {
log.error("Generation failed, the TaskRun returned failure");
return updateRequest(
@@ -150,13 +150,13 @@ protected UpdateControl reconcileGenerating(
try {
manifestPaths = FileUtils.findManifests(generationDir);
} catch (IOException e) {
- log.error("Unexpected IO exception ocurred while trying to find generated manifests", e);
+ log.error("Unexpected IO exception occurred while trying to find generated manifests", e);
return updateRequest(
generationRequest,
SbomGenerationStatus.FAILED,
GenerationResult.ERR_SYSTEM,
- "Generation succeded, but reading generated SBOMs failed due IO exception. See logs for more information.");
+ "Generation succeeded, but reading generated SBOMs failed due IO exception. See logs for more information.");
}
if (manifestPaths.isEmpty()) {
@@ -180,7 +180,7 @@ protected UpdateControl reconcileGenerating(
generationRequest,
SbomGenerationStatus.FAILED,
GenerationResult.ERR_SYSTEM,
- "Generation succeded, but reading generated manifests failed was not successful. See logs for more information.");
+ "Generation succeeded, but reading generated manifests failed was not successful. See logs for more information.");
}
List sboms;
@@ -200,7 +200,7 @@ protected UpdateControl reconcileGenerating(
}
try {
- performPost(sboms, generationRequest);
+ performPost(sboms);
} catch (ApplicationException e) {
return updateRequest(
generationRequest,
diff --git a/service/src/main/java/org/jboss/sbomer/service/feature/sbom/features/generator/rpm/controller/TaskRunBrewRPMGenerateDependentResource.java b/service/src/main/java/org/jboss/sbomer/service/feature/sbom/features/generator/rpm/controller/TaskRunBrewRPMGenerateDependentResource.java
index 571a51263..3ec0b6367 100644
--- a/service/src/main/java/org/jboss/sbomer/service/feature/sbom/features/generator/rpm/controller/TaskRunBrewRPMGenerateDependentResource.java
+++ b/service/src/main/java/org/jboss/sbomer/service/feature/sbom/features/generator/rpm/controller/TaskRunBrewRPMGenerateDependentResource.java
@@ -73,7 +73,7 @@ public class TaskRunBrewRPMGenerateDependentResource
}
public TaskRunBrewRPMGenerateDependentResource(Class resourceType) {
- super(TaskRun.class);
+ super(resourceType);
}
@Override
@@ -88,7 +88,7 @@ protected TaskRun desired(GenerationRequest generationRequest, Context processErrata(Message message) {
if (hasMessageId(event)) {
// Verify that there aren't already ACKED UMBMessages with the same msg id
- // There is an issue in our queues and same messages are processed multiple times, we want to avoid
+ // There is an issue in our queues and same messages are processed multiple times which we want to avoid
// generating manifests for the same event
String msgId = event.get(EVENT_KEY_UMB_MSG_ID).asText();
long alreadyGenerated = getAlreadyAckedUMBEventsFor(msgId);
if (alreadyGenerated > 0) {
log.warn(
- "Message with id '{}' has been already received and processed {} times!! Will not process it again, skipping it",
+ "Message with id '{}' has been already received and processed {} times for errata!! Will not process it again, skipping it",
msgId,
alreadyGenerated);
@@ -142,7 +142,7 @@ public CompletionStage processErrata(Message message) {
log.error("Unable to deserialize Errata message, this is unexpected", e);
return nackAndSave(message, requestEvent, e);
} catch (ApplicationException exc) {
- log.error("Received error while handing request '{}': {}", requestEvent.getId(), exc.getMessage());
+ log.error("Received error while handing errata request '{}': {}", requestEvent.getId(), exc.getMessage());
return nackAndSave(message, requestEvent, exc);
} catch (RuntimeException exc) {
log.error("Received error while handing request '{}'", requestEvent.getId(), exc);
@@ -177,7 +177,7 @@ public CompletionStage process(Message message) {
if (hasMessageId(event)) {
// Verify that there aren't already ACKED UMBMessages with the same msg id
- // There is an issue in our queues and same messages are processed multiple times, we want to avoid
+ // There is an issue in our queues and same messages are processed multiple times which we want to avoid
// generating manifests for the same event
String msgId = event.get(EVENT_KEY_UMB_MSG_ID).asText();
long alreadyGenerated = getAlreadyAckedUMBEventsFor(msgId);
@@ -222,7 +222,7 @@ private void identifyErrataEvent(IncomingAmqpMetadata metadata, ObjectNode event
private void identifyPncEvent(IncomingAmqpMetadata metadata, ObjectNode event) {
JsonObject properties = metadata.getProperties();
- log.debug("Message properties: {}", properties.toString());
+ log.debug("Message properties for PNC event: {}", properties.toString());
if (Objects.equals(properties.getString("type"), "BuildStateChange")) {
event.put(EVENT_KEY_UMB_MSG_TYPE, PncBuildRequestConfig.TYPE_NAME);
diff --git a/service/src/main/java/org/jboss/sbomer/service/feature/sbom/features/umb/consumer/PncNotificationHandler.java b/service/src/main/java/org/jboss/sbomer/service/feature/sbom/features/umb/consumer/PncNotificationHandler.java
index 80f2c8899..c62811f20 100644
--- a/service/src/main/java/org/jboss/sbomer/service/feature/sbom/features/umb/consumer/PncNotificationHandler.java
+++ b/service/src/main/java/org/jboss/sbomer/service/feature/sbom/features/umb/consumer/PncNotificationHandler.java
@@ -210,12 +210,13 @@ private void handle(PncDelAnalysisNotificationMessageBody messageBody, RequestEv
log.debug("Found {} pending requests for operation '{}'", pendingRequests.size(), messageBody.getOperationId());
- // Operation failed. Not good, propagate then the failure to our records as well.
+ // The operation failed. Not good, propagate then the failure to our records as well.
if (!isSuccessfullAnalysis(messageBody)) {
log.warn("Deliverable analyzer operation '{}' failed in PNC", messageBody.getOperationId());
- // We have some pending request for given operation. At this point there is no GenerationRequest created.
- // We need to update the pending request's status to failed.
+ // We have some pending request for given operation.
+ // At this point, there is no GenerationRequest created.
+ // We need to update the pending request's status to SbomGenerationStatus.FAILED.
if (!pendingRequests.isEmpty()) {
String lastId = pendingRequests.get(0).getId();
@@ -240,7 +241,7 @@ private void handle(PncDelAnalysisNotificationMessageBody messageBody, RequestEv
SbomGenerationRequest pendingRequest = null;
- // If there are no pending generation requests create a new ConfigMap
+ // If there are no pending generation requests, create a new ConfigMap
if (!pendingRequests.isEmpty()) {
// Get the oldest pending generation request and create a new ConfigMap with the existing id
pendingRequest = pendingRequests.get(0);
@@ -300,7 +301,7 @@ private GenerationRequest createDelAnalysisGenerationRequest(
PncDelAnalysisNotificationMessageBody messageBody,
SbomGenerationRequest pendingRequest) {
- GenerationRequest generationRequest = null;
+ GenerationRequest generationRequest;
if (pendingRequest == null) {
log.info(
"No pending requests found for operation {}, creating a new one from the UMB message body!",
diff --git a/service/src/main/java/org/jboss/sbomer/service/feature/sbom/features/umb/producer/AmqpMessageProducer.java b/service/src/main/java/org/jboss/sbomer/service/feature/sbom/features/umb/producer/AmqpMessageProducer.java
index bd15d6239..d3c74ec9f 100644
--- a/service/src/main/java/org/jboss/sbomer/service/feature/sbom/features/umb/producer/AmqpMessageProducer.java
+++ b/service/src/main/java/org/jboss/sbomer/service/feature/sbom/features/umb/producer/AmqpMessageProducer.java
@@ -80,7 +80,7 @@ public void notify(GenerationFinishedMessageBody msg) {
return;
}
- String data = null;
+ String data;
try {
data = ObjectMapperProvider.json().writeValueAsString(msg);
diff --git a/service/src/main/java/org/jboss/sbomer/service/feature/sbom/features/umb/producer/GenerationFinishedMessageBodyValidator.java b/service/src/main/java/org/jboss/sbomer/service/feature/sbom/features/umb/producer/GenerationFinishedMessageBodyValidator.java
index 0b290cc95..2594e4932 100644
--- a/service/src/main/java/org/jboss/sbomer/service/feature/sbom/features/umb/producer/GenerationFinishedMessageBodyValidator.java
+++ b/service/src/main/java/org/jboss/sbomer/service/feature/sbom/features/umb/producer/GenerationFinishedMessageBodyValidator.java
@@ -20,6 +20,7 @@
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
+import java.util.Objects;
import org.jboss.sbomer.core.SchemaValidator;
import org.jboss.sbomer.core.SchemaValidator.ValidationResult;
@@ -31,10 +32,6 @@
@ApplicationScoped
public class GenerationFinishedMessageBodyValidator implements Validator {
-
- public GenerationFinishedMessageBodyValidator() {
- }
-
@Override
public ValidationResult validate(GenerationFinishedMessageBody messageBody) {
if (messageBody == null) {
@@ -44,12 +41,11 @@ public ValidationResult validate(GenerationFinishedMessageBody messageBody) {
String schema;
try (InputStream is = getClass().getClassLoader().getResourceAsStream("schemas/message-success-schema.json")) {
- schema = new String(is.readAllBytes(), StandardCharsets.UTF_8);
+ schema = new String(Objects.requireNonNull(is).readAllBytes(), StandardCharsets.UTF_8);
} catch (IOException e) {
throw new ApplicationException("Could not read the configuration file schema", e);
}
return SchemaValidator.validate(schema, messageBody.toJson());
}
-
}
diff --git a/service/src/main/java/org/jboss/sbomer/service/feature/sbom/features/umb/producer/NotificationService.java b/service/src/main/java/org/jboss/sbomer/service/feature/sbom/features/umb/producer/NotificationService.java
index 97044e245..a721754cf 100644
--- a/service/src/main/java/org/jboss/sbomer/service/feature/sbom/features/umb/producer/NotificationService.java
+++ b/service/src/main/java/org/jboss/sbomer/service/feature/sbom/features/umb/producer/NotificationService.java
@@ -116,7 +116,7 @@ public void notifyCompleted(List
*
*
- * Following labels are expect to be present on the {@link ConfigMap} resource in order for it to be used as
+ * Following labels are expected to be present on the {@link ConfigMap} resource in order for it to be used as
* {@link GenerationRequest}.
*
*
{@code app.kubernetes.io/part-of=sbomer}
@@ -54,7 +54,7 @@
*
*
*
- * Additionally following labels can be added:
+ * Additionally, the following labels can be added:
*
*
*
{@code sbomer.jboss.org/sbom-build-id} -- the identifier of the build for which the generation is triggered