Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

style: Fix some more low severity code issues #1111

Merged
merged 1 commit into from
Feb 3, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 2 additions & 4 deletions cli/src/main/java/org/jboss/sbomer/cli/CLI.java
Original file line number Diff line number Diff line change
Expand Up @@ -92,9 +92,7 @@ private void runIfCallable(CommandLine parsed, List<Object> result) {
parsed.setExecutionResult(executionResult);

result.add(executionResult);
} catch (ParameterException ex) {
throw ex;
} catch (ExecutionException ex) {
} catch (ParameterException | ExecutionException ex) {
throw ex;
} catch (Exception ex) {
throw new ExecutionException(parsed, "Error while calling command (" + parsed + "): " + ex, ex);
Expand All @@ -106,7 +104,7 @@ private void runIfCallable(CommandLine parsed, List<Object> result) {
* Checks whether one of previously run commands failed.
*
* @param result A {@link List} of return values from a command.
* @return {@code true} if one of previous cmmands failed, {@code false} otherwise.
* @return {@code true} if one of previous commands failed, {@code false} otherwise.
*/
private boolean isFailed(List<Object> result) {
return result.stream().anyMatch(r -> r instanceof Integer res && res != 0);
Expand Down
5 changes: 2 additions & 3 deletions cli/src/main/java/org/jboss/sbomer/cli/ExceptionHandler.java
Original file line number Diff line number Diff line change
Expand Up @@ -70,11 +70,10 @@ public int handleExecutionException(Exception ex, CommandLine cmd, ParseResult p
String failureReasonPath = System.getenv("SBOMER_CLI_FAILURE_REASON_PATH");

if (failureReasonPath != null) {
Files.write(
Files.writeString(
Path.of(failureReasonPath),
ObjectMapperProvider.json()
.writeValueAsString(Map.of("message", ex.getMessage(), "exitCode", exitCode))
.getBytes(StandardCharsets.UTF_8));
.writeValueAsString(Map.of("message", ex.getMessage(), "exitCode", exitCode)));
}

return exitCode;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ public Config getConfig(Build build) {
scmTag = build.getNoRebuildCause().getScmTag();
}

byte[] configContent = null;
byte[] configContent;

if (scmUrl.contains("gerrit")) {
configContent = getGerritConfigContent(scmUrl, scmTag);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
package org.jboss.sbomer.cli.feature.sbom.adjuster;

import lombok.extern.slf4j.Slf4j;
import org.cyclonedx.exception.GeneratorException;
import org.cyclonedx.model.Bom;
import org.cyclonedx.model.Component;
import org.cyclonedx.model.ExternalReference;
Expand All @@ -27,9 +26,6 @@
import org.jboss.sbomer.core.features.sbom.utils.SbomUtils;

import java.util.List;
import java.util.UUID;

import static java.nio.charset.StandardCharsets.UTF_8;

@Slf4j
public abstract class AbstractAdjuster implements Adjuster {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ public class SyftImageAdjuster extends AbstractAdjuster {
* retained in the generated manifest. In case the found component is not on a path in this list it will be removed
* from the manifest.
* </p>
* ffi
*
* <p>
* If this is {@code null} or an empty list is provided -- all components will be retained in the manifest.
Expand All @@ -77,7 +78,7 @@ public class SyftImageAdjuster extends AbstractAdjuster {
*
* @see SyftImageAdjuster#adjustProperties(List)
*/
static final private List<String> ALLOWED_PROPERTY_PREFIXES = List.of(
private static final List<String> ALLOWED_PROPERTY_PREFIXES = List.of(
"sbomer:package:language",
"sbomer:package:type",
"sbomer:location:0:path",
Expand Down Expand Up @@ -106,7 +107,7 @@ private boolean isOnPath(String path) {
return true;
}

return paths.stream().anyMatch(prefix -> path.startsWith(prefix));
return paths.stream().anyMatch(path::startsWith);
}

@Override
Expand Down Expand Up @@ -311,7 +312,7 @@ private void adjustPublisher(Bom bom) {

// Adjust the publisher for all components in the BOM
if (bom.getComponents() != null) {
bom.getComponents().forEach(component -> adjustComponentPublisher(component));
bom.getComponents().forEach(this::adjustComponentPublisher);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -300,7 +300,7 @@ protected void doClone(String url, String tag, Path path, boolean force) {

log.warn("Cleaning up the '{}' output directory before cloning...", path);

// Delete the output directory directory
// Delete the output directory
FileUtils.rmdir(path);

log.debug("Done.");
Expand Down Expand Up @@ -334,7 +334,7 @@ protected void doClone(String url, String tag, Path path, boolean force) {
// Please note that this ignores the block size of a particular storage,
// and because of this, the number can be different compared to when
// an utility like `du` is being used to determine the size.
log.info("Directory size: {} MB", String.format("%.02f", Float.valueOf(dirSize(path)) / 1024));
log.info("Directory size: {} MB", String.format("%.02f", (float) dirSize(path) / 1024));
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,6 @@ protected Path doGenerate() {
Dependency dep = purl256ToDependencies.get(artifact.getArtifact().getPurl());
Optional.ofNullable(artifact.getArchiveFilenames())
.orElse(List.of())
.stream()
.forEach(filename -> pathToDependencies.put(filename, dep));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ private String[] command(String buildCmdOptions) {

cmd.addAll(Arrays.asList(generatorArgs().split(" ")));

return cmd.toArray(new String[cmd.size()]);
return cmd.toArray(new String[0]);
}

@Override
Expand All @@ -93,7 +93,7 @@ protected GeneratorType generatorType() {
private void configureProcessEnvironmentVariable(String buildCmdOptions, Map<String, String> environment) {
// If there is an hint about the major Gradle version required, use it.
Optional<Integer> gradleMajorVersion = extractGradleMajorVersion(buildCmdOptions);
if (!gradleMajorVersion.isPresent() || gradleMajorVersion.get() >= 5) {
if (gradleMajorVersion.isEmpty() || gradleMajorVersion.get() >= 5) {
environment.put(GRADLE_PLUGIN_VERSION_ENV_VARIABLE, toolVersion());
} else {
// If the version is previous 5, force the Gradle CycloneDX plugin version to 1.6.1 for backward
Expand All @@ -104,13 +104,11 @@ private void configureProcessEnvironmentVariable(String buildCmdOptions, Map<Str

private void configureProcessMainBuildCommands(String buildCmdOptions, List<String> cmd) {
Optional<String> mainGradleBuildCommand = extractGradleMainBuildCommand(buildCmdOptions);
if (!mainGradleBuildCommand.isPresent()) {
if (mainGradleBuildCommand.isEmpty()) {
throw new ApplicationException("Gradle build command is empty.");
}

List.of(mainGradleBuildCommand.get().split(SPLIT_BY_SPACE_HONORING_SINGLE_AND_DOUBLE_QUOTES))
.stream()
.forEach(cmd::add);
cmd.addAll(Arrays.asList(mainGradleBuildCommand.get().split(SPLIT_BY_SPACE_HONORING_SINGLE_AND_DOUBLE_QUOTES)));
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -57,9 +57,9 @@ protected Path doGenerate(String buildCmdOptions) {
}

private String[] command(String buildCmdOptions) {
List<String> cmd = new ArrayList<>();

cmd.addAll(List.of(buildCmdOptions.split(SPLIT_BY_SPACE_HONORING_SINGLE_AND_DOUBLE_QUOTES)));
List<String> cmd = new ArrayList<>(
List.of(buildCmdOptions.split(SPLIT_BY_SPACE_HONORING_SINGLE_AND_DOUBLE_QUOTES)));
cmd.add(String.format("org.cyclonedx:cyclonedx-maven-plugin:%s:makeAggregateBom", toolVersion()));
cmd.add("-DoutputFormat=json");
cmd.add("-DoutputName=bom");
Expand All @@ -73,7 +73,7 @@ private String[] command(String buildCmdOptions) {

cmd.addAll(Arrays.asList(generatorArgs().split(" ")));

return cmd.toArray(new String[cmd.size()]);
return cmd.toArray(new String[0]);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ private String[] command(String buildCmdOptions) {

cmd.addAll(Arrays.asList(generatorArgs().split(" ")));

return cmd.toArray(new String[cmd.size()]);
return cmd.toArray(new String[0]);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
public class PathConverter implements ITypeConverter<Path> {

@Override
public Path convert(String value) throws Exception {
public Path convert(String value) {
return PathConverter.homeExpanded(value);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ private void generateSbom(PncBuildConfig config, ProductConfig product, int i) {
log.info("Running: '{}'", cmd);

// Execute the generation
if (spec.root().commandLine().execute(command.toArray(new String[command.size()])) != 0) {
if (spec.root().commandLine().execute(command.toArray(new String[0])) != 0) {
throw new ApplicationException("Command '{}' failed, see logs above", cmd);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ private PncBuildConfig mappingConfig(Build build) {
if (configs.isEmpty()) {
log.debug(
"No configuration found for product versions: {}",
productVersions.stream().map(pv -> pv.getId()).collect(Collectors.toList()));
productVersions.stream().map(ProductVersionRef::getId).collect(Collectors.toList()));
return null;
}

Expand Down Expand Up @@ -403,7 +403,7 @@ public Integer call() throws Exception {
if (!result.isValid()) {
log.error("Configuration is not valid!");

result.getErrors().forEach(msg -> log.error(msg));
result.getErrors().forEach(log::error);
return GenerationResult.ERR_CONFIG_INVALID.getCode();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -199,7 +199,7 @@ private void generateDeliverableSbom(OperationConfig config, int i) {
log.info("Running: '{}'", cmd);

// Execute the generation
if (spec.root().commandLine().execute(command.toArray(new String[command.size()])) != 0) {
if (spec.root().commandLine().execute(command.toArray(new String[0])) != 0) {
throw new ApplicationException("Command '{}' failed, see logs above", cmd);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,10 +64,7 @@ public enum ConfigFormat {
description = "The PNC operation identifier, example: AYHJRDPEUMYAC")
String operationId;

@Option(
names = { "--config" },
required = false,
description = "The PNC operation identifier, example: AYHJRDPEUMYAC")
@Option(names = { "--config" }, description = "The PNC operation identifier, example: AYHJRDPEUMYAC")
Path partialConfigPath;

@Option(names = { "--format" }, defaultValue = "yaml", description = "Format of the generated configuration.")
Expand Down Expand Up @@ -199,7 +196,7 @@ public Integer call() throws Exception {
if (!result.isValid()) {
log.error("Configuration is not valid!");

result.getErrors().forEach(msg -> log.error(msg));
result.getErrors().forEach(log::error);
return GenerationResult.ERR_CONFIG_INVALID.getCode();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,9 +59,7 @@ public Integer call() throws Exception {
addContext();

List<Path> sbomPaths = findManifests(parent.getPath());
List<Bom> boms = sbomPaths.stream()
.map(sbomPath -> SbomUtils.fromPath(sbomPath))
.collect(Collectors.toList());
List<Bom> boms = sbomPaths.stream().map(SbomUtils::fromPath).collect(Collectors.toList());

log.info("Starting {} cataloguer", getCataloguerType());

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,12 +104,11 @@ private void copyProperties(Component destination, Component origin) {
"sbomer:image:labels:release",
"sbomer:image:labels:version");

propertyNames.forEach(propertyName -> {
SbomUtils.findPropertyWithNameInComponent(propertyName, origin)
.ifPresent(
property -> SbomUtils
.addPropertyIfMissing(destination, property.getName(), property.getValue()));
});
propertyNames.forEach(
propertyName -> SbomUtils.findPropertyWithNameInComponent(propertyName, origin)
.ifPresent(
property -> SbomUtils
.addPropertyIfMissing(destination, property.getName(), property.getValue())));
}

private Component createVariant(Component mainComponent, String bomRefPrefix) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -119,11 +119,10 @@ public Path run(Path workDir, String... generatorArgs) {
}

private String[] command(Path dominoToolPath, Path workDir, String... args) {
List<String> cmd = new ArrayList<>();

log.debug("Using following Java binary to run Domino: '{}'", dominoJava);

cmd.addAll(
List<String> cmd = new ArrayList<>(
Arrays.asList(
dominoJava,
"-XX:InitialRAMPercentage=75.0",
Expand Down Expand Up @@ -161,6 +160,6 @@ private String[] command(Path dominoToolPath, Path workDir, String... args) {
cmd.add(settingsXmlPath.toString());
}

return cmd.toArray(new String[cmd.size()]);
return cmd.toArray(new String[0]);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ public static void run(Map<String, String> environment, Path workDir, String...

log.info("Starting execution...");

Process process = null;
Process process;

try {
process = pb.start();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,11 @@
*/
package org.jboss.sbomer.cli.feature.sbom.processor;

import static org.jboss.sbomer.cli.feature.sbom.command.CycloneDxGenerateOperationCommand.SBOM_REPRESENTING_THE_DELIVERABLE;
import static org.jboss.sbomer.core.features.sbom.Constants.SBOM_RED_HAT_BREW_BUILD_ID;
import static org.jboss.sbomer.core.features.sbom.Constants.SBOM_RED_HAT_ENVIRONMENT_IMAGE;
import static org.jboss.sbomer.core.features.sbom.Constants.SBOM_RED_HAT_PNC_BUILD_ID;
import static org.jboss.sbomer.core.features.sbom.utils.SbomUtils.addHashIfMissing;
import static org.jboss.sbomer.core.features.sbom.utils.SbomUtils.addMrrc;
import static org.jboss.sbomer.core.features.sbom.utils.SbomUtils.createComponent;
import static org.jboss.sbomer.core.features.sbom.utils.SbomUtils.createDependency;
import static org.jboss.sbomer.core.features.sbom.utils.SbomUtils.getExternalReferences;
import static org.jboss.sbomer.core.features.sbom.utils.SbomUtils.getHash;
import static org.jboss.sbomer.core.features.sbom.utils.SbomUtils.hasExternalReference;
import static org.jboss.sbomer.core.features.sbom.utils.SbomUtils.setArtifactMetadata;
Expand All @@ -35,28 +31,19 @@
import static org.jboss.sbomer.core.features.sbom.utils.SbomUtils.setSupplier;
import static org.jboss.sbomer.core.features.sbom.utils.SbomUtils.updatePurl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

import com.github.packageurl.MalformedPackageURLException;
import com.github.packageurl.PackageURL;
import org.cyclonedx.model.Bom;
import org.cyclonedx.model.Component;
import org.cyclonedx.model.Dependency;
import org.cyclonedx.model.ExternalReference;
import org.cyclonedx.model.Hash;
import org.cyclonedx.model.Property;
import org.jboss.pnc.build.finder.koji.KojiBuild;
import org.jboss.pnc.dto.Artifact;
import org.jboss.pnc.dto.Build;
import org.jboss.pnc.enums.BuildType;
import org.jboss.sbomer.cli.feature.sbom.adjuster.PncBuildAdjuster;
import org.jboss.sbomer.cli.feature.sbom.service.KojiService;
import org.jboss.sbomer.core.errors.ApplicationException;
Expand Down Expand Up @@ -337,13 +324,12 @@ private void processContainerImageComponent(Component component) {
return;
}

String nvr = List.of(componentOpt.get().getValue(), versionOpt.get().getValue(), releaseOpt.get().getValue())
.stream()
.collect(Collectors.joining("-"));
String nvr = String
.join("-", componentOpt.get().getValue(), versionOpt.get().getValue(), releaseOpt.get().getValue());

log.debug("Looking up container information in Brew for NVR '{}'", nvr);

KojiBuildInfo buildInfo = null;
KojiBuildInfo buildInfo;

try {
buildInfo = kojiService.findBuild(nvr);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ public Set<Class<?>> getEnabledAlternatives() {

@Test
@DisplayName("Should successfully run default processor")
void testSuccessfulProcessing(QuarkusMainLauncher launcher, @TempDir Path tempDir) throws Exception {
void testSuccessfulProcessing(QuarkusMainLauncher launcher, @TempDir Path tempDir) {

LaunchResult result = launcher.launch(
"-v",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ public Set<Class<?>> getEnabledAlternatives() {

@Test
@DisplayName("Should successfully run redhat-product processor")
void testSuccessfulProcessing(QuarkusMainLauncher launcher, @TempDir Path tempDir) throws Exception {
void testSuccessfulProcessing(QuarkusMainLauncher launcher, @TempDir Path tempDir) {

LaunchResult result = launcher.launch(
"-v",
Expand Down
Loading
Loading