Skip to content

Commit

Permalink
Merge pull request #4744 from jeremylong/cleanup
Browse files Browse the repository at this point in the history
IntelliJ Code Inspection/Correction
  • Loading branch information
aikebah authored Aug 17, 2022
2 parents 73e8dad + 8381d22 commit 21cd89b
Show file tree
Hide file tree
Showing 110 changed files with 326 additions and 487 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ public class Check extends Update {
* to exclude files that contain matching content..
*/
@SuppressWarnings("CanBeFinal")
private List<String> retirejsFilters = new ArrayList<>();
private final List<String> retirejsFilters = new ArrayList<>();
/**
* Whether or not the RetireJS Analyzer filters non-vulnerable JS files from
* the report; default is false.
Expand Down Expand Up @@ -2067,7 +2067,7 @@ private void checkForFailure(Dependency[] dependencies) throws BuildException {
if (showSummary) {
msg = String.format("%n%nDependency-Check Failure:%n"
+ "One or more dependencies were identified with vulnerabilities that have a CVSS score greater than or equal to '%.1f': %s%n"
+ "See the dependency-check report for more details.%n%n", failBuildOnCVSS, ids.toString());
+ "See the dependency-check report for more details.%n%n", failBuildOnCVSS, ids);
} else {
msg = String.format("%n%nDependency-Check Failure:%n"
+ "One or more dependencies were identified with vulnerabilities.%n%n"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@
public class DependencyCheckTaskIT extends BaseDBTestCase {

@Rule
public BuildFileRule buildFileRule = new BuildFileRule();
public final BuildFileRule buildFileRule = new BuildFileRule();

@Before
@Override
Expand Down Expand Up @@ -129,9 +129,7 @@ public void testNestedBADReportFormat() throws Exception {
*/
@Test
public void testGetFailBuildOnCVSS() {
Exception exception = Assert.assertThrows(BuildException.class, () -> {
buildFileRule.executeTarget("failCVSS");
});
Exception exception = Assert.assertThrows(BuildException.class, () -> buildFileRule.executeTarget("failCVSS"));

String expectedMessage = String.format("One or more dependencies were identified with vulnerabilities that " +
"have a CVSS score greater than or equal to '%.1f':", 3.0f);
Expand Down
7 changes: 4 additions & 3 deletions cli/src/main/java/org/owasp/dependencycheck/App.java
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ public class App {
/**
* The configured settings.
*/
private Settings settings;
private final Settings settings;

/**
* The main method for the application.
Expand Down Expand Up @@ -334,7 +334,7 @@ private int determineReturnCode(Engine engine, float cvssFailScore) {
if (ids.length() > 0) {
LOGGER.error(
String.format("%n%nOne or more dependencies were identified with vulnerabilities that have a CVSS score greater than or "
+ "equal to '%.1f': %n%s%n%nSee the dependency-check report for more details.%n%n", cvssFailScore, ids.toString())
+ "equal to '%.1f': %n%s%n%nSee the dependency-check report for more details.%n%n", cvssFailScore, ids)
);

retCode = 1;
Expand Down Expand Up @@ -388,7 +388,7 @@ private Set<File> scanAntStylePaths(List<String> antStylePaths, int symLinkDepth
if (scanner.getIncludedFilesCount() > 0) {
for (String s : scanner.getIncludedFiles()) {
final File f = new File(baseDir, s);
LOGGER.debug("Found file {}", f.toString());
LOGGER.debug("Found file {}", f);
paths.add(f);
}
}
Expand Down Expand Up @@ -731,6 +731,7 @@ protected String ensureCanonicalPath(String path) {
* @param file a file path
* @return the position of the last file separator
*/
@SuppressWarnings("ManualMinMaxCalculation")
private int getLastFileSeparator(String file) {
if (file.contains("*") || file.contains("?")) {
int p1 = file.indexOf('*');
Expand Down
4 changes: 1 addition & 3 deletions cli/src/test/java/org/owasp/dependencycheck/AppTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -120,9 +120,7 @@ public void testPopulateSettings() throws Exception {
@Test
public void testPopulateSettingsException() throws Exception {
String[] args = {"-invalidPROPERTY"};
Exception exception = Assert.assertThrows(UnrecognizedOptionException.class, () -> {
testBooleanProperties(args, null);
});
Exception exception = Assert.assertThrows(UnrecognizedOptionException.class, () -> testBooleanProperties(args, null));
Assert.assertTrue(exception.getMessage().contains("Unrecognized option: -invalidPROPERTY"));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,7 @@ public void testParse_printVersionInfo() throws Exception {
String[] lines = text.split(System.getProperty("line.separator"));
Assert.assertTrue(lines.length >= 1);
Assert.assertTrue(text.contains("version"));
Assert.assertTrue(!text.contains("unknown"));
Assert.assertFalse(text.contains("unknown"));
} catch (IOException ex) {
System.setOut(out);
Assert.fail("CliParser.printVersionInfo did not write anything to system.out.");
Expand Down Expand Up @@ -323,7 +323,7 @@ public void testGetBooleanArgument() throws ParseException {
} catch (FileNotFoundException ex) {
Assert.assertTrue(ex.getMessage().contains("Invalid 'scan' argument"));
}
Boolean expResult;
boolean expResult;
Boolean result = instance.getBooleanArgument("missingArgument");
Assert.assertNull(result);

Expand Down
26 changes: 14 additions & 12 deletions core/src/main/java/org/owasp/dependencycheck/Engine.java
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
Expand Down Expand Up @@ -137,7 +138,7 @@ public class Engine implements FileFilter, AutoCloseable {
* value of this system property at runtime. We store the value to reset the
* property to its original value.
*/
private String accessExternalSchema;
private final String accessExternalSchema;

/**
* Creates a new {@link Mode#STANDALONE} Engine.
Expand Down Expand Up @@ -421,8 +422,8 @@ public List<Dependency> scan(Collection<File> files) {
public List<Dependency> scan(Collection<File> files, String projectReference) {
final List<Dependency> deps = new ArrayList<>();
files.stream().map((file) -> scan(file, projectReference))
.filter((d) -> (d != null))
.forEach((d) -> deps.addAll(d));
.filter(Objects::nonNull)
.forEach(deps::addAll);
return deps;
}

Expand Down Expand Up @@ -655,8 +656,8 @@ public void analyzeDependencies() throws ExceptionCollection {
}
}
mode.getPhases().stream()
.map((phase) -> analyzers.get(phase))
.forEach((analyzerList) -> analyzerList.forEach((a) -> closeAnalyzer(a)));
.map(analyzers::get)
.forEach((analyzerList) -> analyzerList.forEach(this::closeAnalyzer));

LOGGER.debug("\n----------------------------------------------------\nEND ANALYSIS\n----------------------------------------------------");
final long analysisDurationSeconds = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis() - analysisStart);
Expand Down Expand Up @@ -768,7 +769,7 @@ protected void executeAnalysisTasks(@NotNull final Analyzer analyzer, List<Throw
*/
protected synchronized List<AnalysisTask> getAnalysisTasks(Analyzer analyzer, List<Throwable> exceptions) {
final List<AnalysisTask> result = new ArrayList<>();
dependencies.stream().map((dependency) -> new AnalysisTask(analyzer, dependency, this, exceptions)).forEach((task) -> result.add(task));
dependencies.stream().map((dependency) -> new AnalysisTask(analyzer, dependency, this, exceptions)).forEach(result::add);
return result;
}

Expand Down Expand Up @@ -970,6 +971,7 @@ public void openDatabase() throws DatabaseException {
* opening the database
* @throws DatabaseException if the database connection could not be created
*/
@SuppressWarnings("try")
public void openDatabase(boolean readOnly, boolean lockRequired) throws DatabaseException {
if (mode.isDatabaseRequired() && database == null) {
try (WriteLock dblock = new WriteLock(getSettings(), lockRequired && DatabaseManager.isH2Connection(settings))) {
Expand All @@ -989,7 +991,7 @@ public void openDatabase(boolean readOnly, boolean lockRequired) throws Database
}
database = new CveDB(settings);
} else {
throw new DatabaseException("Unable to open database - configured database file does not exist: " + db.toString());
throw new DatabaseException("Unable to open database - configured database file does not exist: " + db);
}
} else {
database = new CveDB(settings);
Expand Down Expand Up @@ -1020,12 +1022,12 @@ public CveDB getDatabase() {
*/
@NotNull
public List<Analyzer> getAnalyzers() {
final List<Analyzer> ret = new ArrayList<>();
final List<Analyzer> analyzerList = new ArrayList<>();
//insteae of forEach - we can just do a collect
mode.getPhases().stream().map((phase) -> analyzers.get(phase)).forEachOrdered((analyzerList) -> {
ret.addAll(analyzerList);
});
return ret;
mode.getPhases().stream()
.map(analyzers::get)
.forEachOrdered(analyzerList::addAll);
return analyzerList;
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
import org.owasp.dependencycheck.data.update.exception.UpdateException;
import org.owasp.dependencycheck.dependency.Dependency;
import org.owasp.dependencycheck.dependency.Vulnerability;
import org.owasp.dependencycheck.dependency.naming.Identifier;
import org.owasp.dependencycheck.exception.ExceptionCollection;
import org.owasp.dependencycheck.exception.ReportException;
import org.owasp.dependencycheck.exception.ScanAgentException;
Expand Down Expand Up @@ -112,7 +113,7 @@ public class DependencyCheckScanAgent {
*/
private boolean updateOnly = false;
/**
* flag indicating whether or not to generate a report of findings.
* flag indicating whether to generate a report of findings.
*/
private boolean generateReport = true;
/**
Expand Down Expand Up @@ -150,7 +151,7 @@ public class DependencyCheckScanAgent {
*/
private String logFile = null;
/**
* flag indicating whether or not to show a summary of findings.
* flag indicating whether to show a summary of findings.
*/
private boolean showSummary = true;
/**
Expand All @@ -167,23 +168,23 @@ public class DependencyCheckScanAgent {
*/
private String cpeStartsWithFilter;
/**
* Whether or not the Maven Central analyzer is enabled.
* Whether the Maven Central analyzer is enabled.
*/
private boolean centralAnalyzerEnabled = true;
/**
* The URL of Maven Central.
*/
private String centralUrl;
/**
* Whether or not the nexus analyzer is enabled.
* Whether the nexus analyzer is enabled.
*/
private boolean nexusAnalyzerEnabled = true;
/**
* The URL of the Nexus server.
*/
private String nexusUrl;
/**
* Whether or not the defined proxy should be used when connecting to Nexus.
* Whether the defined proxy should be used when connecting to Nexus.
*/
private boolean nexusUsesProxy = true;
/**
Expand All @@ -199,7 +200,7 @@ public class DependencyCheckScanAgent {
*/
private String connectionString;
/**
* The user name for connecting to the database.
* The username for connecting to the database.
*/
private String databaseUser;
/**
Expand Down Expand Up @@ -916,7 +917,7 @@ private Engine executeDependencyCheck() throws ExceptionCollection {
*/
private void generateExternalReports(Engine engine, File outDirectory) throws ScanAgentException {
try {
engine.writeReports(applicationName, outDirectory, this.reportFormat.name());
engine.writeReports(applicationName, outDirectory, this.reportFormat.name(), null);
} catch (ReportException ex) {
LOGGER.debug("Unexpected exception occurred during analysis; please see the verbose error log for more details.", ex);
throw new ScanAgentException("Error generating the report", ex);
Expand Down Expand Up @@ -1044,7 +1045,7 @@ private void checkForFailure(Dependency[] dependencies) throws ScanAgentExceptio
if (showSummary) {
msg = String.format("%n%nDependency-Check Failure:%n"
+ "One or more dependencies were identified with vulnerabilities that have a CVSS score greater than or equal to '%.1f': %s%n"
+ "See the dependency-check report for more details.%n%n", failBuildOnCVSS, ids.toString());
+ "See the dependency-check report for more details.%n%n", failBuildOnCVSS, ids);
} else {
msg = String.format("%n%nDependency-Check Failure:%n"
+ "One or more dependencies were identified with vulnerabilities.%n%n"
Expand Down Expand Up @@ -1075,12 +1076,12 @@ public static void showSummary(String projectName, Dependency[] dependencies) {
final StringBuilder summary = new StringBuilder();
for (Dependency d : dependencies) {
final String ids = d.getVulnerabilities(true).stream()
.map(v -> v.getName())
.map(Vulnerability::getName)
.collect(Collectors.joining(", "));
if (ids.length() > 0) {
summary.append(d.getFileName()).append(" (");
summary.append(Stream.concat(d.getSoftwareIdentifiers().stream(), d.getVulnerableSoftwareIdentifiers().stream())
.map(i -> i.getValue())
.map(Identifier::getValue)
.collect(Collectors.joining(", ")));
summary.append(") : ").append(ids).append(NEW_LINE);
}
Expand All @@ -1089,12 +1090,12 @@ public static void showSummary(String projectName, Dependency[] dependencies) {
if (projectName == null || projectName.isEmpty()) {
LOGGER.warn("\n\nOne or more dependencies were identified with known vulnerabilities:\n\n{}\n\n"
+ "See the dependency-check report for more details.\n\n",
summary.toString());
summary);
} else {
LOGGER.warn("\n\nOne or more dependencies were identified with known vulnerabilities in {}:\n\n{}\n\n"
+ "See the dependency-check report for more details.\n\n",
projectName,
summary.toString());
summary);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ protected synchronized void analyzeDependency(Dependency ignore, Engine engine)
}
}
}
dependenciesToRemove.forEach((d) -> engine.removeDependency(d));
dependenciesToRemove.forEach(engine::removeDependency);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ protected int getRuleCount() {
*
* @return a list of file EXTENSIONS supported by this analyzer.
*/
@SuppressWarnings("SameReturnValue")
public Set<String> getSupportedExtensions() {
return null;
}
Expand Down Expand Up @@ -142,7 +143,7 @@ private void loadSuppressionData() throws SuppressionParseException {
if (!failedLoadingFiles.isEmpty()) {
LOGGER.debug("{} suppression files failed to load.", failedLoadingFiles.size());
final StringBuilder sb = new StringBuilder();
failedLoadingFiles.forEach((item) -> sb.append(item));
failedLoadingFiles.forEach(sb::append);
throw new SuppressionParseException(sb.toString());
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -586,7 +586,7 @@ private void extractArchive(ArchiveInputStream input, File destination, Engine e
//final File file = new File(destination, entry.getName());
final Path f = d.resolve(entry.getName()).normalize();
if (!f.startsWith(d)) {
LOGGER.debug("ZipSlip detected\n-Destination: " + d.toString() + "\n-Path: " + f.toString());
LOGGER.debug("ZipSlip detected\n-Destination: " + d + "\n-Path: " + f);
final String msg = String.format(
"Archive contains a file (%s) that would be extracted outside of the target directory.",
entry.getName());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -232,8 +232,7 @@ private void updateDependency(final AssemblyData data, Dependency dependency) {
}

if (data.getFileVersion() != null && data.getProductVersion() != null) {
final int max = data.getFileVersion().length() > data.getProductVersion().length()
? data.getProductVersion().length() : data.getFileVersion().length();
final int max = Math.min(data.getFileVersion().length(), data.getProductVersion().length());
int pos;
for (pos = 0; pos < max; pos++) {
if (data.getFileVersion().charAt(pos) != data.getProductVersion().charAt(pos)) {
Expand Down
Loading

0 comments on commit 21cd89b

Please sign in to comment.