From 046f4605f9abe805e6de063c885b91af6d436467 Mon Sep 17 00:00:00 2001 From: Jeremy Long Date: Fri, 10 Mar 2017 15:30:48 -0500 Subject: [PATCH] java7 updates and cleanup --- .../owasp/dependencycheck/taskdefs/Check.java | 2 +- .../owasp/dependencycheck/taskdefs/Purge.java | 6 ++++ .../java/org/owasp/dependencycheck/App.java | 12 ++++---- .../owasp/dependencycheck/AnalysisTask.java | 1 - .../org/owasp/dependencycheck/Engine.java | 24 +++++++-------- .../agent/DependencyCheckScanAgent.java | 9 ++---- .../analyzer/AbstractFileTypeAnalyzer.java | 2 +- .../analyzer/AnalyzerService.java | 2 +- .../analyzer/ArchiveAnalyzer.java | 5 +++- .../analyzer/AssemblyAnalyzer.java | 19 +++++------- .../dependencycheck/analyzer/CPEAnalyzer.java | 11 +++++-- .../analyzer/DependencyBundlingAnalyzer.java | 2 +- .../analyzer/DependencyMergingAnalyzer.java | 4 +-- .../analyzer/FalsePositiveAnalyzer.java | 2 +- .../dependencycheck/analyzer/JarAnalyzer.java | 12 ++------ .../analyzer/NuspecAnalyzer.java | 4 +-- .../analyzer/PythonDistributionAnalyzer.java | 4 +-- .../analyzer/RubyBundleAuditAnalyzer.java | 4 +-- .../data/central/CentralSearch.java | 7 +++-- .../data/composer/ComposerLockParser.java | 2 +- .../data/cpe/CpeMemoryIndex.java | 2 +- .../dependencycheck/data/cwe/CweHandler.java | 2 +- .../data/lucene/AbstractTokenizingFilter.java | 2 +- .../lucene/TokenPairConcatenatingFilter.java | 2 +- .../data/nexus/NexusSearch.java | 7 +++-- .../data/nuget/XPathNuspecParser.java | 6 +++- .../dependencycheck/data/nvdcve/CveDB.java | 12 ++++---- .../data/nvdcve/DatabaseProperties.java | 2 +- .../data/nvdcve/DriverLoader.java | 16 ++-------- .../data/nvdcve/DriverShim.java | 6 +--- .../data/update/CpeUpdater.java | 4 +-- .../data/update/NvdCveUpdater.java | 13 ++++++-- .../data/update/cpe/CPEHandler.java | 2 +- .../data/update/nvd/DownloadTask.java | 2 +- .../data/update/nvd/NvdCve12Handler.java | 4 +-- .../data/update/nvd/ProcessTask.java | 12 +------- .../data/update/nvd/UpdateableNvdCve.java | 2 +- .../dependency/Dependency.java | 6 ++-- .../dependency/EvidenceCollection.java | 30 +++++++++++-------- .../dependency/Vulnerability.java | 4 +-- .../exception/ExceptionCollection.java | 4 +-- .../utils/DependencyVersion.java | 2 +- .../utils/DependencyVersionUtil.java | 2 +- .../dependencycheck/utils/ExtractionUtil.java | 4 +-- .../utils/FileFilterBuilder.java | 10 +++---- .../owasp/dependencycheck/utils/Filter.java | 24 +++++++++++++-- .../dependencycheck/utils/UrlStringUtils.java | 4 +-- .../owasp/dependencycheck/xml/pom/Model.java | 2 +- .../dependencycheck/xml/pom/PomHandler.java | 2 +- .../xml/suppression/SuppressionHandler.java | 2 +- .../owasp/dependencycheck/BaseDBTestCase.java | 1 - .../analyzer/JarAnalyzerTest.java | 2 +- .../analyzer/RubyBundleAuditAnalyzerTest.java | 5 ++-- .../data/lucene/FieldAnalyzerTest.java | 14 ++++----- .../data/lucene/UrlTokenizingFilterTest.java | 2 +- .../data/nvdcve/ConnectionFactoryTest.java | 6 ++-- .../update/NvdCveUpdaterIntegrationTest.java | 1 - .../data/update/nvd/NvdCveInfoTest.java | 1 - .../update/nvd/NvdCve_1_2_HandlerTest.java | 1 - .../update/nvd/NvdCve_2_0_HandlerTest.java | 8 +++-- .../dependencycheck/utils/FilterTest.java | 4 +-- .../dependencycheck/xml/pom/ModelTest.java | 2 +- .../xml/suppression/SuppressionRuleTest.java | 6 ++-- .../dependencycheck/maven/AggregateMojo.java | 6 ++-- .../maven/BaseDependencyCheckMojo.java | 3 ++ .../maven/BaseDependencyCheckMojoTest.java | 5 +++- .../utils/ExpectedOjectInputStream.java | 2 +- .../utils/SSLSocketFactoryEx.java | 2 +- .../owasp/dependencycheck/utils/Settings.java | 10 ++----- .../dependencycheck/utils/DownloaderTest.java | 1 - .../utils/ExpectedOjectInputStreamTest.java | 13 ++++---- 71 files changed, 214 insertions(+), 207 deletions(-) diff --git a/dependency-check-ant/src/main/java/org/owasp/dependencycheck/taskdefs/Check.java b/dependency-check-ant/src/main/java/org/owasp/dependencycheck/taskdefs/Check.java index 83b344907..97f53611b 100644 --- a/dependency-check-ant/src/main/java/org/owasp/dependencycheck/taskdefs/Check.java +++ b/dependency-check-ant/src/main/java/org/owasp/dependencycheck/taskdefs/Check.java @@ -942,7 +942,7 @@ public class Check extends Update { } } DatabaseProperties prop = null; - CveDB cve = null; + CveDB cve; try { cve = CveDB.getInstance(); prop = cve.getDatabaseProperties(); diff --git a/dependency-check-ant/src/main/java/org/owasp/dependencycheck/taskdefs/Purge.java b/dependency-check-ant/src/main/java/org/owasp/dependencycheck/taskdefs/Purge.java index 3bc335fb0..2169baaac 100644 --- a/dependency-check-ant/src/main/java/org/owasp/dependencycheck/taskdefs/Purge.java +++ b/dependency-check-ant/src/main/java/org/owasp/dependencycheck/taskdefs/Purge.java @@ -95,6 +95,12 @@ public class Purge extends Task { this.failOnError = failOnError; } + /** + * Executes the dependency-check purge to delete the existing local copy of + * the NVD CVE data. + * + * @throws BuildException thrown if there is a problem deleting the file(s) + */ @Override public void execute() throws BuildException { populateSettings(); diff --git a/dependency-check-cli/src/main/java/org/owasp/dependencycheck/App.java b/dependency-check-cli/src/main/java/org/owasp/dependencycheck/App.java index 7b6d8d354..e01b729d4 100644 --- a/dependency-check-cli/src/main/java/org/owasp/dependencycheck/App.java +++ b/dependency-check-cli/src/main/java/org/owasp/dependencycheck/App.java @@ -223,13 +223,13 @@ public class App { int retCode = 0; try { engine = new Engine(); - final List antStylePaths = new ArrayList(); + final List antStylePaths = new ArrayList<>(); for (String file : files) { final String antPath = ensureCanonicalPath(file); antStylePaths.add(antPath); } - final Set paths = new HashSet(); + final Set paths = new HashSet<>(); for (String file : antStylePaths) { LOGGER.debug("Scanning {}", file); final DirectoryScanner scanner = new DirectoryScanner(); @@ -282,10 +282,8 @@ public class App { exCol = ex; } final List dependencies = engine.getDependencies(); - DatabaseProperties prop = null; - CveDB cve = null; - cve = CveDB.getInstance(); - prop = cve.getDatabaseProperties(); + CveDB cve = CveDB.getInstance(); + DatabaseProperties prop = cve.getDatabaseProperties(); final ReportGenerator report = new ReportGenerator(applicationName, dependencies, engine.getAnalyzers(), prop); try { report.generateReports(reportDirectory, outputFormat); @@ -461,7 +459,7 @@ public class App { encoder.setPattern("%d %C:%L%n%-5level - %msg%n"); encoder.setContext(context); encoder.start(); - final FileAppender fa = new FileAppender(); + final FileAppender fa = new FileAppender<>(); fa.setAppend(true); fa.setEncoder(encoder); fa.setContext(context); diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/AnalysisTask.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/AnalysisTask.java index ef1e00372..7f96e269c 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/AnalysisTask.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/AnalysisTask.java @@ -86,7 +86,6 @@ public class AnalysisTask implements Callable { * Executes the analysis task. * * @return null - * @throws Exception thrown if unable to execute the analysis task */ @Override public Void call() { diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/Engine.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/Engine.java index f39e345ef..506341a0a 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/Engine.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/Engine.java @@ -76,7 +76,7 @@ public class Engine implements FileFilter { /** * A Map of analyzers grouped by Analysis phase. */ - private final Set fileTypeAnalyzers = new HashSet(); + private final Set fileTypeAnalyzers = new HashSet<>(); /** * The ClassLoader to use when dynamically loading Analyzer and Update @@ -145,7 +145,7 @@ public class Engine implements FileFilter { for (AnalysisPhase phase : AnalysisPhase.values()) { analyzers.put(phase, new ArrayList()); } - + final AnalyzerService service = new AnalyzerService(serviceClassLoader); final List iterator = service.getAnalyzers(); for (Analyzer a : iterator) { @@ -281,7 +281,7 @@ public class Engine implements FileFilter { * @since v1.4.4 */ public List scan(File[] files, String projectReference) { - final List deps = new ArrayList(); + final List deps = new ArrayList<>(); for (File file : files) { final List d = scan(file, projectReference); if (d != null) { @@ -316,7 +316,7 @@ public class Engine implements FileFilter { * @since v1.4.4 */ public List scan(Collection files, String projectReference) { - final List deps = new ArrayList(); + final List deps = new ArrayList<>(); for (File file : files) { final List d = scan(file, projectReference); if (d != null) { @@ -357,7 +357,7 @@ public class Engine implements FileFilter { } else { final Dependency d = scanFile(file, projectReference); if (d != null) { - final List deps = new ArrayList(); + final List deps = new ArrayList<>(); deps.add(d); return deps; } @@ -509,7 +509,7 @@ public class Engine implements FileFilter { } catch (DatabaseException ex) { throwFatalExceptionCollection("Unable to connect to the dependency-check database.", ex, exceptions); } - + LOGGER.debug("\n----------------------------------------------------\nBEGIN ANALYSIS\n----------------------------------------------------"); LOGGER.info("Analysis Started"); final long analysisStart = System.currentTimeMillis(); @@ -517,7 +517,7 @@ public class Engine implements FileFilter { // analysis phases for (AnalysisPhase phase : AnalysisPhase.values()) { final List analyzerList = analyzers.get(phase); - + for (final Analyzer analyzer : analyzerList) { final long analyzerStart = System.currentTimeMillis(); try { @@ -526,10 +526,10 @@ public class Engine implements FileFilter { exceptions.add(ex); continue; } - + if (analyzer.isEnabled()) { executeAnalysisTasks(analyzer, exceptions); - + final long analyzerDurationMillis = System.currentTimeMillis() - analyzerStart; final long analyzerDurationSeconds = TimeUnit.MILLISECONDS.toSeconds(analyzerDurationMillis); LOGGER.info("Finished {} ({} seconds)", analyzer.getName(), analyzerDurationSeconds); @@ -540,12 +540,12 @@ public class Engine implements FileFilter { } for (AnalysisPhase phase : AnalysisPhase.values()) { final List analyzerList = analyzers.get(phase); - + for (Analyzer a : analyzerList) { closeAnalyzer(a); } } - + LOGGER.debug("\n----------------------------------------------------\nEND ANALYSIS\n----------------------------------------------------"); final long analysisDurationSeconds = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis() - analysisStart); LOGGER.info("Analysis Complete ({} seconds)", analysisDurationSeconds); @@ -566,7 +566,7 @@ public class Engine implements FileFilter { LOGGER.debug("Starting {}", analyzer.getName()); final List analysisTasks = getAnalysisTasks(analyzer, exceptions); final ExecutorService executorService = getExecutorService(analyzer); - + try { final List> results = executorService.invokeAll(analysisTasks, 10, TimeUnit.MINUTES); diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/agent/DependencyCheckScanAgent.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/agent/DependencyCheckScanAgent.java index 1cc6cf539..eafdb7b1e 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/agent/DependencyCheckScanAgent.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/agent/DependencyCheckScanAgent.java @@ -28,6 +28,7 @@ import org.owasp.dependencycheck.dependency.Dependency; import org.owasp.dependencycheck.dependency.Identifier; import org.owasp.dependencycheck.dependency.Vulnerability; import org.owasp.dependencycheck.exception.ExceptionCollection; +import org.owasp.dependencycheck.exception.ReportException; import org.owasp.dependencycheck.exception.ScanAgentException; import org.owasp.dependencycheck.reporting.ReportGenerator; import org.owasp.dependencycheck.utils.Settings; @@ -842,7 +843,7 @@ public class DependencyCheckScanAgent { */ private void generateExternalReports(Engine engine, File outDirectory) { DatabaseProperties prop = null; - CveDB cve = null; + CveDB cve; try { cve = CveDB.getInstance(); prop = cve.getDatabaseProperties(); @@ -853,13 +854,9 @@ public class DependencyCheckScanAgent { final ReportGenerator r = new ReportGenerator(this.applicationName, engine.getDependencies(), engine.getAnalyzers(), prop); try { r.generateReports(outDirectory.getCanonicalPath(), this.reportFormat.name()); - } catch (IOException ex) { + } catch (IOException | ReportException ex) { LOGGER.error("Unexpected exception occurred during analysis; please see the verbose error log for more details."); LOGGER.debug("", ex); - } catch (Throwable ex) { - LOGGER.error( - "Unexpected exception occurred during analysis; please see the verbose error log for more details."); - LOGGER.debug("", ex); } } diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/AbstractFileTypeAnalyzer.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/AbstractFileTypeAnalyzer.java index e55cf0307..74e87bd0e 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/AbstractFileTypeAnalyzer.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/AbstractFileTypeAnalyzer.java @@ -141,7 +141,7 @@ public abstract class AbstractFileTypeAnalyzer extends AbstractAnalyzer implemen * @return a Set of strings. */ protected static Set newHashSet(String... strings) { - final Set set = new HashSet(strings.length); + final Set set = new HashSet<>(strings.length); Collections.addAll(set, strings); return set; } diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/AnalyzerService.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/AnalyzerService.java index e27f95649..5b786b0fc 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/AnalyzerService.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/AnalyzerService.java @@ -57,7 +57,7 @@ public class AnalyzerService { * @return a list of Analyzers. */ public List getAnalyzers() { - final List analyzers = new ArrayList(); + final List analyzers = new ArrayList<>(); final Iterator iterator = service.iterator(); boolean experimentalEnabled = false; try { diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/ArchiveAnalyzer.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/ArchiveAnalyzer.java index 4298ec5ff..001d80a8d 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/ArchiveAnalyzer.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/ArchiveAnalyzer.java @@ -105,6 +105,7 @@ public class ArchiveAnalyzer extends AbstractFileTypeAnalyzer { * in {@link #extractFiles(File, File, Engine)}. */ private static final Set EXTENSIONS = newHashSet("tar", "gz", "tgz", "bz2", "tbz2"); + static { final String additionalZipExt = Settings.getString(Settings.KEYS.ADDITIONAL_ZIP_EXTENSIONS); if (additionalZipExt != null) { @@ -220,6 +221,8 @@ public class ArchiveAnalyzer extends AbstractFileTypeAnalyzer { * Does not support parallel processing as it both modifies and iterates * over the engine's list of dependencies. * + * @return true if the analyzer supports parallel processing; + * otherwise false * @see #analyzeDependency(Dependency, Engine) * @see #findMoreDependencies(Engine, File) */ @@ -517,7 +520,7 @@ public class ArchiveAnalyzer extends AbstractFileTypeAnalyzer { extractAcceptedFile(input, file); } } - } catch (Throwable ex) { + } catch (IOException | AnalysisException ex) { throw new ArchiveExtractionException(ex); } finally { FileUtils.close(input); diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/AssemblyAnalyzer.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/AssemblyAnalyzer.java index 348dd6f6c..824bb58b9 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/AssemblyAnalyzer.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/AssemblyAnalyzer.java @@ -84,7 +84,7 @@ public class AssemblyAnalyzer extends AbstractFileTypeAnalyzer { */ protected List buildArgumentList() { // Use file.separator as a wild guess as to whether this is Windows - final List args = new ArrayList(); + final List args = new ArrayList<>(); if (!SystemUtils.IS_OS_WINDOWS) { if (Settings.getString(Settings.KEYS.ANALYZER_ASSEMBLY_MONO_PATH) != null) { args.add(Settings.getString(Settings.KEYS.ANALYZER_ASSEMBLY_MONO_PATH)); @@ -176,18 +176,17 @@ public class AssemblyAnalyzer extends AbstractFileTypeAnalyzer { } catch (ParserConfigurationException pce) { throw new AnalysisException("Error initializing the assembly analyzer", pce); - } catch (IOException ioe) { + } catch (IOException | XPathExpressionException ioe) { throw new AnalysisException(ioe); - } catch (SAXException saxe) { + }catch (SAXException saxe) { LOGGER.error("----------------------------------------------------"); LOGGER.error("Failed to read the Assembly Analyzer results. " + "On some systems mono-runtime and mono-devel need to be installed."); LOGGER.error("----------------------------------------------------"); throw new AnalysisException("Couldn't parse Assembly Analzyzer results (GrokAssembly)", saxe); - } catch (XPathExpressionException xpe) { - // This shouldn't happen - throw new AnalysisException(xpe); } + // This shouldn't happen + } /** @@ -280,7 +279,7 @@ public class AssemblyAnalyzer extends AbstractFileTypeAnalyzer { } catch (InitializationException e) { setEnabled(false); throw e; - } catch (Throwable e) { + } catch (IOException | ParserConfigurationException | SAXException | XPathExpressionException | InterruptedException e) { LOGGER.warn("An error occurred with the .NET AssemblyAnalyzer;\n" + "this can be ignored unless you are scanning .NET DLLs. Please see the log for more details."); LOGGER.debug("Could not execute GrokAssembly {}", e.getMessage()); @@ -366,10 +365,8 @@ public class AssemblyAnalyzer extends AbstractFileTypeAnalyzer { if (retCode == 0) { return true; } - } catch (IOException ex) { - LOGGER.debug("Path seach failed for " + file); - } catch (InterruptedException ex) { - LOGGER.debug("Path seach failed for " + file); + } catch (IOException | InterruptedException ex) { + LOGGER.debug("Path seach failed for " + file, ex); } return false; } diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/CPEAnalyzer.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/CPEAnalyzer.java index c88f8c102..5e4d82f87 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/CPEAnalyzer.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/CPEAnalyzer.java @@ -188,6 +188,11 @@ public class CPEAnalyzer extends AbstractAnalyzer { } } + /** + * Returns whether or not the analyzer is open. + * + * @return true if the analyzer is open + */ public boolean isOpen() { return cpe != null && cpe.isOpen(); } @@ -291,7 +296,7 @@ public class CPEAnalyzer extends AbstractAnalyzer { protected List searchCPE(String vendor, String product, Set vendorWeightings, Set productWeightings) { - final List ret = new ArrayList(MAX_QUERY_RESULTS); + final List ret = new ArrayList<>(MAX_QUERY_RESULTS); final String searchString = buildSearch(vendor, product, vendorWeightings, productWeightings); if (searchString == null) { @@ -477,7 +482,7 @@ public class CPEAnalyzer extends AbstractAnalyzer { return false; } final String[] words = text.split("[\\s_-]"); - final List list = new ArrayList(); + final List list = new ArrayList<>(); String tempWord = null; for (String word : words) { /* @@ -555,7 +560,7 @@ public class CPEAnalyzer extends AbstractAnalyzer { DependencyVersion bestGuess = new DependencyVersion("-"); Confidence bestGuessConf = null; boolean hasBroadMatch = false; - final List collected = new ArrayList(); + final List collected = new ArrayList<>(); //TODO the following algorithm incorrectly identifies things as a lower version // if there lower confidence evidence when the current (highest) version number diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/DependencyBundlingAnalyzer.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/DependencyBundlingAnalyzer.java index 72c8e95ea..c27e69f8b 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/DependencyBundlingAnalyzer.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/DependencyBundlingAnalyzer.java @@ -145,7 +145,7 @@ public class DependencyBundlingAnalyzer extends AbstractAnalyzer { protected synchronized void analyzeDependency(Dependency ignore, Engine engine) throws AnalysisException { if (!analyzed) { analyzed = true; - final Set dependenciesToRemove = new HashSet(); + final Set dependenciesToRemove = new HashSet<>(); final ListIterator mainIterator = engine.getDependencies().listIterator(); //for (Dependency nextDependency : engine.getDependencies()) { while (mainIterator.hasNext()) { diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/DependencyMergingAnalyzer.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/DependencyMergingAnalyzer.java index 3328a8602..a2f88542e 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/DependencyMergingAnalyzer.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/DependencyMergingAnalyzer.java @@ -129,7 +129,7 @@ public class DependencyMergingAnalyzer extends AbstractAnalyzer { protected synchronized void analyzeDependency(Dependency ignore, Engine engine) throws AnalysisException { if (!analyzed) { analyzed = true; - final Set dependenciesToRemove = new HashSet(); + final Set dependenciesToRemove = new HashSet<>(); final ListIterator mainIterator = engine.getDependencies().listIterator(); //for (Dependency nextDependency : engine.getDependencies()) { while (mainIterator.hasNext()) { @@ -138,7 +138,7 @@ public class DependencyMergingAnalyzer extends AbstractAnalyzer { final ListIterator subIterator = engine.getDependencies().listIterator(mainIterator.nextIndex()); while (subIterator.hasNext()) { final Dependency nextDependency = subIterator.next(); - Dependency main = null; + Dependency main; if ((main = getMainGemspecDependency(dependency, nextDependency)) != null) { if (main == dependency) { mergeDependencies(dependency, nextDependency, dependenciesToRemove); diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/FalsePositiveAnalyzer.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/FalsePositiveAnalyzer.java index 1b9dbe43f..df50edb21 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/FalsePositiveAnalyzer.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/FalsePositiveAnalyzer.java @@ -173,7 +173,7 @@ public class FalsePositiveAnalyzer extends AbstractAnalyzer { */ @SuppressWarnings("null") private void removeSpuriousCPE(Dependency dependency) { - final List ids = new ArrayList(dependency.getIdentifiers()); + final List ids = new ArrayList<>(dependency.getIdentifiers()); Collections.sort(ids); final ListIterator mainItr = ids.listIterator(); while (mainItr.hasNext()) { diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/JarAnalyzer.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/JarAnalyzer.java index 4374aa80d..af3af0032 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/JarAnalyzer.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/JarAnalyzer.java @@ -255,7 +255,7 @@ public class JarAnalyzer extends AbstractFileTypeAnalyzer { */ protected boolean analyzePOM(Dependency dependency, List classes, Engine engine) throws AnalysisException { JarFile jar = null; - List pomEntries = null; + List pomEntries; try { jar = new JarFile(dependency.getActualFilePath()); pomEntries = retrievePomListing(jar); @@ -636,9 +636,7 @@ public class JarAnalyzer extends AbstractFileTypeAnalyzer { protected boolean parseManifest(Dependency dependency, List classInformation) throws IOException { boolean foundSomething = false; - JarFile jar = null; - try { - jar = new JarFile(dependency.getActualFilePath()); + try (JarFile jar = new JarFile(dependency.getActualFilePath())) { final Manifest manifest = jar.getManifest(); if (manifest == null) { if (!dependency.getFileName().toLowerCase().endsWith("-sources.jar") @@ -793,10 +791,6 @@ public class JarAnalyzer extends AbstractFileTypeAnalyzer { foundSomething = true; versionEvidence.addEvidence(source, "specification-version", specificationVersion, Confidence.HIGH); } - } finally { - if (jar != null) { - jar.close(); - } } return foundSomething; } @@ -1124,7 +1118,7 @@ public class JarAnalyzer extends AbstractFileTypeAnalyzer { * Up to the first four levels of the package structure, excluding a * leading "org" or "com". */ - private final ArrayList packageStructure = new ArrayList(); + private final ArrayList packageStructure = new ArrayList<>(); /** *

diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/NuspecAnalyzer.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/NuspecAnalyzer.java index 2d6fd1993..46e74f968 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/NuspecAnalyzer.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/NuspecAnalyzer.java @@ -136,9 +136,7 @@ public class NuspecAnalyzer extends AbstractFileTypeAnalyzer { try { fis = new FileInputStream(dependency.getActualFilePath()); np = parser.parse(fis); - } catch (NuspecParseException ex) { - throw new AnalysisException(ex); - } catch (FileNotFoundException ex) { + } catch (NuspecParseException | FileNotFoundException ex) { throw new AnalysisException(ex); } finally { if (fis != null) { diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/PythonDistributionAnalyzer.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/PythonDistributionAnalyzer.java index 578c8d8f4..23d5c9bc7 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/PythonDistributionAnalyzer.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/PythonDistributionAnalyzer.java @@ -364,9 +364,7 @@ public class PythonDistributionAnalyzer extends AbstractFileTypeAnalyzer { try { in = new BufferedInputStream(new FileInputStream(manifest)); result.load(in); - } catch (MessagingException e) { - LOGGER.warn(e.getMessage(), e); - } catch (FileNotFoundException e) { + } catch (MessagingException | FileNotFoundException e) { LOGGER.warn(e.getMessage(), e); } finally { if (in != null) { diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/RubyBundleAuditAnalyzer.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/RubyBundleAuditAnalyzer.java index e44aa6b45..b52adb255 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/RubyBundleAuditAnalyzer.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/RubyBundleAuditAnalyzer.java @@ -113,7 +113,7 @@ public class RubyBundleAuditAnalyzer extends AbstractFileTypeAnalyzer { if (!folder.isDirectory()) { throw new AnalysisException(String.format("%s should have been a directory.", folder.getAbsolutePath())); } - final List args = new ArrayList(); + final List args = new ArrayList<>(); final String bundleAuditPath = Settings.getString(Settings.KEYS.ANALYZER_BUNDLE_AUDIT_PATH); File bundleAudit = null; if (bundleAuditPath != null) { @@ -342,7 +342,7 @@ public class RubyBundleAuditAnalyzer extends AbstractFileTypeAnalyzer { Dependency dependency = null; Vulnerability vulnerability = null; String gem = null; - final Map map = new HashMap(); + final Map map = new HashMap<>(); boolean appendToDescription = false; while (rdr.ready()) { final String nextLine = rdr.readLine(); diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/central/CentralSearch.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/central/CentralSearch.java index 5f3cfc420..09abaa2bc 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/central/CentralSearch.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/central/CentralSearch.java @@ -24,8 +24,10 @@ import java.net.URL; import java.util.ArrayList; import java.util.List; import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; +import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.owasp.dependencycheck.data.nexus.MavenArtifact; import org.owasp.dependencycheck.utils.Settings; @@ -35,6 +37,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.NodeList; +import org.xml.sax.SAXException; /** * Class of methods to search Maven Central via Central. @@ -117,7 +120,7 @@ public class CentralSearch { if ("0".equals(numFound)) { missing = true; } else { - result = new ArrayList(); + result = new ArrayList<>(); final NodeList docs = (NodeList) xpath.evaluate("/response/result/doc", doc, XPathConstants.NODESET); for (int i = 0; i < docs.getLength(); i++) { final String g = xpath.evaluate("./str[@name='g']", docs.item(i)); @@ -149,7 +152,7 @@ public class CentralSearch { result.add(new MavenArtifact(g, a, v, jarAvailable, pomAvailable, useHTTPS)); } } - } catch (Throwable e) { + } catch (ParserConfigurationException | IOException | SAXException | XPathExpressionException e) { // Anything else is jacked up XML stuff that we really can't recover from well throw new IOException(e.getMessage(), e); } diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/composer/ComposerLockParser.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/composer/ComposerLockParser.java index 289163763..43971bd30 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/composer/ComposerLockParser.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/composer/ComposerLockParser.java @@ -66,7 +66,7 @@ public class ComposerLockParser { LOGGER.info("Creating a ComposerLockParser"); this.inputStream = inputStream; this.jsonReader = Json.createReader(inputStream); - this.composerDependencies = new ArrayList(); + this.composerDependencies = new ArrayList<>(); } /** diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/cpe/CpeMemoryIndex.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/cpe/CpeMemoryIndex.java index 3100c5ebc..5776f7e55 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/cpe/CpeMemoryIndex.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/cpe/CpeMemoryIndex.java @@ -149,7 +149,7 @@ public final class CpeMemoryIndex { * @return the CPE Analyzer. */ private Analyzer createSearchingAnalyzer() { - final Map fieldAnalyzers = new HashMap(); + final Map fieldAnalyzers = new HashMap<>(); fieldAnalyzers.put(Fields.DOCUMENT_KEY, new KeywordAnalyzer()); productFieldAnalyzer = new SearchFieldAnalyzer(LuceneUtils.CURRENT_VERSION); vendorFieldAnalyzer = new SearchFieldAnalyzer(LuceneUtils.CURRENT_VERSION); diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/cwe/CweHandler.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/cwe/CweHandler.java index e0d948b57..894aed93a 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/cwe/CweHandler.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/cwe/CweHandler.java @@ -32,7 +32,7 @@ public class CweHandler extends DefaultHandler { /** * a HashMap containing the CWE data. */ - private final HashMap cwe = new HashMap(); + private final HashMap cwe = new HashMap<>(); /** * Returns the HashMap of CWE entries (CWE-ID, Full CWE Name). diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/lucene/AbstractTokenizingFilter.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/lucene/AbstractTokenizingFilter.java index 2a0b20d6a..25e943378 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/lucene/AbstractTokenizingFilter.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/lucene/AbstractTokenizingFilter.java @@ -63,7 +63,7 @@ public abstract class AbstractTokenizingFilter extends TokenFilter { */ public AbstractTokenizingFilter(TokenStream stream) { super(stream); - tokens = new LinkedList(); + tokens = new LinkedList<>(); } /** diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/lucene/TokenPairConcatenatingFilter.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/lucene/TokenPairConcatenatingFilter.java index 4b36d3e01..22f6f369a 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/lucene/TokenPairConcatenatingFilter.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/lucene/TokenPairConcatenatingFilter.java @@ -71,7 +71,7 @@ public final class TokenPairConcatenatingFilter extends TokenFilter { */ public TokenPairConcatenatingFilter(TokenStream stream) { super(stream); - words = new LinkedList(); + words = new LinkedList<>(); } /** diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/nexus/NexusSearch.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/nexus/NexusSearch.java index c7f6b790b..09567475f 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/nexus/NexusSearch.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/nexus/NexusSearch.java @@ -22,7 +22,9 @@ import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.XPath; +import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.owasp.dependencycheck.utils.URLConnectionFactory; @@ -30,6 +32,7 @@ import org.owasp.dependencycheck.utils.XmlUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; +import org.xml.sax.SAXException; /** * Class of methods to search Nexus repositories. @@ -132,7 +135,7 @@ public class NexusSearch { ma.setPomUrl(pomLink); } return ma; - } catch (Throwable e) { + } catch (ParserConfigurationException | IOException | SAXException | XPathExpressionException e) { // Anything else is jacked-up XML stuff that we really can't recover // from well throw new IOException(e.getMessage(), e); @@ -170,7 +173,7 @@ public class NexusSearch { LOGGER.warn("Expected root node name of status, got {}", doc.getDocumentElement().getNodeName()); return false; } - } catch (Throwable e) { + } catch (IOException | ParserConfigurationException | SAXException e) { return false; } diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/nuget/XPathNuspecParser.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/nuget/XPathNuspecParser.java index bbf2ecd1d..fa91cb73f 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/nuget/XPathNuspecParser.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/nuget/XPathNuspecParser.java @@ -17,14 +17,18 @@ */ package org.owasp.dependencycheck.data.nuget; +import java.io.IOException; import java.io.InputStream; import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; +import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.owasp.dependencycheck.utils.XmlUtils; import org.w3c.dom.Document; import org.w3c.dom.Node; +import org.xml.sax.SAXException; /** * Parse a Nuspec file using XPath. @@ -78,7 +82,7 @@ public class XPathNuspecParser implements NuspecParser { nuspec.setLicenseUrl(getOrNull((Node) xpath.evaluate("/package/metadata/licenseUrl", d, XPathConstants.NODE))); nuspec.setTitle(getOrNull((Node) xpath.evaluate("/package/metadata/title", d, XPathConstants.NODE))); return nuspec; - } catch (Throwable e) { + } catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException | NuspecParseException e) { throw new NuspecParseException("Unable to parse nuspec", e); } } diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/nvdcve/CveDB.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/nvdcve/CveDB.java index 650f84a34..355ae4a32 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/nvdcve/CveDB.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/nvdcve/CveDB.java @@ -228,7 +228,7 @@ public final class CveDB { private EnumMap prepareStatements() throws DatabaseException { - final EnumMap result = new EnumMap(PreparedStatementCveDb.class); + final EnumMap result = new EnumMap<>(PreparedStatementCveDb.class); for (PreparedStatementCveDb key : values()) { final String statementString = statementBundle.getString(key.name()); final PreparedStatement preparedStatement; @@ -777,7 +777,7 @@ public final class CveDB { final boolean isVersionTwoADifferentProduct = "apache".equals(vendor) && "struts".equals(product); - final Set majorVersionsAffectingAllPrevious = new HashSet(); + final Set majorVersionsAffectingAllPrevious = new HashSet<>(); final boolean matchesAnyPrevious = identifiedVersion == null || "-".equals(identifiedVersion.toString()); String majorVersionMatch = null; for (Entry entry : vulnerableSoftware.entrySet()) { @@ -806,12 +806,12 @@ public final class CveDB { if (!entry.getValue()) { final DependencyVersion v = parseDependencyVersion(entry.getKey()); //this can't dereference a null 'majorVersionMatch' as canSkipVersions accounts for this. - if (canSkipVersions && !majorVersionMatch.equals(v.getVersionParts().get(0))) { + if (canSkipVersions && majorVersionMatch != null && !majorVersionMatch.equals(v.getVersionParts().get(0))) { continue; } //this can't dereference a null 'identifiedVersion' because if it was null we would have exited //in the above loop or just after loop (if matchesAnyPrevious return null). - if (identifiedVersion.equals(v)) { + if (identifiedVersion != null && identifiedVersion.equals(v)) { return entry; } } @@ -820,12 +820,12 @@ public final class CveDB { if (entry.getValue()) { final DependencyVersion v = parseDependencyVersion(entry.getKey()); //this can't dereference a null 'majorVersionMatch' as canSkipVersions accounts for this. - if (canSkipVersions && !majorVersionMatch.equals(v.getVersionParts().get(0))) { + if (canSkipVersions && majorVersionMatch != null && !majorVersionMatch.equals(v.getVersionParts().get(0))) { continue; } //this can't dereference a null 'identifiedVersion' because if it was null we would have exited //in the above loop or just after loop (if matchesAnyPrevious return null). - if (entry.getValue() && identifiedVersion.compareTo(v) <= 0) { + if (entry.getValue() && identifiedVersion != null && identifiedVersion.compareTo(v) <= 0) { if (!(isVersionTwoADifferentProduct && !identifiedVersion.getVersionParts().get(0).equals(v.getVersionParts().get(0)))) { return entry; } diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/nvdcve/DatabaseProperties.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/nvdcve/DatabaseProperties.java index a3b2aa86c..ea690ba75 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/nvdcve/DatabaseProperties.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/nvdcve/DatabaseProperties.java @@ -166,7 +166,7 @@ public class DatabaseProperties { * @return a map of the database meta data */ public Map getMetaData() { - final Map map = new TreeMap(); + final Map map = new TreeMap<>(); for (Entry entry : properties.entrySet()) { final String key = (String) entry.getKey(); if (!"version".equals(key)) { diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/nvdcve/DriverLoader.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/nvdcve/DriverLoader.java index c2f792bc7..1c61fcde9 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/nvdcve/DriverLoader.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/nvdcve/DriverLoader.java @@ -75,7 +75,7 @@ public final class DriverLoader { */ public static Driver load(String className, String pathToDriver) throws DriverLoadException { final URLClassLoader parent = (URLClassLoader) ClassLoader.getSystemClassLoader(); - final List urls = new ArrayList(); + final List urls = new ArrayList<>(); final String[] paths = pathToDriver.split(File.pathSeparator); for (String path : paths) { final File file = new File(path); @@ -129,19 +129,7 @@ public final class DriverLoader { //using the DriverShim to get around the fact that the DriverManager won't register a driver not in the base class path DriverManager.registerDriver(shim); return shim; - } catch (ClassNotFoundException ex) { - final String msg = String.format("Unable to load database driver '%s'", className); - LOGGER.debug(msg, ex); - throw new DriverLoadException(msg, ex); - } catch (InstantiationException ex) { - final String msg = String.format("Unable to load database driver '%s'", className); - LOGGER.debug(msg, ex); - throw new DriverLoadException(msg, ex); - } catch (IllegalAccessException ex) { - final String msg = String.format("Unable to load database driver '%s'", className); - LOGGER.debug(msg, ex); - throw new DriverLoadException(msg, ex); - } catch (SQLException ex) { + } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException ex) { final String msg = String.format("Unable to load database driver '%s'", className); LOGGER.debug(msg, ex); throw new DriverLoadException(msg, ex); diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/nvdcve/DriverShim.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/nvdcve/DriverShim.java index acd289498..9d5f04ff0 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/nvdcve/DriverShim.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/nvdcve/DriverShim.java @@ -126,11 +126,7 @@ class DriverShim implements Driver { if (m != null) { try { return (java.util.logging.Logger) m.invoke(m); - } catch (IllegalAccessException ex) { - LOGGER.trace("", ex); - } catch (IllegalArgumentException ex) { - LOGGER.trace("", ex); - } catch (InvocationTargetException ex) { + } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) { LOGGER.trace("", ex); } } diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/update/CpeUpdater.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/update/CpeUpdater.java index fbca59444..c55bb5225 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/update/CpeUpdater.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/update/CpeUpdater.java @@ -16,7 +16,7 @@ * Copyright (c) 2015 Jeremy Long. All Rights Reserved. */ package org.owasp.dependencycheck.data.update; - +/* import java.io.File; import java.io.IOException; import java.net.MalformedURLException; @@ -37,7 +37,7 @@ import org.owasp.dependencycheck.utils.XmlUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xml.sax.SAXException; - +*/ /** * * This class is currently unused and if enabled will likely not work on MySQL diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/update/NvdCveUpdater.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/update/NvdCveUpdater.java index d86583af1..61053ee72 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/update/NvdCveUpdater.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/update/NvdCveUpdater.java @@ -24,13 +24,13 @@ import java.util.HashSet; import java.util.Map; import java.util.Set; import java.net.URL; -import java.util.Properties; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; import org.owasp.dependencycheck.data.nvdcve.CveDB; import org.owasp.dependencycheck.data.nvdcve.DatabaseException; import org.owasp.dependencycheck.data.nvdcve.DatabaseProperties; @@ -136,6 +136,10 @@ public class NvdCveUpdater implements CachedWebDataSource { } } + /** + * Initialize the executor services for download and processing of the NVD + * CVE XML data. + */ protected void initializeExecutorServices() { processingExecutorService = Executors.newFixedThreadPool(PROCESSING_THREAD_POOL_SIZE); downloadExecutorService = Executors.newFixedThreadPool(DOWNLOAD_THREAD_POOL_SIZE); @@ -143,6 +147,9 @@ public class NvdCveUpdater implements CachedWebDataSource { LOGGER.debug("#processing threads: {}", PROCESSING_THREAD_POOL_SIZE); } + /** + * Shutdown and cleanup of resources used by the executor services. + */ private void shutdownExecutorServices() { if (processingExecutorService != null) { processingExecutorService.shutdownNow(); @@ -427,7 +434,7 @@ public class NvdCveUpdater implements CachedWebDataSource { final long timestamp; try { timestamp = timestampFuture.get(60, TimeUnit.SECONDS); - } catch (Exception e) { + } catch (InterruptedException | ExecutionException | TimeoutException e) { throw new DownloadFailedException(e); } lastModifiedDates.put(url, timestamp); @@ -441,7 +448,7 @@ public class NvdCveUpdater implements CachedWebDataSource { */ private static class TimestampRetriever implements Callable { - private String url; + private final String url; TimestampRetriever(String url) { this.url = url; diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/update/cpe/CPEHandler.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/update/cpe/CPEHandler.java index 4c778e7b2..54870e859 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/update/cpe/CPEHandler.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/update/cpe/CPEHandler.java @@ -60,7 +60,7 @@ public class CPEHandler extends DefaultHandler { /** * The list of CPE values. */ - private final List data = new ArrayList(); + private final List data = new ArrayList<>(); /** * Returns the list of CPE values. diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/update/nvd/DownloadTask.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/update/nvd/DownloadTask.java index 59eb331a4..973b6798e 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/update/nvd/DownloadTask.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/update/nvd/DownloadTask.java @@ -229,7 +229,7 @@ public class DownloadTask implements Callable> { is = new FileInputStream(file); final byte[] buf = new byte[5]; - int read = 0; + int read; try { read = is.read(buf); } catch (IOException ex) { diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/update/nvd/NvdCve12Handler.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/update/nvd/NvdCve12Handler.java index c47d5ddde..7adfbb18c 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/update/nvd/NvdCve12Handler.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/update/nvd/NvdCve12Handler.java @@ -93,7 +93,7 @@ public class NvdCve12Handler extends DefaultHandler { skip = "1".equals(reject); if (!skip) { vulnerability = attributes.getValue("name"); - software = new ArrayList(); + software = new ArrayList<>(); } else { vulnerability = null; software = null; @@ -132,7 +132,7 @@ public class NvdCve12Handler extends DefaultHandler { if (!CURRENT_SCHEMA_VERSION.equals(nvdVer)) { throw new SAXNotSupportedException("Schema version " + nvdVer + " is not supported"); } - vulnerabilities = new HashMap>(); + vulnerabilities = new HashMap<>(); } } diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/update/nvd/ProcessTask.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/update/nvd/ProcessTask.java index 20f64e804..4054b7344 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/update/nvd/ProcessTask.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/update/nvd/ProcessTask.java @@ -169,17 +169,7 @@ public class ProcessTask implements Callable { properties.save(filePair.getNvdCveInfo()); } catch (FileNotFoundException ex) { throw new UpdateException(ex); - } catch (ParserConfigurationException ex) { - throw new UpdateException(ex); - } catch (SAXException ex) { - throw new UpdateException(ex); - } catch (IOException ex) { - throw new UpdateException(ex); - } catch (SQLException ex) { - throw new UpdateException(ex); - } catch (DatabaseException ex) { - throw new UpdateException(ex); - } catch (ClassNotFoundException ex) { + } catch (ParserConfigurationException | SAXException | SQLException | DatabaseException | ClassNotFoundException | IOException ex) { throw new UpdateException(ex); } finally { filePair.cleanup(); diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/update/nvd/UpdateableNvdCve.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/update/nvd/UpdateableNvdCve.java index 4287bba4d..e086f2fae 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/update/nvd/UpdateableNvdCve.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/update/nvd/UpdateableNvdCve.java @@ -33,7 +33,7 @@ public class UpdateableNvdCve implements Iterable, Iterator collection = new TreeMap(); + private final Map collection = new TreeMap<>(); /** * Returns the collection of NvdCveInfo objects. This method is mainly used for testing. diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/dependency/Dependency.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/dependency/Dependency.java index fe442ee3a..cdfe7fc83 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/dependency/Dependency.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/dependency/Dependency.java @@ -128,15 +128,15 @@ public class Dependency implements Serializable, Comparable { /** * A collection of related dependencies. */ - private Set relatedDependencies = new TreeSet(); + private Set relatedDependencies = new TreeSet<>(); /** * A list of projects that reference this dependency. */ - private Set projectReferences = new HashSet(); + private Set projectReferences = new HashSet<>(); /** * A list of available versions. */ - private List availableVersions = new ArrayList(); + private List availableVersions = new ArrayList<>(); /** * Returns the package path. diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/dependency/EvidenceCollection.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/dependency/EvidenceCollection.java index 2590f0cbb..c921da7cf 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/dependency/EvidenceCollection.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/dependency/EvidenceCollection.java @@ -114,23 +114,27 @@ public class EvidenceCollection implements Serializable, Iterable { * @return Iterable<Evidence> an iterable collection of evidence */ public final Iterable iterator(Confidence confidence) { - if (confidence == Confidence.HIGHEST) { - return EvidenceCollection.HIGHEST_CONFIDENCE.filter(this.list); - } else if (confidence == Confidence.HIGH) { - return EvidenceCollection.HIGH_CONFIDENCE.filter(this.list); - } else if (confidence == Confidence.MEDIUM) { - return EvidenceCollection.MEDIUM_CONFIDENCE.filter(this.list); - } else { - return EvidenceCollection.LOW_CONFIDENCE.filter(this.list); + if (null != confidence) { + switch (confidence) { + case HIGHEST: + return EvidenceCollection.HIGHEST_CONFIDENCE.filter(this.list); + case HIGH: + return EvidenceCollection.HIGH_CONFIDENCE.filter(this.list); + case MEDIUM: + return EvidenceCollection.MEDIUM_CONFIDENCE.filter(this.list); + default: + return EvidenceCollection.LOW_CONFIDENCE.filter(this.list); + } } + return null; } /** * Creates a new EvidenceCollection. */ public EvidenceCollection() { - list = new TreeSet(); - weightedStrings = new HashSet(); + list = new TreeSet<>(); + weightedStrings = new HashSet<>(); } /** @@ -204,7 +208,7 @@ public class EvidenceCollection implements Serializable, Iterable { if (source == null) { return null; } - final Set ret = new HashSet(); + final Set ret = new HashSet<>(); for (Evidence e : list) { if (source.equals(e.getSource())) { ret.add(e); @@ -224,7 +228,7 @@ public class EvidenceCollection implements Serializable, Iterable { if (source == null || name == null) { return null; } - final Set ret = new HashSet(); + final Set ret = new HashSet<>(); for (Evidence e : list) { if (source.equals(e.getSource()) && name.equals(e.getName())) { ret.add(e); @@ -345,7 +349,7 @@ public class EvidenceCollection implements Serializable, Iterable { * collections */ public static Set mergeForDisplay(EvidenceCollection... ec) { - final Set ret = new TreeSet(); + final Set ret = new TreeSet<>(); for (EvidenceCollection col : ec) { for (Evidence e : col) { //if (e.isUsed()) { diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/dependency/Vulnerability.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/dependency/Vulnerability.java index b03001a53..ac8dbc7ad 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/dependency/Vulnerability.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/dependency/Vulnerability.java @@ -47,11 +47,11 @@ public class Vulnerability implements Serializable, Comparable { /** * References for this vulnerability. */ - private Set references = new HashSet(); + private Set references = new HashSet<>(); /** * A set of vulnerable software. */ - private Set vulnerableSoftware = new HashSet(); + private Set vulnerableSoftware = new HashSet<>(); /** * The CWE for the vulnerability. */ diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/exception/ExceptionCollection.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/exception/ExceptionCollection.java index de8dfbcd8..e7bf7e9dd 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/exception/ExceptionCollection.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/exception/ExceptionCollection.java @@ -35,7 +35,7 @@ public class ExceptionCollection extends Exception { /** * A collection of exceptions. */ - private List exceptions; + private final List exceptions; /** * Flag indicating if a fatal exception occurred that would prevent the * attempt at completing the analysis even if exceptions occurred. @@ -99,7 +99,7 @@ public class ExceptionCollection extends Exception { */ public ExceptionCollection(Throwable exceptions, boolean fatal) { super(); - this.exceptions = new ArrayList(); + this.exceptions = new ArrayList<>(); this.exceptions.add(exceptions); this.fatal = fatal; } diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/utils/DependencyVersion.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/utils/DependencyVersion.java index f25c76a24..ff8bf15c8 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/utils/DependencyVersion.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/utils/DependencyVersion.java @@ -66,7 +66,7 @@ public class DependencyVersion implements Iterable, Comparable(); + versionParts = new ArrayList<>(); if (version != null) { final Pattern rx = Pattern.compile("(\\d+[a-z]{1,3}$|[a-z]+\\d+|\\d+|(release|beta|alpha)$)"); final Matcher matcher = rx.matcher(version.toLowerCase()); diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/utils/DependencyVersionUtil.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/utils/DependencyVersionUtil.java index 61e88a820..b4ac9cbd6 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/utils/DependencyVersionUtil.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/utils/DependencyVersionUtil.java @@ -74,7 +74,7 @@ public final class DependencyVersionUtil { //'-' is a special case used within the CVE entries, just include it as the version. if ("-".equals(text)) { final DependencyVersion dv = new DependencyVersion(); - final List list = new ArrayList(); + final List list = new ArrayList<>(); list.add(text); dv.setVersionParts(list); return dv; diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/utils/ExtractionUtil.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/utils/ExtractionUtil.java index 9b137b5f6..a23004db5 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/utils/ExtractionUtil.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/utils/ExtractionUtil.java @@ -197,9 +197,7 @@ public final class ExtractionUtil { extractFile(input, destination, filter, entry); } } - } catch (IOException ex) { - throw new ArchiveExtractionException(ex); - } catch (Throwable ex) { + } catch (IOException | AnalysisException ex) { throw new ArchiveExtractionException(ex); } finally { FileUtils.close(input); diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/utils/FileFilterBuilder.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/utils/FileFilterBuilder.java index bf3dbb5ae..f320e0604 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/utils/FileFilterBuilder.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/utils/FileFilterBuilder.java @@ -48,15 +48,15 @@ public class FileFilterBuilder { /** * A set of filenames to filter. */ - private final Set filenames = new HashSet(); + private final Set filenames = new HashSet<>(); /** * A set of extensions to filter. */ - private final Set extensions = new HashSet(); + private final Set extensions = new HashSet<>(); /** * An array list of file filters. */ - private final List fileFilters = new ArrayList(); + private final List fileFilters = new ArrayList<>(); /** * Create a new instance and return it. This method is for convenience in using the builder pattern within a single statement. @@ -125,10 +125,10 @@ public class FileFilterBuilder { } final OrFileFilter filter = new OrFileFilter(); if (!filenames.isEmpty()) { - filter.addFileFilter(new NameFileFilter(new ArrayList(filenames))); + filter.addFileFilter(new NameFileFilter(new ArrayList<>(filenames))); } if (!extensions.isEmpty()) { - filter.addFileFilter(new SuffixFileFilter(new ArrayList(extensions), IOCase.INSENSITIVE)); + filter.addFileFilter(new SuffixFileFilter(new ArrayList<>(extensions), IOCase.INSENSITIVE)); } for (IOFileFilter iof : fileFilters) { filter.addFileFilter(iof); diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/utils/Filter.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/utils/Filter.java index 65c24616e..554a70dc1 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/utils/Filter.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/utils/Filter.java @@ -3,7 +3,7 @@ package org.owasp.dependencycheck.utils; import java.util.Iterator; import java.util.NoSuchElementException; -/* +/** * This is an abstract filter that can be used to filter iterable list. * * This Filter class was copied from: @@ -11,15 +11,35 @@ import java.util.NoSuchElementException; * * Erik Rasmussen - © 2006 - 2012 All Rights Reserved. @author Erik Rasmussen * https://plus.google.com/115403795880834599019/?rel=author + * + * @param the type to filter */ public abstract class Filter { + /** + * Determines whether the object passes the filter. + * + * @param object the object to test + * @return whether or not the object passes the filter + */ public abstract boolean passes(T object); + /** + * Filters a given iterator. + * + * @param iterator the iterator to filter + * @return the filtered iterator + */ public Iterator filter(Iterator iterator) { return new FilterIterator(iterator); } + /** + * Filters a given iterable. + * + * @param iterable the iterable to filter + * @return the filtered iterable + */ public Iterable filter(final Iterable iterable) { return new Iterable() { @@ -71,4 +91,4 @@ public abstract class Filter { } } } -} \ No newline at end of file +} diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/utils/UrlStringUtils.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/utils/UrlStringUtils.java index 7b0da6864..bbabe8f64 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/utils/UrlStringUtils.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/utils/UrlStringUtils.java @@ -69,7 +69,7 @@ public final class UrlStringUtils { /** * A listing of domain parts that should not be used as evidence. Yes, this is an incomplete list. */ - private static final Set IGNORE_LIST = new HashSet( + private static final Set IGNORE_LIST = new HashSet<>( Arrays.asList("www", "com", "org", "gov", "info", "name", "net", "pro", "tel", "mobi", "xxx")); /** @@ -87,7 +87,7 @@ public final class UrlStringUtils { * @throws MalformedURLException thrown if the URL is malformed */ public static List extractImportantUrlData(String text) throws MalformedURLException { - final List importantParts = new ArrayList(); + final List importantParts = new ArrayList<>(); final URL url = new URL(text); final String[] domain = url.getHost().split("\\."); //add the domain except www and the tld. diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/xml/pom/Model.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/xml/pom/Model.java index 132f10daf..2168ec950 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/xml/pom/Model.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/xml/pom/Model.java @@ -74,7 +74,7 @@ public class Model { /** * The list of licenses. */ - private final List licenses = new ArrayList(); + private final List licenses = new ArrayList<>(); /** * The project URL. */ diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/xml/pom/PomHandler.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/xml/pom/PomHandler.java index 198ce2e12..9b9ecea9f 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/xml/pom/PomHandler.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/xml/pom/PomHandler.java @@ -91,7 +91,7 @@ public class PomHandler extends DefaultHandler { /** * The stack of elements processed; used to determine the parent node. */ - private final Deque stack = new ArrayDeque(); + private final Deque stack = new ArrayDeque<>(); /** * The license object. */ diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/xml/suppression/SuppressionHandler.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/xml/suppression/SuppressionHandler.java index 62c11ffc3..86e84a4bc 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/xml/suppression/SuppressionHandler.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/xml/suppression/SuppressionHandler.java @@ -71,7 +71,7 @@ public class SuppressionHandler extends DefaultHandler { /** * A list of suppression rules. */ - private final List suppressionRules = new ArrayList(); + private final List suppressionRules = new ArrayList<>(); /** * Get the value of suppressionRules. diff --git a/dependency-check-core/src/test/java/org/owasp/dependencycheck/BaseDBTestCase.java b/dependency-check-core/src/test/java/org/owasp/dependencycheck/BaseDBTestCase.java index c09568194..b4a9cd0d4 100644 --- a/dependency-check-core/src/test/java/org/owasp/dependencycheck/BaseDBTestCase.java +++ b/dependency-check-core/src/test/java/org/owasp/dependencycheck/BaseDBTestCase.java @@ -26,7 +26,6 @@ import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import org.junit.AfterClass; import org.junit.Before; -import org.junit.BeforeClass; import org.owasp.dependencycheck.data.nvdcve.CveDB; import org.owasp.dependencycheck.utils.Settings; import org.slf4j.Logger; diff --git a/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/JarAnalyzerTest.java b/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/JarAnalyzerTest.java index 97d11546a..cb97030b3 100644 --- a/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/JarAnalyzerTest.java +++ b/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/JarAnalyzerTest.java @@ -136,7 +136,7 @@ public class JarAnalyzerTest extends BaseTest { File file = BaseTest.getResourceAsFile(this, "xalan-2.7.0.jar"); Dependency result = new Dependency(file); JarAnalyzer instance = new JarAnalyzer(); - List cni = new ArrayList(); + List cni = new ArrayList<>(); instance.parseManifest(result, cni); assertTrue(result.getVersionEvidence().getEvidence("manifest: org/apache/xalan/").size() > 0); diff --git a/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/RubyBundleAuditAnalyzerTest.java b/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/RubyBundleAuditAnalyzerTest.java index 91f72a3ba..ff5a4a9e1 100644 --- a/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/RubyBundleAuditAnalyzerTest.java +++ b/dependency-check-core/src/test/java/org/owasp/dependencycheck/analyzer/RubyBundleAuditAnalyzerTest.java @@ -45,6 +45,7 @@ import org.owasp.dependencycheck.utils.Settings; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.junit.Assert.fail; +import org.owasp.dependencycheck.exception.InitializationException; /** * Unit tests for {@link RubyBundleAuditAnalyzer}. @@ -122,7 +123,7 @@ public class RubyBundleAuditAnalyzerTest extends BaseDBTestCase { assertTrue(dependency.getVersionEvidence().toString().toLowerCase().contains("2.2.2")); assertTrue(dependency.getFilePath().endsWith(resource)); assertTrue(dependency.getFileName().equals("Gemfile.lock")); - } catch (Exception e) { + } catch (InitializationException | DatabaseException | AnalysisException e) { LOGGER.warn("Exception setting up RubyBundleAuditAnalyzer. Make sure Ruby gem bundle-audit is installed. You may also need to set property \"analyzer.bundle.audit.path\"."); Assume.assumeNoException("Exception setting up RubyBundleAuditAnalyzer; bundle audit may not be installed, or property \"analyzer.bundle.audit.path\" may not be set.", e); } @@ -145,7 +146,7 @@ public class RubyBundleAuditAnalyzerTest extends BaseDBTestCase { Vulnerability vulnerability = dependency.getVulnerabilities().first(); assertEquals(vulnerability.getCvssScore(), 5.0f, 0.0); - } catch (Exception e) { + } catch (InitializationException | DatabaseException | AnalysisException e) { LOGGER.warn("Exception setting up RubyBundleAuditAnalyzer. Make sure Ruby gem bundle-audit is installed. You may also need to set property \"analyzer.bundle.audit.path\"."); Assume.assumeNoException("Exception setting up RubyBundleAuditAnalyzer; bundle audit may not be installed, or property \"analyzer.bundle.audit.path\" may not be set.", e); } diff --git a/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/lucene/FieldAnalyzerTest.java b/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/lucene/FieldAnalyzerTest.java index 77c70cb17..f98107ba2 100644 --- a/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/lucene/FieldAnalyzerTest.java +++ b/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/lucene/FieldAnalyzerTest.java @@ -61,19 +61,19 @@ public class FieldAnalyzerTest extends BaseTest { String field2 = "vendor"; String text2 = "springsource"; - IndexWriter w = createIndex(analyzer, index); - addDoc(w, field1, text1, field2, text2); - text1 = "x-stream"; - text2 = "xstream"; - addDoc(w, field1, text1, field2, text2); - w.close(); + try (IndexWriter w = createIndex(analyzer, index)) { + addDoc(w, field1, text1, field2, text2); + text1 = "x-stream"; + text2 = "xstream"; + addDoc(w, field1, text1, field2, text2); + } //Analyzer searchingAnalyzer = new SearchFieldAnalyzer(LuceneUtils.CURRENT_VERSION); String querystr = "product:\"(Spring Framework Core)\" vendor:(SpringSource)"; SearchFieldAnalyzer searchAnalyzerProduct = new SearchFieldAnalyzer(LuceneUtils.CURRENT_VERSION); SearchFieldAnalyzer searchAnalyzerVendor = new SearchFieldAnalyzer(LuceneUtils.CURRENT_VERSION); - HashMap map = new HashMap(); + HashMap map = new HashMap<>(); map.put(field1, searchAnalyzerProduct); map.put(field2, searchAnalyzerVendor); PerFieldAnalyzerWrapper wrapper = new PerFieldAnalyzerWrapper(new StandardAnalyzer(LuceneUtils.CURRENT_VERSION), map); diff --git a/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/lucene/UrlTokenizingFilterTest.java b/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/lucene/UrlTokenizingFilterTest.java index 8b902f417..adb7b94ce 100644 --- a/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/lucene/UrlTokenizingFilterTest.java +++ b/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/lucene/UrlTokenizingFilterTest.java @@ -31,7 +31,7 @@ import org.apache.lucene.analysis.core.KeywordTokenizer; */ public class UrlTokenizingFilterTest extends BaseTokenStreamTestCase { - private Analyzer analyzer; + private final Analyzer analyzer; public UrlTokenizingFilterTest() { analyzer = new Analyzer() { diff --git a/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/nvdcve/ConnectionFactoryTest.java b/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/nvdcve/ConnectionFactoryTest.java index 7768acbdb..4316c7311 100644 --- a/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/nvdcve/ConnectionFactoryTest.java +++ b/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/nvdcve/ConnectionFactoryTest.java @@ -36,9 +36,9 @@ public class ConnectionFactoryTest extends BaseDBTestCase { @Test public void testInitialize() throws DatabaseException, SQLException { ConnectionFactory.initialize(); - Connection result = ConnectionFactory.getConnection(); - assertNotNull(result); - result.close(); + try (Connection result = ConnectionFactory.getConnection()) { + assertNotNull(result); + } ConnectionFactory.cleanup(); } } diff --git a/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/update/NvdCveUpdaterIntegrationTest.java b/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/update/NvdCveUpdaterIntegrationTest.java index 6cedb1858..d2305a956 100644 --- a/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/update/NvdCveUpdaterIntegrationTest.java +++ b/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/update/NvdCveUpdaterIntegrationTest.java @@ -21,7 +21,6 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; import org.junit.Test; import org.owasp.dependencycheck.BaseTest; -import org.owasp.dependencycheck.data.nvdcve.CveDB; import org.owasp.dependencycheck.data.update.exception.UpdateException; import org.owasp.dependencycheck.data.update.nvd.UpdateableNvdCve; diff --git a/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/update/nvd/NvdCveInfoTest.java b/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/update/nvd/NvdCveInfoTest.java index 81250cd52..2b31123e0 100644 --- a/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/update/nvd/NvdCveInfoTest.java +++ b/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/update/nvd/NvdCveInfoTest.java @@ -17,7 +17,6 @@ */ package org.owasp.dependencycheck.data.update.nvd; -import org.owasp.dependencycheck.data.update.nvd.NvdCveInfo; import static org.junit.Assert.assertEquals; import org.junit.Test; import org.owasp.dependencycheck.BaseTest; diff --git a/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/update/nvd/NvdCve_1_2_HandlerTest.java b/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/update/nvd/NvdCve_1_2_HandlerTest.java index 4a6684712..01b9662fb 100644 --- a/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/update/nvd/NvdCve_1_2_HandlerTest.java +++ b/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/update/nvd/NvdCve_1_2_HandlerTest.java @@ -17,7 +17,6 @@ */ package org.owasp.dependencycheck.data.update.nvd; -import org.owasp.dependencycheck.data.update.nvd.NvdCve12Handler; import java.io.File; import java.util.List; import java.util.Map; diff --git a/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/update/nvd/NvdCve_2_0_HandlerTest.java b/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/update/nvd/NvdCve_2_0_HandlerTest.java index e438239eb..95dcb5255 100644 --- a/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/update/nvd/NvdCve_2_0_HandlerTest.java +++ b/dependency-check-core/src/test/java/org/owasp/dependencycheck/data/update/nvd/NvdCve_2_0_HandlerTest.java @@ -17,10 +17,11 @@ */ package org.owasp.dependencycheck.data.update.nvd; -import org.owasp.dependencycheck.data.update.nvd.NvdCve20Handler; import java.io.File; +import java.io.IOException; import java.util.List; import java.util.Map; +import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; @@ -29,6 +30,7 @@ import static org.junit.Assert.assertTrue; import org.junit.Test; import org.owasp.dependencycheck.BaseTest; import org.owasp.dependencycheck.dependency.VulnerableSoftware; +import org.xml.sax.SAXException; /** * @@ -49,7 +51,7 @@ public class NvdCve_2_0_HandlerTest extends BaseTest { NvdCve20Handler instance = new NvdCve20Handler(); saxParser.parse(file, instance); - } catch (Throwable ex) { + } catch (ParserConfigurationException | SAXException | IOException ex) { ex.printStackTrace(); results = ex; } @@ -80,7 +82,7 @@ public class NvdCve_2_0_HandlerTest extends BaseTest { saxParser.parse(file20, instance); assertTrue(instance.getTotalNumberOfEntries()==1); - } catch (Throwable ex) { + } catch (ParserConfigurationException | SAXException | IOException ex) { results = ex; } assertTrue("Exception thrown during parse of 2012 CVE version 2.0?", results == null); diff --git a/dependency-check-core/src/test/java/org/owasp/dependencycheck/utils/FilterTest.java b/dependency-check-core/src/test/java/org/owasp/dependencycheck/utils/FilterTest.java index dc0290d85..fcdefcd00 100644 --- a/dependency-check-core/src/test/java/org/owasp/dependencycheck/utils/FilterTest.java +++ b/dependency-check-core/src/test/java/org/owasp/dependencycheck/utils/FilterTest.java @@ -48,12 +48,12 @@ public class FilterTest extends BaseTest { */ @Test public void testFilter_Iterable() { - List testData = new ArrayList(); + List testData = new ArrayList<>(); testData.add("keep"); testData.add("remove"); testData.add("keep"); - List expResults = new ArrayList(); + List expResults = new ArrayList<>(); expResults.add("keep"); expResults.add("keep"); diff --git a/dependency-check-core/src/test/java/org/owasp/dependencycheck/xml/pom/ModelTest.java b/dependency-check-core/src/test/java/org/owasp/dependencycheck/xml/pom/ModelTest.java index 3edb28a01..7d0492f58 100644 --- a/dependency-check-core/src/test/java/org/owasp/dependencycheck/xml/pom/ModelTest.java +++ b/dependency-check-core/src/test/java/org/owasp/dependencycheck/xml/pom/ModelTest.java @@ -248,7 +248,7 @@ public class ModelTest extends BaseTest { public void testGetLicenses() { Model instance = new Model(); instance.addLicense(new License("name", "url")); - List expResult = new ArrayList(); + List expResult = new ArrayList<>(); expResult.add(new License("name", "url")); List result = instance.getLicenses(); assertEquals(expResult, result); diff --git a/dependency-check-core/src/test/java/org/owasp/dependencycheck/xml/suppression/SuppressionRuleTest.java b/dependency-check-core/src/test/java/org/owasp/dependencycheck/xml/suppression/SuppressionRuleTest.java index ec38c0eec..c50f00c26 100644 --- a/dependency-check-core/src/test/java/org/owasp/dependencycheck/xml/suppression/SuppressionRuleTest.java +++ b/dependency-check-core/src/test/java/org/owasp/dependencycheck/xml/suppression/SuppressionRuleTest.java @@ -86,7 +86,7 @@ public class SuppressionRuleTest extends BaseTest { @Test public void testGetCvssBelow() { SuppressionRule instance = new SuppressionRule(); - List cvss = new ArrayList(); + List cvss = new ArrayList<>(); instance.setCvssBelow(cvss); assertFalse(instance.hasCvssBelow()); instance.addCvssBelow(0.7f); @@ -101,7 +101,7 @@ public class SuppressionRuleTest extends BaseTest { @Test public void testCwe() { SuppressionRule instance = new SuppressionRule(); - List cwe = new ArrayList(); + List cwe = new ArrayList<>(); instance.setCwe(cwe); assertFalse(instance.hasCwe()); instance.addCwe("2"); @@ -116,7 +116,7 @@ public class SuppressionRuleTest extends BaseTest { @Test public void testCve() { SuppressionRule instance = new SuppressionRule(); - List cve = new ArrayList(); + List cve = new ArrayList<>(); instance.setCve(cve); assertFalse(instance.hasCve()); instance.addCve("CVE-2013-1337"); diff --git a/dependency-check-maven/src/main/java/org/owasp/dependencycheck/maven/AggregateMojo.java b/dependency-check-maven/src/main/java/org/owasp/dependencycheck/maven/AggregateMojo.java index 0a7220daf..4d1f481ed 100644 --- a/dependency-check-maven/src/main/java/org/owasp/dependencycheck/maven/AggregateMojo.java +++ b/dependency-check-maven/src/main/java/org/owasp/dependencycheck/maven/AggregateMojo.java @@ -153,8 +153,8 @@ public class AggregateMojo extends BaseDependencyCheckMojo { if (project == null) { return Collections.emptySet(); } - final Set descendants = new HashSet(); - int size = 0; + final Set descendants = new HashSet<>(); + int size; if (getLog().isDebugEnabled()) { getLog().debug(String.format("Collecting descendants of %s", project.getName())); } @@ -191,7 +191,7 @@ public class AggregateMojo extends BaseDependencyCheckMojo { } } } - final Set addedDescendants = new HashSet(); + final Set addedDescendants = new HashSet<>(); for (MavenProject dec : descendants) { for (String mod : dec.getModules()) { try { diff --git a/dependency-check-maven/src/main/java/org/owasp/dependencycheck/maven/BaseDependencyCheckMojo.java b/dependency-check-maven/src/main/java/org/owasp/dependencycheck/maven/BaseDependencyCheckMojo.java index ca767a4b4..e97881e07 100644 --- a/dependency-check-maven/src/main/java/org/owasp/dependencycheck/maven/BaseDependencyCheckMojo.java +++ b/dependency-check-maven/src/main/java/org/owasp/dependencycheck/maven/BaseDependencyCheckMojo.java @@ -114,6 +114,9 @@ public abstract class BaseDependencyCheckMojo extends AbstractMojo implements Ma @Component private ArtifactResolver artifactResolver; + /** + * The Maven Session. + */ @Parameter( defaultValue = "${session}", readonly = true, required = true ) protected MavenSession session; diff --git a/dependency-check-maven/src/test/java/org/owasp/dependencycheck/maven/BaseDependencyCheckMojoTest.java b/dependency-check-maven/src/test/java/org/owasp/dependencycheck/maven/BaseDependencyCheckMojoTest.java index 339397e2f..6ac427185 100644 --- a/dependency-check-maven/src/test/java/org/owasp/dependencycheck/maven/BaseDependencyCheckMojoTest.java +++ b/dependency-check-maven/src/test/java/org/owasp/dependencycheck/maven/BaseDependencyCheckMojoTest.java @@ -70,7 +70,7 @@ public class BaseDependencyCheckMojoTest extends BaseTest { MavenProject project = new MockUp() { @Mock public Set getArtifacts() { - Set artifacts = new HashSet(); + Set artifacts = new HashSet<>(); Artifact a = new ArtifactStub(); try { File file = new File(Test.class.getProtectionDomain().getCodeSource().getLocation().toURI()); @@ -107,6 +107,9 @@ public class BaseDependencyCheckMojoTest extends BaseTest { } } + /** + * Implementation of ODC Mojo for testing. + */ public class BaseDependencyCheckMojoImpl extends BaseDependencyCheckMojo { @Override diff --git a/dependency-check-utils/src/main/java/org/owasp/dependencycheck/utils/ExpectedOjectInputStream.java b/dependency-check-utils/src/main/java/org/owasp/dependencycheck/utils/ExpectedOjectInputStream.java index c14b026ee..1fae30831 100644 --- a/dependency-check-utils/src/main/java/org/owasp/dependencycheck/utils/ExpectedOjectInputStream.java +++ b/dependency-check-utils/src/main/java/org/owasp/dependencycheck/utils/ExpectedOjectInputStream.java @@ -36,7 +36,7 @@ public class ExpectedOjectInputStream extends ObjectInputStream { /** * The list of fully qualified class names that are able to be deserialized. */ - private List expected = new ArrayList(); + private List expected = new ArrayList<>(); /** * Constructs a new ExpectedOjectInputStream that can be used to securely deserialize an object by restricting the classes diff --git a/dependency-check-utils/src/main/java/org/owasp/dependencycheck/utils/SSLSocketFactoryEx.java b/dependency-check-utils/src/main/java/org/owasp/dependencycheck/utils/SSLSocketFactoryEx.java index 59a70f487..4849de733 100644 --- a/dependency-check-utils/src/main/java/org/owasp/dependencycheck/utils/SSLSocketFactoryEx.java +++ b/dependency-check-utils/src/main/java/org/owasp/dependencycheck/utils/SSLSocketFactoryEx.java @@ -283,7 +283,7 @@ public class SSLSocketFactoryEx extends SSLSocketFactory { } } - final List aa = new ArrayList(); + final List aa = new ArrayList<>(); for (String preferredProtocol : preferredProtocols) { final int idx = Arrays.binarySearch(availableProtocols, preferredProtocol); if (idx >= 0) { diff --git a/dependency-check-utils/src/main/java/org/owasp/dependencycheck/utils/Settings.java b/dependency-check-utils/src/main/java/org/owasp/dependencycheck/utils/Settings.java index b38b58e6e..5293b0708 100644 --- a/dependency-check-utils/src/main/java/org/owasp/dependencycheck/utils/Settings.java +++ b/dependency-check-utils/src/main/java/org/owasp/dependencycheck/utils/Settings.java @@ -49,7 +49,7 @@ public final class Settings { /** * Thread local settings. */ - private static final ThreadLocal LOCAL_SETTINGS = new ThreadLocal(); + private static final ThreadLocal LOCAL_SETTINGS = new ThreadLocal<>(); /** * The properties. */ @@ -530,9 +530,7 @@ public final class Settings { private static void logProperties(String header, Properties properties) { if (LOGGER.isDebugEnabled()) { final StringWriter sw = new StringWriter(); - PrintWriter pw = null; - try { - pw = new PrintWriter(sw); + try (PrintWriter pw = new PrintWriter(sw)) { pw.format("%s:%n%n", header); final Enumeration e = properties.propertyNames(); while (e.hasMoreElements()) { @@ -548,10 +546,6 @@ public final class Settings { } pw.flush(); LOGGER.debug(sw.toString()); - } finally { - if (pw != null) { - pw.close(); - } } } diff --git a/dependency-check-utils/src/test/java/org/owasp/dependencycheck/utils/DownloaderTest.java b/dependency-check-utils/src/test/java/org/owasp/dependencycheck/utils/DownloaderTest.java index 2ec75264f..7bc487fde 100644 --- a/dependency-check-utils/src/test/java/org/owasp/dependencycheck/utils/DownloaderTest.java +++ b/dependency-check-utils/src/test/java/org/owasp/dependencycheck/utils/DownloaderTest.java @@ -20,7 +20,6 @@ package org.owasp.dependencycheck.utils; import java.io.File; import static org.junit.Assert.assertTrue; import org.junit.Test; -import org.owasp.dependencycheck.utils.Downloader; /** * diff --git a/dependency-check-utils/src/test/java/org/owasp/dependencycheck/utils/ExpectedOjectInputStreamTest.java b/dependency-check-utils/src/test/java/org/owasp/dependencycheck/utils/ExpectedOjectInputStreamTest.java index a70965cb9..210bf0c04 100644 --- a/dependency-check-utils/src/test/java/org/owasp/dependencycheck/utils/ExpectedOjectInputStreamTest.java +++ b/dependency-check-utils/src/test/java/org/owasp/dependencycheck/utils/ExpectedOjectInputStreamTest.java @@ -69,15 +69,16 @@ public class ExpectedOjectInputStreamTest { */ @Test(expected = java.io.InvalidClassException.class) public void testResolveClassException() throws Exception { - List data = new ArrayList(); + List data = new ArrayList<>(); data.add(new SimplePojo()); ByteArrayOutputStream mem = new ByteArrayOutputStream(); - ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(mem)); - out.writeObject(data); - out.flush(); - byte[] buf = mem.toByteArray(); - out.close(); + byte[] buf; + try (ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(mem))) { + out.writeObject(data); + out.flush(); + buf = mem.toByteArray(); + } ByteArrayInputStream in = new ByteArrayInputStream(buf); ExpectedOjectInputStream instance = new ExpectedOjectInputStream(in, "java.util.ArrayList", "org.owasp.dependencycheck.utils.SimplePojo");