From 3f6b72c8bb0e73f7dc8ec30fef7528e7abf5d6b2 Mon Sep 17 00:00:00 2001 From: David Walluck Date: Fri, 14 Feb 2025 20:37:20 -0500 Subject: [PATCH] style: Fix more sonar issues with core --- core/pom.xml | 1 - .../core/config/ConfigSchemaValidator.java | 7 +- .../core/config/DefaultProcessingConfig.java | 2 +- .../core/config/SbomerConfigProvider.java | 12 ++-- .../config/SbomerConfigSourceProvider.java | 5 +- .../request/ErrataAdvisoryRequestConfig.java | 12 ++-- .../config/request/ImageRequestConfig.java | 12 ++-- .../request/PncAnalysisRequestConfig.java | 13 ++-- .../config/request/PncBuildRequestConfig.java | 11 ++-- .../request/PncOperationRequestConfig.java | 12 ++-- .../core/config/request/RequestConfig.java | 5 +- .../core/errors/ApplicationException.java | 16 ++--- .../sbomer/core/features/sbom/Constants.java | 2 +- .../core/features/sbom/config/Config.java | 6 +- .../features/sbom/config/SyftImageConfig.java | 2 +- .../provider/BuildFinderConfigProvider.java | 9 +-- .../core/features/sbom/utils/FileUtils.java | 7 +- .../features/sbom/utils/PurlRebuilder.java | 4 ++ .../features/sbom/utils/PurlSanitizer.java | 19 ++++-- .../core/features/sbom/utils/SbomUtils.java | 52 +++++++-------- .../core/features/sbom/utils/UrlUtils.java | 6 +- .../commandline/CommandLineParserUtil.java | 2 +- .../maven/MavenCommandLineParser.java | 20 +++--- .../maven/MavenCommandOptions.java | 64 ++++++++----------- .../org/jboss/sbomer/core/pnc/PncService.java | 3 +- .../jboss/sbomer/core/test/TestResources.java | 6 +- .../jboss/sbomer/core/utils/h2/JsonUtils.java | 5 +- .../sbomer/core/test/unit/SbomUtilsTest.java | 2 +- .../config/ConfigSchemaValidatorTest.java | 4 +- ...mmentAdvisoryOnRelevantEventsListener.java | 6 +- ...ReleaseStandardAdvisoryEventsListener.java | 4 +- 31 files changed, 171 insertions(+), 160 deletions(-) diff --git a/core/pom.xml b/core/pom.xml index 88a20364d..fceb65c82 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -32,7 +32,6 @@ ../pom.xml - org.jboss.sbomer 1.0.0-SNAPSHOT sbomer-core diff --git a/core/src/main/java/org/jboss/sbomer/core/config/ConfigSchemaValidator.java b/core/src/main/java/org/jboss/sbomer/core/config/ConfigSchemaValidator.java index 92790f957..69da0165d 100644 --- a/core/src/main/java/org/jboss/sbomer/core/config/ConfigSchemaValidator.java +++ b/core/src/main/java/org/jboss/sbomer/core/config/ConfigSchemaValidator.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; @@ -47,10 +48,12 @@ public ValidationResult validate(Config config) { } String schemaFile = GenerationRequestType.schemaFile(config.getClass()); + String name = "schemas/" + schemaFile; String schema; - try (InputStream is = SchemaValidator.class.getClassLoader().getResourceAsStream("schemas/" + schemaFile)) { - schema = new String(is.readAllBytes(), StandardCharsets.UTF_8); + try (InputStream in = SchemaValidator.class.getClassLoader().getResourceAsStream(name)) { + Objects.requireNonNull(in, "Resource " + name + " not found"); + schema = new String(in.readAllBytes(), StandardCharsets.UTF_8); } catch (IOException e) { throw new ApplicationException("Could not read the configuration file schema", e); } diff --git a/core/src/main/java/org/jboss/sbomer/core/config/DefaultProcessingConfig.java b/core/src/main/java/org/jboss/sbomer/core/config/DefaultProcessingConfig.java index 0d0a185c6..0ca07bfb3 100644 --- a/core/src/main/java/org/jboss/sbomer/core/config/DefaultProcessingConfig.java +++ b/core/src/main/java/org/jboss/sbomer/core/config/DefaultProcessingConfig.java @@ -53,7 +53,7 @@ interface ProcessorConfig { /** * List of configured default processors. * - * @return + * @return the list of default processors */ List defaultProcessors(); diff --git a/core/src/main/java/org/jboss/sbomer/core/config/SbomerConfigProvider.java b/core/src/main/java/org/jboss/sbomer/core/config/SbomerConfigProvider.java index 6ef6c086a..7c39dc234 100644 --- a/core/src/main/java/org/jboss/sbomer/core/config/SbomerConfigProvider.java +++ b/core/src/main/java/org/jboss/sbomer/core/config/SbomerConfigProvider.java @@ -31,10 +31,10 @@ import lombok.Getter; import lombok.extern.slf4j.Slf4j; +@Getter @Slf4j public class SbomerConfigProvider { - @Getter final DefaultGenerationConfig defaultGenerationConfig; private static SbomerConfigProvider instance; @@ -69,7 +69,7 @@ public void adjust(PncBuildConfig config) { config.getProducts().forEach(product -> { // Adjusting generator configuration. This is the only thing we can adjust, - // because processor configuration is specific to the build and product release. + // because the processor configuration is specific to the build and product release. adjustGenerator(product); if (!product.hasDefaultProcessor()) { @@ -88,7 +88,7 @@ public void adjust(PncBuildConfig config) { public void adjust(OperationConfig config) { log.debug("Adjusting operation configuration..."); - // If we have not specified any products (for example when provided an empty config) + // If we have not specified any products (for example, when provided an empty config) if (config.getProduct() == null) { config.setProduct(ProductConfig.builder().build()); } @@ -97,7 +97,9 @@ public void adjust(OperationConfig config) { // Generator configuration was not provided, will use defaults if (generatorConfig == null) { - log.debug("No generator provided, will use defaults: '{}'", GeneratorType.CYCLONEDX_OPERATION); + log.debug( + "No generator provided for adjusting, will use defaults: '{}'", + GeneratorType.CYCLONEDX_OPERATION); generatorConfig = GeneratorConfig.builder().type(GeneratorType.CYCLONEDX_OPERATION).build(); config.getProduct().setGenerator(generatorConfig); } @@ -113,7 +115,7 @@ private void adjustGenerator(ProductConfig product) { // Generator configuration was not provided, will use defaults if (generatorConfig == null) { - log.debug("No generator provided, will use defaults: '{}'", defaultGeneratorConfig); + log.debug("No generator provided for adjusting generator, will use defaults: '{}'", defaultGeneratorConfig); product.setGenerator(defaultGeneratorConfig); } else { diff --git a/core/src/main/java/org/jboss/sbomer/core/config/SbomerConfigSourceProvider.java b/core/src/main/java/org/jboss/sbomer/core/config/SbomerConfigSourceProvider.java index dfae3defb..c42f151e9 100644 --- a/core/src/main/java/org/jboss/sbomer/core/config/SbomerConfigSourceProvider.java +++ b/core/src/main/java/org/jboss/sbomer/core/config/SbomerConfigSourceProvider.java @@ -18,7 +18,6 @@ package org.jboss.sbomer.core.config; import java.util.ArrayList; -import java.util.List; import org.eclipse.microprofile.config.spi.ConfigSource; @@ -27,8 +26,6 @@ class SbomerConfigSourceProvider extends YamlConfigSourceProvider { @Override public Iterable getConfigSources(ClassLoader classLoader) { - final List sources = new ArrayList<>( - loadConfigSources("META-INF/sbomer-config.yaml", 110, classLoader)); - return sources; + return new ArrayList<>(loadConfigSources("META-INF/sbomer-config.yaml", 110, classLoader)); } } diff --git a/core/src/main/java/org/jboss/sbomer/core/config/request/ErrataAdvisoryRequestConfig.java b/core/src/main/java/org/jboss/sbomer/core/config/request/ErrataAdvisoryRequestConfig.java index 256cd6822..71d971b96 100644 --- a/core/src/main/java/org/jboss/sbomer/core/config/request/ErrataAdvisoryRequestConfig.java +++ b/core/src/main/java/org/jboss/sbomer/core/config/request/ErrataAdvisoryRequestConfig.java @@ -36,17 +36,17 @@ @JsonInclude(JsonInclude.Include.NON_NULL) @JsonTypeName(ErrataAdvisoryRequestConfig.TYPE_NAME) public class ErrataAdvisoryRequestConfig extends RequestConfig { - public static final String TYPE_NAME = "errata-advisory"; - public static final String IDENTIFIER_KEY = "advisoryId"; - { - this.type = TYPE_NAME; - } + public static final String IDENTIFIER_KEY = "advisoryId"; /** * Advisory identifier (number or name). */ - String advisoryId; + private String advisoryId; + @Override + public String getType() { + return TYPE_NAME; + } } diff --git a/core/src/main/java/org/jboss/sbomer/core/config/request/ImageRequestConfig.java b/core/src/main/java/org/jboss/sbomer/core/config/request/ImageRequestConfig.java index c20071ea6..20103e6a8 100644 --- a/core/src/main/java/org/jboss/sbomer/core/config/request/ImageRequestConfig.java +++ b/core/src/main/java/org/jboss/sbomer/core/config/request/ImageRequestConfig.java @@ -38,14 +38,14 @@ @JsonInclude(JsonInclude.Include.NON_NULL) @JsonTypeName(ImageRequestConfig.TYPE_NAME) public class ImageRequestConfig extends RequestConfig { - public static final String TYPE_NAME = "image"; - public static final String IDENTIFIER_KEY = "image"; - { - this.type = TYPE_NAME; - } + public static final String IDENTIFIER_KEY = "image"; - String image; + private String image; + @Override + public String getType() { + return TYPE_NAME; + } } diff --git a/core/src/main/java/org/jboss/sbomer/core/config/request/PncAnalysisRequestConfig.java b/core/src/main/java/org/jboss/sbomer/core/config/request/PncAnalysisRequestConfig.java index ebba81f89..ff5968b2f 100644 --- a/core/src/main/java/org/jboss/sbomer/core/config/request/PncAnalysisRequestConfig.java +++ b/core/src/main/java/org/jboss/sbomer/core/config/request/PncAnalysisRequestConfig.java @@ -40,15 +40,16 @@ @JsonInclude(JsonInclude.Include.NON_NULL) @JsonTypeName(PncAnalysisRequestConfig.TYPE_NAME) public class PncAnalysisRequestConfig extends RequestConfig { - public static final String TYPE_NAME = "pnc-analysis"; + public static final String IDENTIFIER_KEY = "milestoneId"; - { - this.type = TYPE_NAME; - } + private String milestoneId; - String milestoneId; - List urls; + private List urls; + @Override + public String getType() { + return TYPE_NAME; + } } diff --git a/core/src/main/java/org/jboss/sbomer/core/config/request/PncBuildRequestConfig.java b/core/src/main/java/org/jboss/sbomer/core/config/request/PncBuildRequestConfig.java index a9d81e929..9050b25c3 100644 --- a/core/src/main/java/org/jboss/sbomer/core/config/request/PncBuildRequestConfig.java +++ b/core/src/main/java/org/jboss/sbomer/core/config/request/PncBuildRequestConfig.java @@ -38,13 +38,14 @@ @JsonInclude(JsonInclude.Include.NON_NULL) @JsonTypeName(PncBuildRequestConfig.TYPE_NAME) public class PncBuildRequestConfig extends RequestConfig { - public static final String TYPE_NAME = "pnc-build"; + public static final String IDENTIFIER_KEY = "buildId"; - { - this.type = TYPE_NAME; - } + private String buildId; - String buildId; + @Override + public String getType() { + return TYPE_NAME; + } } diff --git a/core/src/main/java/org/jboss/sbomer/core/config/request/PncOperationRequestConfig.java b/core/src/main/java/org/jboss/sbomer/core/config/request/PncOperationRequestConfig.java index 4c0f6d291..3ac228133 100644 --- a/core/src/main/java/org/jboss/sbomer/core/config/request/PncOperationRequestConfig.java +++ b/core/src/main/java/org/jboss/sbomer/core/config/request/PncOperationRequestConfig.java @@ -38,14 +38,14 @@ @JsonInclude(JsonInclude.Include.NON_NULL) @JsonTypeName(PncOperationRequestConfig.TYPE_NAME) public class PncOperationRequestConfig extends RequestConfig { - public static final String TYPE_NAME = "pnc-operation"; - public static final String IDENTIFIER_KEY = "operationId"; - { - this.type = TYPE_NAME; - } + public static final String IDENTIFIER_KEY = "operationId"; - String operationId; + private String operationId; + @Override + public String getType() { + return TYPE_NAME; + } } diff --git a/core/src/main/java/org/jboss/sbomer/core/config/request/RequestConfig.java b/core/src/main/java/org/jboss/sbomer/core/config/request/RequestConfig.java index 34fa5f93d..bd0c6e9b6 100644 --- a/core/src/main/java/org/jboss/sbomer/core/config/request/RequestConfig.java +++ b/core/src/main/java/org/jboss/sbomer/core/config/request/RequestConfig.java @@ -47,7 +47,7 @@ }) public abstract class RequestConfig { /** - * The API version of the configuration file. In case of breaking changes this value will be used to detect the + * The API version of the configuration file. In case of breaking changes, this value will be used to detect the * correct (de)serializer. */ @Builder.Default @@ -55,6 +55,8 @@ public abstract class RequestConfig { String type; + public abstract String getType(); + public String toJson() { try { return ObjectMapperProvider.json().writerWithDefaultPrettyPrinter().writeValueAsString(this); @@ -75,5 +77,4 @@ public static T fromString(String value, Class claz return null; } } - } diff --git a/core/src/main/java/org/jboss/sbomer/core/errors/ApplicationException.java b/core/src/main/java/org/jboss/sbomer/core/errors/ApplicationException.java index 6012cafdb..6baabf814 100644 --- a/core/src/main/java/org/jboss/sbomer/core/errors/ApplicationException.java +++ b/core/src/main/java/org/jboss/sbomer/core/errors/ApplicationException.java @@ -20,21 +20,17 @@ import org.slf4j.helpers.MessageFormatter; public class ApplicationException extends RuntimeException { - private final Object[] params; - - private String formattedMessage; + private final String message; public ApplicationException(String msg, Object... params) { super(msg, MessageFormatter.getThrowableCandidate(params)); - this.params = params; + this.message = (params != null && params.length != 0) + ? MessageFormatter.arrayFormat(super.getMessage(), params).getMessage() + : super.getMessage(); } @Override - public synchronized String getMessage() { - if (formattedMessage == null) { - formattedMessage = MessageFormatter.arrayFormat(super.getMessage(), params).getMessage(); - } - return formattedMessage; + public String getMessage() { + return message; } - } diff --git a/core/src/main/java/org/jboss/sbomer/core/features/sbom/Constants.java b/core/src/main/java/org/jboss/sbomer/core/features/sbom/Constants.java index c630e41dd..e27da4a9f 100644 --- a/core/src/main/java/org/jboss/sbomer/core/features/sbom/Constants.java +++ b/core/src/main/java/org/jboss/sbomer/core/features/sbom/Constants.java @@ -81,7 +81,7 @@ private Constants() { public static final String TEKTON_LABEL_VALUE_APP_PART_OF = "sbomer"; /** - * The suffix which is used in a Task Run name to identify the number of retry attempt + * The suffix which is used in a Task Run name to identify the number of retry attempts */ public static final String TEKTON_TASK_RUN_NAME_SUFFIX_RETRY_ATTEMPT = "retry"; diff --git a/core/src/main/java/org/jboss/sbomer/core/features/sbom/config/Config.java b/core/src/main/java/org/jboss/sbomer/core/features/sbom/config/Config.java index 335fd523b..40f3db50f 100644 --- a/core/src/main/java/org/jboss/sbomer/core/features/sbom/config/Config.java +++ b/core/src/main/java/org/jboss/sbomer/core/features/sbom/config/Config.java @@ -55,14 +55,14 @@ public abstract class Config { /** - * The API version of the configuration file. In case of breaking changes this value will be used to detect the + * The API version of the configuration file. In case of breaking changes, this value will be used to detect the * correct (de)serializer. */ @Builder.Default String apiVersion = "sbomer.jboss.org/v1alpha1"; /** - * Checks whether current object is an empty one. + * Checks whether the current object is empty. * * @return {@code true} if the object is empty, {@code false} otherwise. */ @@ -84,7 +84,7 @@ protected List processCommand() { /** *

* Returns a command that represents the parameters that should be passed to the process command. This basically - * translates all the configured processors and it's parameters into a string that can be executed via CLI. + * translates all the configured processors and its parameters into a string that can be executed via CLI. *

* *

diff --git a/core/src/main/java/org/jboss/sbomer/core/features/sbom/config/SyftImageConfig.java b/core/src/main/java/org/jboss/sbomer/core/features/sbom/config/SyftImageConfig.java index 110e22564..5d30ca94d 100644 --- a/core/src/main/java/org/jboss/sbomer/core/features/sbom/config/SyftImageConfig.java +++ b/core/src/main/java/org/jboss/sbomer/core/features/sbom/config/SyftImageConfig.java @@ -84,7 +84,7 @@ protected List processCommand() { DefaultProcessorConfig defaultProcessorConfig = new DefaultProcessorConfig(); // If the default processor is not there, add it. - // This ensures that even after we initialize the object, for example after deserialization, + // This ensures that even after we initialize the object, for example, after deserialization, // we will have the default processor added, so that the correct command can be instantiated. if (!processors.contains(defaultProcessorConfig)) { processors.add(0, defaultProcessorConfig); diff --git a/core/src/main/java/org/jboss/sbomer/core/features/sbom/provider/BuildFinderConfigProvider.java b/core/src/main/java/org/jboss/sbomer/core/features/sbom/provider/BuildFinderConfigProvider.java index b4e2835c1..bb2649d04 100644 --- a/core/src/main/java/org/jboss/sbomer/core/features/sbom/provider/BuildFinderConfigProvider.java +++ b/core/src/main/java/org/jboss/sbomer/core/features/sbom/provider/BuildFinderConfigProvider.java @@ -91,7 +91,8 @@ public BuildFinderConfigProvider() throws IOException { // The checksum-only option specifies whether to skip the Koji build lookup stage and only checksum the files in // the input. config.setChecksumOnly(false); - // The checksum-type option specifies the checksum type to use for lookups. Note that at this time Koji can only + // The checksum-type option specifies the checksum type to use for lookups. Note that at this time, Koji can + // only // support a single checksum type in its database, md5, even though the Koji API currently provides additional // support for sha256 and sha512 checksum types. config.setChecksumTypes(DEFAULT_CHECKSUM_TYPES); @@ -119,7 +120,7 @@ public BuildFinderConfigProvider() throws IOException { } /** - * Ensures that the content of temporary directory is removed after we shut down the application. + * Ensures that the content of the temporary directory is removed after we shut down the application. * * @param event the shutdown event */ @@ -128,7 +129,7 @@ void cleanup(@Observes ShutdownEvent event) { } /** - * Override koji hub url in the config if 'sbomer.koji.hub.url' defined in a system property, env variable, or in + * Override koji hub url in the config if 'sbomer.koji.hub.url' is defined in a system property, env variable, or in * application.properties. * * @param config config file to potentially override its kojiHubUrl @@ -158,7 +159,7 @@ private void setKojiHubURL(BuildConfig config) throws IOException { } /** - * Override koji web url in the config if 'sbomer.koji.web.url' defined in a system property, env variable, or in + * Override koji web url in the config if 'sbomer.koji.web.url' is defined in a system property, env variable, or in * application.properties. Otherwise, use kojiHubUrl to generate the kojiWebUrl. * * @param config config file to potentially override its kojiWebUrl diff --git a/core/src/main/java/org/jboss/sbomer/core/features/sbom/utils/FileUtils.java b/core/src/main/java/org/jboss/sbomer/core/features/sbom/utils/FileUtils.java index 4509e326c..730b811a6 100644 --- a/core/src/main/java/org/jboss/sbomer/core/features/sbom/utils/FileUtils.java +++ b/core/src/main/java/org/jboss/sbomer/core/features/sbom/utils/FileUtils.java @@ -18,15 +18,12 @@ package org.jboss.sbomer.core.features.sbom.utils; import java.io.IOException; -import java.nio.file.FileSystems; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.PathMatcher; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.List; -import java.util.stream.Collectors; import java.util.stream.Stream; import lombok.extern.slf4j.Slf4j; @@ -80,7 +77,9 @@ public static List findManifests(Path directory) throws IOException { List manifestPaths = paths.filter(path -> MANIFEST_FILENAME.equals(path.getFileName().toString())) .filter(Files::isRegularFile) .sorted() - .peek(path -> log.info("Found manifest at path '{}'", path.toAbsolutePath())) + .peek(path -> log.info("Found manifest at path '{}'", path.toAbsolutePath())) // NOSONAR: peek() is + // used just for + // logging .toList(); log.info("Found {} generated manifests", manifestPaths.size()); diff --git a/core/src/main/java/org/jboss/sbomer/core/features/sbom/utils/PurlRebuilder.java b/core/src/main/java/org/jboss/sbomer/core/features/sbom/utils/PurlRebuilder.java index d2df0ae36..62dfaeeae 100644 --- a/core/src/main/java/org/jboss/sbomer/core/features/sbom/utils/PurlRebuilder.java +++ b/core/src/main/java/org/jboss/sbomer/core/features/sbom/utils/PurlRebuilder.java @@ -106,6 +106,10 @@ public class PurlRebuilder { SYFT_PACKAGE_2_PURL_TYPE_MAP.put(SYFT_WORDPRESSPLUGINPKG, "wordpress-plugin"); } + private PurlRebuilder() { + throw new IllegalStateException("This is a utility class that should not be instantiated"); + } + /** * Given a component, tries to create a valid purl using the Syft information (if available) and the component * properties diff --git a/core/src/main/java/org/jboss/sbomer/core/features/sbom/utils/PurlSanitizer.java b/core/src/main/java/org/jboss/sbomer/core/features/sbom/utils/PurlSanitizer.java index 577ad01a3..ebac2fe22 100644 --- a/core/src/main/java/org/jboss/sbomer/core/features/sbom/utils/PurlSanitizer.java +++ b/core/src/main/java/org/jboss/sbomer/core/features/sbom/utils/PurlSanitizer.java @@ -31,6 +31,10 @@ public class PurlSanitizer { private static final String NAME_VERSION_QKEY_QVALUE = "[^a-zA-Z0-9.+\\-_]"; private static final String TYPE_INVALID_CHARS = "[^a-zA-Z0-9.+-]"; + private PurlSanitizer() { + throw new IllegalStateException("This is a utility class that should not be instantiated"); + } + /** * Sanitize a given PURL string by replacing invalid characters in each component. * @@ -150,9 +154,13 @@ public static String sanitizeSubpath(String subpath) { return String.join("/", segments); } - public static TreeMap sanitizeQualifiers(TreeMap qualifiers) { - if (qualifiers == null) - return null; + public static TreeMap sanitizeQualifiers(TreeMap qualifiers) { // NOSONAR: This + // should be Map, but + // PackageURL + // requires TreeMap + if (qualifiers == null) { + return null; // NOSONAR: Should return an empty map, but PackageURL expects null + } TreeMap sanitized = new TreeMap<>(); for (Map.Entry entry : qualifiers.entrySet()) { String key = entry.getKey().replaceAll(NAME_VERSION_QKEY_QVALUE, ""); @@ -163,8 +171,9 @@ public static TreeMap sanitizeQualifiers(TreeMap } private static TreeMap parseQualifiers(String qualifiersPart) { - if (qualifiersPart == null || qualifiersPart.isEmpty()) - return null; + if (qualifiersPart == null || qualifiersPart.isEmpty()) { + return null; // NOSONAR: Should return an empty map, but PackageURL expects null + } TreeMap qualifiers = new TreeMap<>(); String[] pairs = qualifiersPart.split("&"); for (String pair : pairs) { 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 7f23bd128..bd2f4f0ac 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 @@ -227,7 +227,8 @@ public static Component setPncBuildMetadata(Component component, Build pncBuild, // If the SCM repository is not internal and a commitID was computed, add the pedigree. if (!Strings.isEmpty(pncBuild.getScmRepository().getExternalUrl()) - && pncBuild.getScmBuildConfigRevisionInternal() != null && !pncBuild.getScmBuildConfigRevisionInternal() + && pncBuild.getScmBuildConfigRevisionInternal() != null + && !Boolean.TRUE.equals(pncBuild.getScmBuildConfigRevisionInternal()) && pncBuild.getScmBuildConfigRevision() != null) { addPedigreeCommit( @@ -382,8 +383,8 @@ public static List validate(JsonNode jsonNode) throws IOExceptio schemaVersion()); } - public static Tool createTool(String version) { - Tool tool = new Tool(); + public static Tool createTool(String version) { // NOSONAR: Tool is deprecated, but this is for legacy support + Tool tool = new Tool(); // NOSONAR: Tool is deprecated, but this is for legacy support tool.setName(SBOMER_NAME); tool.setVendor(PUBLISHER); if (version != null) { @@ -404,7 +405,7 @@ public static Tool createTool(String version) { *

* *

- * In some cases this will lead to duplicate components and dependencies. This process ensures that there are no + * In some cases, this will lead to duplicate components and dependencies. This process ensures that there are no * duplicates as well. *

* @@ -448,18 +449,17 @@ public static boolean updatePurl(Component component, String oldPurl, String new } /** - * Updates the bom-ref for the given component, and update the refs in the dependencies hierarchy, looking for - * nested dependencies and provides. + * Updates the bom-ref for the given component, and update the refs in the dependency hierarchy, looking for nested + * dependencies and provides. * - * @param component - * @param newRef - * @return + * @param component the component to update the bom-ref for + * @param newRef the new reference */ public static void updateBomRef(Bom bom, Component component, String oldRef, String newRef) { - // Update the BOM reference of the component + // Update the BOM reference of the component. // There might be cases (mainly for components detected by Syft) where the same purl is duplicated across - // components (which have different bom-refs), so we need to check if there are not already dependencies having - // the bom-ref equals to the new purl before updating it, otherwise we would have bom validation errors. + // components (which have different bom-refs). So, we need to check if there are not already dependencies having + // the bom-ref equals to the new purl before updating it. Otherwise, we would have bom validation errors. if (oldRef.equals(component.getBomRef()) && !bom.getDependencies().stream().map(Dependency::getRef).toList().contains(newRef)) { @@ -467,12 +467,12 @@ public static void updateBomRef(Bom bom, Component component, String oldRef, Str // Recursively update the dependencies in the BOM if (bom.getDependencies() != null) { - Set updatedDependencies = new TreeSet<>(); + List updatedDependencies = new ArrayList<>(bom.getDependencies().size()); for (Dependency dependency : bom.getDependencies()) { updateDependencyRef(dependency, oldRef, newRef); updatedDependencies.add(dependency); } - bom.setDependencies(new ArrayList<>(updatedDependencies)); + bom.setDependencies(updatedDependencies); } } } @@ -520,11 +520,6 @@ public static Dependency createDependency(String ref) { return new Dependency(ref); } - public static boolean hasProperty(Component component, String property) { - return component.getProperties() != null - && component.getProperties().stream().anyMatch(c -> c.getName().equalsIgnoreCase(property)); - } - public static boolean hasHash(Component component, Algorithm algorithm) { return getHash(component, algorithm).isPresent(); } @@ -624,6 +619,13 @@ public static Optional findComponentWithPurl(String purl, Bom bom) { return bom.getComponents().stream().filter(c -> c.getPurl().equals(purl)).findFirst(); } + public static boolean hasProperty(Component component, String property) { + return component.getProperties() != null + && component.getProperties().stream().anyMatch(c -> c.getName().equalsIgnoreCase(property)); + } + + // FIXME: hasProperty() uses equalsIgnoreCase(), but findPropertyWithNameInComponent() uses equals() + // TODO: Optimize so that addPropertyIfMissing() is not filtering twice by using, e.g., Optional.orElse() public static Optional findPropertyWithNameInComponent(String propertyName, Component component) { if (component == null) { return Optional.empty(); @@ -800,10 +802,10 @@ public static Bom fromJsonNode(JsonNode jsonNode) { } } - public static String[] computeNVRFromContainerManifest(JsonNode jsonNode) { + public static List computeNVRFromContainerManifest(JsonNode jsonNode) { Bom bom = fromJsonNode(jsonNode); if (bom == null || bom.getComponents() == null || bom.getComponents().isEmpty()) { - return null; + return List.of(); } Component mainComponent = bom.getComponents().get(0); @@ -813,10 +815,10 @@ public static String[] computeNVRFromContainerManifest(JsonNode jsonNode) { Property r = findPropertyWithNameInComponent("sbomer:image:labels:release", mainComponent).orElse(null); if (n != null && v != null && r != null) { - return new String[] { n.getValue(), v.getValue(), r.getValue() }; + return List.of(n.getValue(), v.getValue(), r.getValue()); } - return null; + return List.of(); } public static void setEvidenceIdentities(Component c, Set concludedValues, Field field) { @@ -1128,11 +1130,11 @@ private static String rebuildPurl(Component component) { /** * Creates a new purl with the same name, namespace, subpath, type, version and qualifiers and add the specified * qualifier. If "redHatComponentsOnly" is true, add the qualifiers only if the component has a Red Hat version. - * Finally rebuilds the purl to make sure it is valid and qualifiers are properly sorted. + * Finally, rebuild the purl to make sure it is valid and qualifiers are properly sorted. * * @param component the input component which has the purl to modify * @param qualifiers the Map with the qualifiers key-value - * @param redHatComponentsOnly boolean, true if the qualifiers should be added only to components with Red Hat + * @param redHatComponentsOnly boolean, true if the qualifiers should be added only to components with the Red Hat * version * @return The new validated purl as string. */ diff --git a/core/src/main/java/org/jboss/sbomer/core/features/sbom/utils/UrlUtils.java b/core/src/main/java/org/jboss/sbomer/core/features/sbom/utils/UrlUtils.java index 84d823ad1..36a09d7c6 100644 --- a/core/src/main/java/org/jboss/sbomer/core/features/sbom/utils/UrlUtils.java +++ b/core/src/main/java/org/jboss/sbomer/core/features/sbom/utils/UrlUtils.java @@ -43,8 +43,8 @@ public static String urldecode(String value) { } /** - * Removes from the provided purl the qualifiers which are present (if any) in the allowList. If the purl does not - * contain any qualifier which needs to be removed, the original purl is returned, otherwise a new purl is built and + * Removes from the provided purl the qualifiers that are present (if any) in the allowList. If the purl does not + * contain any qualifier that needs to be removed, the original purl is returned, otherwise a new purl is built and * returned. * * @param purl the purl from which the qualifiers should be removed @@ -65,7 +65,7 @@ public static String removeAllowedQualifiersFromPurl(String purl, List a return purl; } - // Qualifiers are not modifiable, we need to recreate the purl with new map of qualifiers + // Qualifiers are not modifiable, we need to recreate the purl with the new map of qualifiers TreeMap modifiableQualifiers = new TreeMap<>(qualifiers); allowList.forEach(modifiableQualifiers.keySet()::remove); diff --git a/core/src/main/java/org/jboss/sbomer/core/features/sbom/utils/commandline/CommandLineParserUtil.java b/core/src/main/java/org/jboss/sbomer/core/features/sbom/utils/commandline/CommandLineParserUtil.java index 28a61bdcc..e9a6664aa 100644 --- a/core/src/main/java/org/jboss/sbomer/core/features/sbom/utils/commandline/CommandLineParserUtil.java +++ b/core/src/main/java/org/jboss/sbomer/core/features/sbom/utils/commandline/CommandLineParserUtil.java @@ -54,7 +54,7 @@ public static String getLaunderedCommandScript(Build build) { } buildCmdOptions += "gradle"; - // Looks like we need to override the final version as it might not be picked up in the CycloneDX + // It looks like we need to override the final version as it might not be picked up in the CycloneDX // generation, which would be overridden by the gradle.properties. The BREW_BUILD_VERSION attribute contains // the version we need. Optional versionOverride = getVersionFromBuildAttributes(build); diff --git a/core/src/main/java/org/jboss/sbomer/core/features/sbom/utils/commandline/maven/MavenCommandLineParser.java b/core/src/main/java/org/jboss/sbomer/core/features/sbom/utils/commandline/maven/MavenCommandLineParser.java index f8ecc439f..366eced59 100644 --- a/core/src/main/java/org/jboss/sbomer/core/features/sbom/utils/commandline/maven/MavenCommandLineParser.java +++ b/core/src/main/java/org/jboss/sbomer/core/features/sbom/utils/commandline/maven/MavenCommandLineParser.java @@ -87,17 +87,17 @@ private MavenCommandLineParser() { } private Options createOptions() { - Options options = new Options(); + Options localOptions = new Options(); - addIgnorableOptions(options); - addIneffectiveOptions(options); - addNoArgsOptions(options); - addSystemPropertyOptions(options); - addProfilesOptions(options); - addProjectsOptions(options); - addAlternativePomOption(options); + addIgnorableOptions(localOptions); + addIneffectiveOptions(localOptions); + addNoArgsOptions(localOptions); + addSystemPropertyOptions(localOptions); + addProfilesOptions(localOptions); + addProjectsOptions(localOptions); + addAlternativePomOption(localOptions); - return options; + return localOptions; } private void reset() { @@ -194,7 +194,7 @@ private String rebuildProjectsCmd() { String projectList = String.join(",", projects); // Remove single and double quotes if the string starts and ends with them projectList = projectList.replaceAll("(^['\"])|(['\"]$)", "").trim(); - // Finally remove all spaces inside the string + // Finally, remove all spaces inside the string projectList = projectList.replaceAll("\\s+", ""); return " -" + PROJECTS_OPTION + " " + projectList; diff --git a/core/src/main/java/org/jboss/sbomer/core/features/sbom/utils/commandline/maven/MavenCommandOptions.java b/core/src/main/java/org/jboss/sbomer/core/features/sbom/utils/commandline/maven/MavenCommandOptions.java index 373b50703..763b18c11 100644 --- a/core/src/main/java/org/jboss/sbomer/core/features/sbom/utils/commandline/maven/MavenCommandOptions.java +++ b/core/src/main/java/org/jboss/sbomer/core/features/sbom/utils/commandline/maven/MavenCommandOptions.java @@ -20,8 +20,12 @@ import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; +import java.util.List; + public class MavenCommandOptions { + private static final String COMPATIBILITY_DESC = "Ineffective, only kept for backward compatibility"; + private static final String ALSO_MAKE_OPTION = "am"; private static final String ALSO_MAKE_DEPENDENTS_OPTION = "amd"; private static final String STRICT_CHECKSUM_OPTION = "C"; @@ -33,8 +37,12 @@ public class MavenCommandOptions { public static final String PROJECTS_OPTION = "pl"; public static final String ALTERNATIVE_POM = "f"; - public static final String[] NO_ARGS_OPTIONS = { ALSO_MAKE_OPTION, ALSO_MAKE_DEPENDENTS_OPTION, - STRICT_CHECKSUM_OPTION, LAX_CHECKSUM_OPTION, NON_RECURSIVE_OPTION }; + public static final List NO_ARGS_OPTIONS = List.of( + ALSO_MAKE_OPTION, + ALSO_MAKE_DEPENDENTS_OPTION, + STRICT_CHECKSUM_OPTION, + LAX_CHECKSUM_OPTION, + NON_RECURSIVE_OPTION); private MavenCommandOptions() { // This is a utility class @@ -43,34 +51,18 @@ private MavenCommandOptions() { /** * Add ineffective maven command options kept for backward compatibility * - * @param options - * @return + * @param options the options to add the ineffective options to + * @return the options with the ineffective options added */ public static Options addIneffectiveOptions(Options options) { options.addOption( - Option.builder("cpu") - .longOpt("check-plugin-updates") - .hasArg(false) - .desc("Ineffective, only kept for backward compatibility") - .build()); + Option.builder("cpu").longOpt("check-plugin-updates").hasArg(false).desc(COMPATIBILITY_DESC).build()); options.addOption( - Option.builder("npr") - .longOpt("no-plugin-registry") - .hasArg(false) - .desc("Ineffective, only kept for backward compatibility") - .build()); + Option.builder("npr").longOpt("no-plugin-registry").hasArg(false).desc(COMPATIBILITY_DESC).build()); options.addOption( - Option.builder("npu") - .longOpt("no-plugin-updates") - .hasArg(false) - .desc("Ineffective, only kept for backward compatibility") - .build()); + Option.builder("npu").longOpt("no-plugin-updates").hasArg(false).desc(COMPATIBILITY_DESC).build()); options.addOption( - Option.builder("up") - .longOpt("update-plugins") - .hasArg(false) - .desc("Ineffective, only kept for backward compatibility") - .build()); + Option.builder("up").longOpt("update-plugins").hasArg(false).desc(COMPATIBILITY_DESC).build()); return options; } @@ -78,8 +70,8 @@ public static Options addIneffectiveOptions(Options options) { /** * Add maven command options which should be ignored but should be parsed * - * @param options - * @return + * @param options the options to add the ignorable options to + * @return the options with the ignorable options added */ public static Options addIgnorableOptions(Options options) { options.addOption( @@ -218,8 +210,8 @@ public static Options addIgnorableOptions(Options options) { /** * Add maven command options which do not have any argument * - * @param options - * @return + * @param options the options to add the no-args options to + * @return the options with the no-args options added */ public static Options addNoArgsOptions(Options options) { options.addOption( @@ -259,8 +251,8 @@ public static Options addNoArgsOptions(Options options) { /** * Add command line provided system properties * - * @param options - * @return + * @param options the options to add the system property options to + * @return the options with the system property options added */ public static Options addSystemPropertyOptions(Options options) { options.addOption( @@ -278,8 +270,8 @@ public static Options addSystemPropertyOptions(Options options) { /** * Add maven command options to parse profiles * - * @param options - * @return + * @param options the options to add the profiles options to + * @return the options with the profiles options added */ public static Options addProfilesOptions(Options options) { options.addOption( @@ -296,8 +288,8 @@ public static Options addProfilesOptions(Options options) { /** * Add maven command options to parse projects * - * @param options - * @return + * @param options the options to add the projects options to + * @return the options with the projects options added */ public static Options addProjectsOptions(Options options) { options.addOption( @@ -315,8 +307,8 @@ public static Options addProjectsOptions(Options options) { /** * Add maven command options to parse pom alternative locations * - * @param options - * @return + * @param options the options to add the alternative pom options to + * @return the options with the alternative pom options added */ public static Options addAlternativePomOption(Options options) { options.addOption( diff --git a/core/src/main/java/org/jboss/sbomer/core/pnc/PncService.java b/core/src/main/java/org/jboss/sbomer/core/pnc/PncService.java index cf299e45c..8e48e25b8 100644 --- a/core/src/main/java/org/jboss/sbomer/core/pnc/PncService.java +++ b/core/src/main/java/org/jboss/sbomer/core/pnc/PncService.java @@ -412,8 +412,7 @@ public Artifact getArtifact(String purl, Optional sha256, Optional asMap(String path) throws IOException { diff --git a/core/src/main/java/org/jboss/sbomer/core/utils/h2/JsonUtils.java b/core/src/main/java/org/jboss/sbomer/core/utils/h2/JsonUtils.java index 70897631b..e0c85a998 100644 --- a/core/src/main/java/org/jboss/sbomer/core/utils/h2/JsonUtils.java +++ b/core/src/main/java/org/jboss/sbomer/core/utils/h2/JsonUtils.java @@ -22,11 +22,14 @@ import com.fasterxml.jackson.databind.JsonNode; /* - * Utility class which is needed to enhance H2 database to query JsonNode content. + * Utility class which is needed to enhance the H2 database to query JsonNode content. * * This class is mapped in service/src/main/resources/init.sql */ public class JsonUtils { + private JsonUtils() { + throw new IllegalStateException("This is a utility class that should not be instantiated"); + } public static String jsonExtract(String json, String path) { try { diff --git a/core/src/test/java/org/jboss/sbomer/core/test/unit/SbomUtilsTest.java b/core/src/test/java/org/jboss/sbomer/core/test/unit/SbomUtilsTest.java index 5c4464c81..866c01ed0 100644 --- a/core/src/test/java/org/jboss/sbomer/core/test/unit/SbomUtilsTest.java +++ b/core/src/test/java/org/jboss/sbomer/core/test/unit/SbomUtilsTest.java @@ -394,7 +394,7 @@ void testUpdatePurl() { assertEquals("pkg:maven/org.ow2.asm/asm@9.1.0.redhat-00002?type=jar", bom.getComponents().get(1).getPurl()); assertEquals("pkg:maven/custom@1.1.0.redhat-00002?type=jar", bom.getComponents().get(2).getPurl()); - // Main component's purl should be updated + // The main component's purl should be updated assertEquals( "pkg:maven/main-product-updated/asm@9.1.0.redhat-00002?type=jar", bom.getMetadata().getComponent().getPurl()); diff --git a/core/src/test/java/org/jboss/sbomer/core/test/unit/config/ConfigSchemaValidatorTest.java b/core/src/test/java/org/jboss/sbomer/core/test/unit/config/ConfigSchemaValidatorTest.java index 9d1962889..4508d0ab0 100644 --- a/core/src/test/java/org/jboss/sbomer/core/test/unit/config/ConfigSchemaValidatorTest.java +++ b/core/src/test/java/org/jboss/sbomer/core/test/unit/config/ConfigSchemaValidatorTest.java @@ -74,7 +74,7 @@ void shouldFailOnInvalidObjectListingAllProblems() { } /** - * With the feature to generate minifests for all builds + * With the feature to generate manifests for all builds * (...) the Red Hat Product processor has been made * optional. */ @@ -164,6 +164,8 @@ private OperationConfig minimalRuntimeOperationConfig() { .withGenerator(GeneratorConfig.builder().type(GeneratorType.CYCLONEDX_OPERATION).build()) .build(); + productConfig.setProcessors(processors); + return OperationConfig.builder().withOperationId("OPERATIONAABBCC").withProduct(productConfig).build(); } diff --git a/service/src/main/java/org/jboss/sbomer/service/feature/sbom/errata/event/comment/CommentAdvisoryOnRelevantEventsListener.java b/service/src/main/java/org/jboss/sbomer/service/feature/sbom/errata/event/comment/CommentAdvisoryOnRelevantEventsListener.java index eed22e137..7c219709b 100644 --- a/service/src/main/java/org/jboss/sbomer/service/feature/sbom/errata/event/comment/CommentAdvisoryOnRelevantEventsListener.java +++ b/service/src/main/java/org/jboss/sbomer/service/feature/sbom/errata/event/comment/CommentAdvisoryOnRelevantEventsListener.java @@ -291,9 +291,9 @@ private String getGenerationNVRFromManifest(V1Beta1RequestManifestRecord manifes // The NVR is not stored inside the generation, we need to get it from the manifest. If it is null, it might // be a release manifest, we will return the identifier Sbom sbom = sbomService.get(manifestRecord.id()); - String[] nvrArray = SbomUtils.computeNVRFromContainerManifest(sbom.getSbom()); - if (nvrArray != null && nvrArray.length > 0) { - return String.join("-", nvrArray); + List nvrList = SbomUtils.computeNVRFromContainerManifest(sbom.getSbom()); + if (!nvrList.isEmpty()) { + return String.join("-", nvrList); } return manifestRecord.identifier() + ": "; } diff --git a/service/src/main/java/org/jboss/sbomer/service/feature/sbom/errata/event/release/ReleaseStandardAdvisoryEventsListener.java b/service/src/main/java/org/jboss/sbomer/service/feature/sbom/errata/event/release/ReleaseStandardAdvisoryEventsListener.java index 47e1b1a1a..00369f65f 100644 --- a/service/src/main/java/org/jboss/sbomer/service/feature/sbom/errata/event/release/ReleaseStandardAdvisoryEventsListener.java +++ b/service/src/main/java/org/jboss/sbomer/service/feature/sbom/errata/event/release/ReleaseStandardAdvisoryEventsListener.java @@ -891,8 +891,8 @@ private String getGenerationNVRFromManifest(V1Beta1RequestManifestRecord manifes // The NVR is not stored inside the generation, we need to get it from the manifest. Might be optimized in // the future. Sbom sbom = sbomService.get(manifestRecord.id()); - String[] nvr = SbomUtils.computeNVRFromContainerManifest(sbom.getSbom()); - if (nvr != null) { + List nvr = SbomUtils.computeNVRFromContainerManifest(sbom.getSbom()); + if (!nvr.isEmpty()) { return String.join(NVR_STANDARD_SEPARATOR, nvr); } }