Skip to content

Commit 10693ba

Browse files
authored
chore: code cleanup, remove redundant and obsolete codes and simplify some method calls. (#142)
## Description chore: code cleanup, remove redundant and obsolete codes and simplify some method calls. ## Checklist - [x] I have followed this repository's contributing guidelines. - [x] I will adhere to the project's code of conduct. --------- Signed-off-by: Chao Wang <[email protected]>
1 parent e53b921 commit 10693ba

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

44 files changed

+273
-381
lines changed

src/main/java/com/redhat/exhort/Api.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@
2727
/** The Api interface is used for contracting API implementations. * */
2828
public interface Api {
2929

30-
public static final String CYCLONEDX_MEDIA_TYPE = "application/vnd.cyclonedx+json";
30+
String CYCLONEDX_MEDIA_TYPE = "application/vnd.cyclonedx+json";
3131

3232
enum MediaType {
3333
APPLICATION_JSON,

src/main/java/com/redhat/exhort/image/Image.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,7 @@ public Image(String fullName) {
8989

9090
/**
9191
* Create an image name with a tag. If a tag is provided (i.e. is not null) then this tag is used.
92-
* Otherwise the tag of the provided name is used (if any).
92+
* Otherwise, the tag of the provided name is used (if any).
9393
*
9494
* @param fullName The fullname of the image in Docker format. I
9595
* @param givenTag tag to use. Can be null in which case the tag specified in fullName is used.
@@ -190,7 +190,7 @@ public String toString() {
190190
}
191191

192192
public boolean hasRegistry() {
193-
return registry != null && registry.length() > 0;
193+
return registry != null && !registry.isEmpty();
194194
}
195195

196196
private String joinTail(String[] parts) {
@@ -329,7 +329,7 @@ private void doValidate() {
329329
checks[i], value, checkPattern.pattern()));
330330
}
331331
}
332-
if (errors.size() > 0) {
332+
if (!errors.isEmpty()) {
333333
StringBuilder buf = new StringBuilder();
334334
buf.append(String.format("Given Docker name '%s' is invalid:\n", getFullName()));
335335
for (String error : errors) {

src/main/java/com/redhat/exhort/image/ImageRef.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ public class ImageRef {
3434
public static final String OS_QUALIFIER = "os";
3535
public static final String VARIANT_QUALIFIER = "variant";
3636

37-
private Image image;
37+
private final Image image;
3838
private Platform platform;
3939

4040
public ImageRef(String image, String platform) {
@@ -48,8 +48,8 @@ public ImageRef(String image, String platform) {
4848
}
4949

5050
public ImageRef(PackageURL packageURL) {
51-
String name = null;
52-
String version = null;
51+
String name;
52+
String version;
5353
String tag = null;
5454
String repositoryRrl = null;
5555
String arch = null;

src/main/java/com/redhat/exhort/impl/ExhortApi.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -427,7 +427,7 @@ private void commonHookAfterProviderCreatedSbomAndBeforeExhort() {
427427
"Time took to create sbom file to be sent to exhort backend, in ms : %s, in seconds:"
428428
+ " %s",
429429
this.startTime.until(this.providerEndTime, ChronoUnit.MILLIS),
430-
(float) (this.startTime.until(this.providerEndTime, ChronoUnit.MILLIS) / 1000F)));
430+
this.startTime.until(this.providerEndTime, ChronoUnit.MILLIS) / 1000F));
431431
}
432432
}
433433

@@ -673,13 +673,13 @@ private HttpRequest buildRequest(
673673
// set rhda-token
674674
// Environment variable/property name = RHDA_TOKEN
675675
String rhdaToken = calculateHeaderValue(RHDA_TOKEN_HEADER);
676-
if (rhdaToken != null && Optional.of(rhdaToken).isPresent()) {
676+
if (rhdaToken != null) {
677677
request.setHeader(RHDA_TOKEN_HEADER, rhdaToken);
678678
}
679679
// set rhda-source ( extension/plugin id/name)
680680
// Environment variable/property name = RHDA_SOURCE
681681
String rhdaSource = calculateHeaderValue(RHDA_SOURCE_HEADER);
682-
if (rhdaSource != null && Optional.of(rhdaSource).isPresent()) {
682+
if (rhdaSource != null) {
683683
request.setHeader(RHDA_SOURCE_HEADER, rhdaSource);
684684
}
685685
request.setHeader(RHDA_OPERATION_TYPE_HEADER, analysisType);

src/main/java/com/redhat/exhort/impl/RequestManager.java

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323
public class RequestManager {
2424

2525
private static RequestManager requestManager;
26-
private Map<String, String> requests;
26+
private final Map<String, String> requests;
2727

2828
public static RequestManager getInstance() {
2929
if (Objects.isNull(requestManager)) {
@@ -47,11 +47,9 @@ public synchronized void removeClientTraceIdFromRequest() {
4747
Optional<String> keyOfParent =
4848
requests.entrySet().stream()
4949
.filter(pair -> pair.getValue().equals(removedClientTraceId))
50-
.map(pair -> pair.getKey())
50+
.map(Map.Entry::getKey)
5151
.findFirst();
52-
if (keyOfParent.isPresent()) {
53-
requests.remove(keyOfParent.get());
54-
}
52+
keyOfParent.ifPresent(requests::remove);
5553
}
5654
}
5755

src/main/java/com/redhat/exhort/providers/BaseJavaProvider.java

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ void parseDependencyTree(String src, int srcDepth, String[] lines, Sbom sbom, St
3636
if (lines.length == 0) {
3737
return;
3838
}
39-
if (lines.length == 1 && lines[0].trim().equals("")) {
39+
if (lines.length == 1 && lines[0].trim().isEmpty()) {
4040
return;
4141
}
4242
int index = 0;
@@ -90,7 +90,7 @@ PackageURL parseDep(String dep) {
9090
dependency = dependency.replace(":runtime", ":compile").replace(":provided", ":compile");
9191
int endIndex = Math.max(dependency.indexOf(":compile"), dependency.indexOf(":test"));
9292
int scopeLength;
93-
if (dependency.indexOf(":compile") > -1) {
93+
if (dependency.contains(":compile")) {
9494
scopeLength = ":compile".length();
9595
} else {
9696
scopeLength = ":test".length();
@@ -140,7 +140,7 @@ else if (parts.length == 6) {
140140
}
141141

142142
int getDepth(String line) {
143-
if (line == null || line.trim().equals("")) {
143+
if (line == null || line.trim().isEmpty()) {
144144
return -1;
145145
}
146146

@@ -165,7 +165,7 @@ static final class DependencyAggregator {
165165
/**
166166
* Get the string representation of the dependency to use as excludes
167167
*
168-
* @return an exclude string for the dependency:tree plugin, ie. group-id:artifact-id:*:version
168+
* @return an exclude string for the dependency:tree plugin, i.e. group-id:artifact-id:*:version
169169
*/
170170
@Override
171171
public String toString() {
@@ -188,7 +188,7 @@ PackageURL toPurl() {
188188
groupId,
189189
artifactId,
190190
version,
191-
this.scope == "*" ? null : new TreeMap<>(Map.of("scope", this.scope)),
191+
this.scope.equals("*") ? null : new TreeMap<>(Map.of("scope", this.scope)),
192192
null);
193193
} catch (MalformedPackageURLException e) {
194194
throw new IllegalArgumentException("Unable to parse PackageURL", e);

src/main/java/com/redhat/exhort/providers/GoModulesProvider.java

Lines changed: 50 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,6 @@
1717

1818
import static com.redhat.exhort.impl.ExhortApi.debugLoggingIsNeeded;
1919

20-
import com.fasterxml.jackson.core.JsonProcessingException;
21-
import com.fasterxml.jackson.databind.JsonMappingException;
2220
import com.github.packageurl.MalformedPackageURLException;
2321
import com.github.packageurl.PackageURL;
2422
import com.redhat.exhort.Api;
@@ -36,7 +34,13 @@
3634
import java.nio.charset.StandardCharsets;
3735
import java.nio.file.Files;
3836
import java.nio.file.Path;
39-
import java.util.*;
37+
import java.util.ArrayList;
38+
import java.util.Arrays;
39+
import java.util.HashMap;
40+
import java.util.List;
41+
import java.util.Map;
42+
import java.util.Objects;
43+
import java.util.TreeMap;
4044
import java.util.logging.Logger;
4145
import java.util.regex.Pattern;
4246
import java.util.stream.Collectors;
@@ -152,56 +156,52 @@ private void performManifestVersionsCheck(String[] goModGraphLines, Path manifes
152156
List<String> comparisonLines =
153157
Arrays.stream(goModGraphLines)
154158
.filter((line) -> line.startsWith(root))
155-
.map((line) -> getChildVertex(line))
159+
.map(GoModulesProvider::getChildVertex)
156160
.collect(Collectors.toList());
157161
List<String> goModDependencies = collectAllDepsFromManifest(lines, goModLines);
158-
comparisonLines.stream()
159-
.forEach(
160-
(dependency) -> {
161-
String[] parts = dependency.split("@");
162-
String version = parts[1];
163-
String depName = parts[0];
164-
goModDependencies.stream()
165-
.forEach(
166-
(dep) -> {
167-
String[] artifactParts = dep.trim().split(" ");
168-
String currentDepName = artifactParts[0];
169-
String currentVersion = artifactParts[1];
170-
if (currentDepName.trim().equals(depName.trim())) {
171-
if (!currentVersion.trim().equals(version.trim())) {
172-
throw new RuntimeException(
173-
String.format(
174-
"Can't continue with analysis - versions mismatch for"
175-
+ " dependency name=%s, manifest version=%s, installed"
176-
+ " Version=%s, if you want to allow version mismatch for"
177-
+ " analysis between installed and requested packages,"
178-
+ " set environment variable/setting -"
179-
+ " %s=false",
180-
depName,
181-
currentVersion,
182-
version,
183-
Provider.PROP_MATCH_MANIFEST_VERSIONS));
184-
}
185-
}
186-
});
187-
});
162+
comparisonLines.forEach(
163+
(dependency) -> {
164+
String[] parts = dependency.split("@");
165+
String version = parts[1];
166+
String depName = parts[0];
167+
goModDependencies.forEach(
168+
(dep) -> {
169+
String[] artifactParts = dep.trim().split(" ");
170+
String currentDepName = artifactParts[0];
171+
String currentVersion = artifactParts[1];
172+
if (currentDepName.trim().equals(depName.trim())) {
173+
if (!currentVersion.trim().equals(version.trim())) {
174+
throw new RuntimeException(
175+
String.format(
176+
"Can't continue with analysis - versions mismatch for"
177+
+ " dependency name=%s, manifest version=%s, installed"
178+
+ " Version=%s, if you want to allow version mismatch for"
179+
+ " analysis between installed and requested packages,"
180+
+ " set environment variable/setting -"
181+
+ " %s=false",
182+
depName,
183+
currentVersion,
184+
version,
185+
Provider.PROP_MATCH_MANIFEST_VERSIONS));
186+
}
187+
}
188+
});
189+
});
188190
} catch (IOException e) {
189191
throw new RuntimeException(
190192
"Failed to open go.mod file for manifest versions check validation!");
191193
}
192194
}
193195

194196
private List<String> collectAllDepsFromManifest(String[] lines, String goModLines) {
195-
List<String> result = new ArrayList<>();
196197
// collect all deps that starts with require keyword
197-
result =
198+
List<String> result =
198199
Arrays.stream(lines)
199200
.filter((line) -> line.trim().startsWith("require") && !line.contains("("))
200201
.map((dep) -> dep.substring("require".length()).trim())
201202
.collect(Collectors.toList());
202203

203204
// collect all deps that are inside `require` blocks
204-
205205
String currentSegmentOfGoMod = goModLines;
206206
Map<String, Integer> requirePosObject = decideRequireBlockIndex(currentSegmentOfGoMod);
207207
while (requirePosObject.get("index") > -1) {
@@ -245,15 +245,15 @@ public void determineMainModuleVersion(Path directory) {
245245
VersionControlSystem vcs = new GitVersionControlSystemImpl();
246246
if (vcs.isDirectoryRepo(directory)) {
247247
TagInfo latestTagInfo = vcs.getLatestTag(directory);
248-
if (!latestTagInfo.getTagName().trim().equals("")) {
248+
if (!latestTagInfo.getTagName().trim().isEmpty()) {
249249
if (!latestTagInfo.isCurrentCommitPointedByTag()) {
250250
String nextTagVersion = vcs.getNextTagVersion(latestTagInfo);
251251
this.mainModuleVersion = vcs.getPseudoVersion(latestTagInfo, nextTagVersion);
252252
} else {
253253
this.mainModuleVersion = latestTagInfo.getTagName();
254254
}
255255
} else {
256-
if (!latestTagInfo.getCurrentCommitDigest().trim().equals("")) {
256+
if (!latestTagInfo.getCurrentCommitDigest().trim().isEmpty()) {
257257
this.mainModuleVersion =
258258
vcs.getPseudoVersion(latestTagInfo, getDefaultMainModuleVersion());
259259
}
@@ -262,7 +262,7 @@ public void determineMainModuleVersion(Path directory) {
262262
}
263263

264264
private Sbom buildSbomFromGraph(
265-
String goModulesResult, List<PackageURL> ignoredDeps, Path manifestPath) throws IOException {
265+
String goModulesResult, List<PackageURL> ignoredDeps, Path manifestPath) {
266266
// Each entry contains a key of the module, and the list represents the module direct
267267
// dependencies , so
268268
// pairing of the key with each of the dependencies in a list is basically an edge in the graph.
@@ -272,7 +272,7 @@ private Sbom buildSbomFromGraph(
272272
// value of list of that module' dependencies.
273273
List<String> linesList = Arrays.asList(goModulesResult.split(System.lineSeparator()));
274274

275-
Integer startingIndex = 0;
275+
int startingIndex = 0;
276276
for (String line : linesList) {
277277
if (!edges.containsKey(getParentVertex(line))) {
278278
// Collect all direct dependencies of the current module into a list.
@@ -298,8 +298,7 @@ private Sbom buildSbomFromGraph(
298298
PackageURL source = toPurl(key, "@", this.goEnvironmentVariableForPurl);
299299
value.forEach(
300300
dep -> {
301-
PackageURL targetPurl =
302-
toPurl((String) dep, "@", this.goEnvironmentVariableForPurl);
301+
PackageURL targetPurl = toPurl(dep, "@", this.goEnvironmentVariableForPurl);
303302
sbom.addDependency(source, targetPurl, null);
304303
});
305304
});
@@ -348,12 +347,11 @@ private Map<String, List<String>> getFinalPackagesVersionsForModule(
348347

349348
private List<String> getListOfPackagesWithFinalVersions(
350349
Map<String, String> finalModulesVersions, Map.Entry<String, List<String>> entry) {
351-
return (List<String>)
352-
entry.getValue().stream()
353-
.map(
354-
(packageWithVersion) ->
355-
getPackageWithFinalVersion(finalModulesVersions, (String) packageWithVersion))
356-
.collect(Collectors.toList());
350+
return entry.getValue().stream()
351+
.map(
352+
(packageWithVersion) ->
353+
getPackageWithFinalVersion(finalModulesVersions, packageWithVersion))
354+
.collect(Collectors.toList());
357355
}
358356

359357
public static String getPackageWithFinalVersion(
@@ -387,11 +385,10 @@ private TreeMap<String, String> getQualifiers(boolean includeOsAndArch) {
387385
getEnvironmentVariable(goEnvironmentVariables, GO_HOST_ARCHITECTURE_ENV_NAME);
388386
String hostOS =
389387
getEnvironmentVariable(goEnvironmentVariables, GO_HOST_OPERATION_SYSTEM_ENV_NAME);
390-
return new TreeMap<String, String>(
391-
Map.of("type", "module", "goos", hostOS, "goarch", hostArch));
388+
return new TreeMap<>(Map.of("type", "module", "goos", hostOS, "goarch", hostArch));
392389
}
393390

394-
return new TreeMap<String, String>(Map.of("type", "module"));
391+
return new TreeMap<>(Map.of("type", "module"));
395392
}
396393

397394
private static String getEnvironmentVariable(String goEnvironmentVariables, String envName) {
@@ -403,8 +400,7 @@ private static String getEnvironmentVariable(String goEnvironmentVariables, Stri
403400
return envValue.replaceAll("\"", "");
404401
}
405402

406-
private String buildGoModulesDependencies(Path manifestPath)
407-
throws JsonMappingException, JsonProcessingException {
403+
private String buildGoModulesDependencies(Path manifestPath) {
408404
String[] goModulesDeps;
409405
goModulesDeps = new String[] {goExecutable, "mod", "graph"};
410406

src/main/java/com/redhat/exhort/providers/GradleProvider.java

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -233,7 +233,7 @@ private Path getDependencies(Path manifestPath) throws IOException {
233233
return tempFile;
234234
}
235235

236-
protected Path getProperties(Path manifestPath) throws IOException {
236+
private Path getProperties(Path manifestPath) throws IOException {
237237
Path propsTempFile = Files.createTempFile("propsfile", ".txt");
238238
String propCmd = gradleExecutable + " properties";
239239
String[] propCmdList = propCmd.split("\\s+");
@@ -504,8 +504,7 @@ private String getRoot(Path textFormatFile, Map<String, String> propertiesMap)
504504
String group = propertiesMap.get("group");
505505
String version = propertiesMap.get("version");
506506
String rootName = extractRootProjectValue(textFormatFile);
507-
String root = group + ':' + rootName + ':' + "jar" + ':' + version;
508-
return root;
507+
return group + ':' + rootName + ':' + "jar" + ':' + version;
509508
}
510509

511510
private String extractRootProjectValue(Path inputFilePath) throws IOException {

src/main/java/com/redhat/exhort/providers/JavaMavenProvider.java

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -162,13 +162,7 @@ private Content generateSbomFromEffectivePom() throws IOException {
162162
deps.stream()
163163
.filter(dep -> !testsDeps.contains(dep))
164164
.map(DependencyAggregator::toPurl)
165-
.filter(
166-
dep ->
167-
ignored.stream()
168-
.filter(artifact -> artifact.isCoordinatesEquals(dep))
169-
.collect(Collectors.toList())
170-
.size()
171-
== 0)
165+
.filter(dep -> ignored.stream().noneMatch(artifact -> artifact.isCoordinatesEquals(dep)))
172166
.forEach(d -> sbom.addDependency(sbom.getRoot(), d, null));
173167

174168
// build and return content for constructing request to the backend
@@ -206,7 +200,7 @@ private PackageURL getRoot(final Path manifestPath) throws IOException {
206200
break;
207201
}
208202
}
209-
if (isRoot && dependencyAggregator.isValid()) {
203+
if (dependencyAggregator.isValid()) {
210204
return dependencyAggregator.toPurl();
211205
}
212206
}

src/main/java/com/redhat/exhort/providers/JavaScriptNpmProvider.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ public JavaScriptNpmProvider(Path manifest) {
3232
}
3333

3434
@Override
35-
protected final String lockFileName() {
35+
protected String lockFileName() {
3636
return LOCK_FILE;
3737
}
3838

0 commit comments

Comments
 (0)