java7 updates and cleanup

This commit is contained in:
Jeremy Long
2017-03-10 15:30:48 -05:00
parent 32590ab7ff
commit 046f4605f9
71 changed files with 214 additions and 207 deletions

View File

@@ -942,7 +942,7 @@ public class Check extends Update {
} }
} }
DatabaseProperties prop = null; DatabaseProperties prop = null;
CveDB cve = null; CveDB cve;
try { try {
cve = CveDB.getInstance(); cve = CveDB.getInstance();
prop = cve.getDatabaseProperties(); prop = cve.getDatabaseProperties();

View File

@@ -95,6 +95,12 @@ public class Purge extends Task {
this.failOnError = failOnError; 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 @Override
public void execute() throws BuildException { public void execute() throws BuildException {
populateSettings(); populateSettings();

View File

@@ -223,13 +223,13 @@ public class App {
int retCode = 0; int retCode = 0;
try { try {
engine = new Engine(); engine = new Engine();
final List<String> antStylePaths = new ArrayList<String>(); final List<String> antStylePaths = new ArrayList<>();
for (String file : files) { for (String file : files) {
final String antPath = ensureCanonicalPath(file); final String antPath = ensureCanonicalPath(file);
antStylePaths.add(antPath); antStylePaths.add(antPath);
} }
final Set<File> paths = new HashSet<File>(); final Set<File> paths = new HashSet<>();
for (String file : antStylePaths) { for (String file : antStylePaths) {
LOGGER.debug("Scanning {}", file); LOGGER.debug("Scanning {}", file);
final DirectoryScanner scanner = new DirectoryScanner(); final DirectoryScanner scanner = new DirectoryScanner();
@@ -282,10 +282,8 @@ public class App {
exCol = ex; exCol = ex;
} }
final List<Dependency> dependencies = engine.getDependencies(); final List<Dependency> dependencies = engine.getDependencies();
DatabaseProperties prop = null; CveDB cve = CveDB.getInstance();
CveDB cve = null; DatabaseProperties prop = cve.getDatabaseProperties();
cve = CveDB.getInstance();
prop = cve.getDatabaseProperties();
final ReportGenerator report = new ReportGenerator(applicationName, dependencies, engine.getAnalyzers(), prop); final ReportGenerator report = new ReportGenerator(applicationName, dependencies, engine.getAnalyzers(), prop);
try { try {
report.generateReports(reportDirectory, outputFormat); report.generateReports(reportDirectory, outputFormat);
@@ -461,7 +459,7 @@ public class App {
encoder.setPattern("%d %C:%L%n%-5level - %msg%n"); encoder.setPattern("%d %C:%L%n%-5level - %msg%n");
encoder.setContext(context); encoder.setContext(context);
encoder.start(); encoder.start();
final FileAppender<ILoggingEvent> fa = new FileAppender<ILoggingEvent>(); final FileAppender<ILoggingEvent> fa = new FileAppender<>();
fa.setAppend(true); fa.setAppend(true);
fa.setEncoder(encoder); fa.setEncoder(encoder);
fa.setContext(context); fa.setContext(context);

View File

@@ -86,7 +86,6 @@ public class AnalysisTask implements Callable<Void> {
* Executes the analysis task. * Executes the analysis task.
* *
* @return null * @return null
* @throws Exception thrown if unable to execute the analysis task
*/ */
@Override @Override
public Void call() { public Void call() {

View File

@@ -76,7 +76,7 @@ public class Engine implements FileFilter {
/** /**
* A Map of analyzers grouped by Analysis phase. * A Map of analyzers grouped by Analysis phase.
*/ */
private final Set<FileTypeAnalyzer> fileTypeAnalyzers = new HashSet<FileTypeAnalyzer>(); private final Set<FileTypeAnalyzer> fileTypeAnalyzers = new HashSet<>();
/** /**
* The ClassLoader to use when dynamically loading Analyzer and Update * The ClassLoader to use when dynamically loading Analyzer and Update
@@ -281,7 +281,7 @@ public class Engine implements FileFilter {
* @since v1.4.4 * @since v1.4.4
*/ */
public List<Dependency> scan(File[] files, String projectReference) { public List<Dependency> scan(File[] files, String projectReference) {
final List<Dependency> deps = new ArrayList<Dependency>(); final List<Dependency> deps = new ArrayList<>();
for (File file : files) { for (File file : files) {
final List<Dependency> d = scan(file, projectReference); final List<Dependency> d = scan(file, projectReference);
if (d != null) { if (d != null) {
@@ -316,7 +316,7 @@ public class Engine implements FileFilter {
* @since v1.4.4 * @since v1.4.4
*/ */
public List<Dependency> scan(Collection<File> files, String projectReference) { public List<Dependency> scan(Collection<File> files, String projectReference) {
final List<Dependency> deps = new ArrayList<Dependency>(); final List<Dependency> deps = new ArrayList<>();
for (File file : files) { for (File file : files) {
final List<Dependency> d = scan(file, projectReference); final List<Dependency> d = scan(file, projectReference);
if (d != null) { if (d != null) {
@@ -357,7 +357,7 @@ public class Engine implements FileFilter {
} else { } else {
final Dependency d = scanFile(file, projectReference); final Dependency d = scanFile(file, projectReference);
if (d != null) { if (d != null) {
final List<Dependency> deps = new ArrayList<Dependency>(); final List<Dependency> deps = new ArrayList<>();
deps.add(d); deps.add(d);
return deps; return deps;
} }

View File

@@ -28,6 +28,7 @@ import org.owasp.dependencycheck.dependency.Dependency;
import org.owasp.dependencycheck.dependency.Identifier; import org.owasp.dependencycheck.dependency.Identifier;
import org.owasp.dependencycheck.dependency.Vulnerability; import org.owasp.dependencycheck.dependency.Vulnerability;
import org.owasp.dependencycheck.exception.ExceptionCollection; import org.owasp.dependencycheck.exception.ExceptionCollection;
import org.owasp.dependencycheck.exception.ReportException;
import org.owasp.dependencycheck.exception.ScanAgentException; import org.owasp.dependencycheck.exception.ScanAgentException;
import org.owasp.dependencycheck.reporting.ReportGenerator; import org.owasp.dependencycheck.reporting.ReportGenerator;
import org.owasp.dependencycheck.utils.Settings; import org.owasp.dependencycheck.utils.Settings;
@@ -842,7 +843,7 @@ public class DependencyCheckScanAgent {
*/ */
private void generateExternalReports(Engine engine, File outDirectory) { private void generateExternalReports(Engine engine, File outDirectory) {
DatabaseProperties prop = null; DatabaseProperties prop = null;
CveDB cve = null; CveDB cve;
try { try {
cve = CveDB.getInstance(); cve = CveDB.getInstance();
prop = cve.getDatabaseProperties(); prop = cve.getDatabaseProperties();
@@ -853,13 +854,9 @@ public class DependencyCheckScanAgent {
final ReportGenerator r = new ReportGenerator(this.applicationName, engine.getDependencies(), engine.getAnalyzers(), prop); final ReportGenerator r = new ReportGenerator(this.applicationName, engine.getDependencies(), engine.getAnalyzers(), prop);
try { try {
r.generateReports(outDirectory.getCanonicalPath(), this.reportFormat.name()); 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.error("Unexpected exception occurred during analysis; please see the verbose error log for more details.");
LOGGER.debug("", ex); 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);
} }
} }

View File

@@ -141,7 +141,7 @@ public abstract class AbstractFileTypeAnalyzer extends AbstractAnalyzer implemen
* @return a Set of strings. * @return a Set of strings.
*/ */
protected static Set<String> newHashSet(String... strings) { protected static Set<String> newHashSet(String... strings) {
final Set<String> set = new HashSet<String>(strings.length); final Set<String> set = new HashSet<>(strings.length);
Collections.addAll(set, strings); Collections.addAll(set, strings);
return set; return set;
} }

View File

@@ -57,7 +57,7 @@ public class AnalyzerService {
* @return a list of Analyzers. * @return a list of Analyzers.
*/ */
public List<Analyzer> getAnalyzers() { public List<Analyzer> getAnalyzers() {
final List<Analyzer> analyzers = new ArrayList<Analyzer>(); final List<Analyzer> analyzers = new ArrayList<>();
final Iterator<Analyzer> iterator = service.iterator(); final Iterator<Analyzer> iterator = service.iterator();
boolean experimentalEnabled = false; boolean experimentalEnabled = false;
try { try {

View File

@@ -105,6 +105,7 @@ public class ArchiveAnalyzer extends AbstractFileTypeAnalyzer {
* in {@link #extractFiles(File, File, Engine)}. * in {@link #extractFiles(File, File, Engine)}.
*/ */
private static final Set<String> EXTENSIONS = newHashSet("tar", "gz", "tgz", "bz2", "tbz2"); private static final Set<String> EXTENSIONS = newHashSet("tar", "gz", "tgz", "bz2", "tbz2");
static { static {
final String additionalZipExt = Settings.getString(Settings.KEYS.ADDITIONAL_ZIP_EXTENSIONS); final String additionalZipExt = Settings.getString(Settings.KEYS.ADDITIONAL_ZIP_EXTENSIONS);
if (additionalZipExt != null) { if (additionalZipExt != null) {
@@ -220,6 +221,8 @@ public class ArchiveAnalyzer extends AbstractFileTypeAnalyzer {
* Does not support parallel processing as it both modifies and iterates * Does not support parallel processing as it both modifies and iterates
* over the engine's list of dependencies. * over the engine's list of dependencies.
* *
* @return <code>true</code> if the analyzer supports parallel processing;
* otherwise <code>false</code>
* @see #analyzeDependency(Dependency, Engine) * @see #analyzeDependency(Dependency, Engine)
* @see #findMoreDependencies(Engine, File) * @see #findMoreDependencies(Engine, File)
*/ */
@@ -517,7 +520,7 @@ public class ArchiveAnalyzer extends AbstractFileTypeAnalyzer {
extractAcceptedFile(input, file); extractAcceptedFile(input, file);
} }
} }
} catch (Throwable ex) { } catch (IOException | AnalysisException ex) {
throw new ArchiveExtractionException(ex); throw new ArchiveExtractionException(ex);
} finally { } finally {
FileUtils.close(input); FileUtils.close(input);

View File

@@ -84,7 +84,7 @@ public class AssemblyAnalyzer extends AbstractFileTypeAnalyzer {
*/ */
protected List<String> buildArgumentList() { protected List<String> buildArgumentList() {
// Use file.separator as a wild guess as to whether this is Windows // Use file.separator as a wild guess as to whether this is Windows
final List<String> args = new ArrayList<String>(); final List<String> args = new ArrayList<>();
if (!SystemUtils.IS_OS_WINDOWS) { if (!SystemUtils.IS_OS_WINDOWS) {
if (Settings.getString(Settings.KEYS.ANALYZER_ASSEMBLY_MONO_PATH) != null) { if (Settings.getString(Settings.KEYS.ANALYZER_ASSEMBLY_MONO_PATH) != null) {
args.add(Settings.getString(Settings.KEYS.ANALYZER_ASSEMBLY_MONO_PATH)); args.add(Settings.getString(Settings.KEYS.ANALYZER_ASSEMBLY_MONO_PATH));
@@ -176,18 +176,17 @@ public class AssemblyAnalyzer extends AbstractFileTypeAnalyzer {
} catch (ParserConfigurationException pce) { } catch (ParserConfigurationException pce) {
throw new AnalysisException("Error initializing the assembly analyzer", pce); throw new AnalysisException("Error initializing the assembly analyzer", pce);
} catch (IOException ioe) { } catch (IOException | XPathExpressionException ioe) {
throw new AnalysisException(ioe); throw new AnalysisException(ioe);
} catch (SAXException saxe) { }catch (SAXException saxe) {
LOGGER.error("----------------------------------------------------"); LOGGER.error("----------------------------------------------------");
LOGGER.error("Failed to read the Assembly Analyzer results. " LOGGER.error("Failed to read the Assembly Analyzer results. "
+ "On some systems mono-runtime and mono-devel need to be installed."); + "On some systems mono-runtime and mono-devel need to be installed.");
LOGGER.error("----------------------------------------------------"); LOGGER.error("----------------------------------------------------");
throw new AnalysisException("Couldn't parse Assembly Analzyzer results (GrokAssembly)", saxe); 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) { } catch (InitializationException e) {
setEnabled(false); setEnabled(false);
throw e; throw e;
} catch (Throwable e) { } catch (IOException | ParserConfigurationException | SAXException | XPathExpressionException | InterruptedException e) {
LOGGER.warn("An error occurred with the .NET AssemblyAnalyzer;\n" 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."); + "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()); LOGGER.debug("Could not execute GrokAssembly {}", e.getMessage());
@@ -366,10 +365,8 @@ public class AssemblyAnalyzer extends AbstractFileTypeAnalyzer {
if (retCode == 0) { if (retCode == 0) {
return true; return true;
} }
} catch (IOException ex) { } catch (IOException | InterruptedException ex) {
LOGGER.debug("Path seach failed for " + file); LOGGER.debug("Path seach failed for " + file, ex);
} catch (InterruptedException ex) {
LOGGER.debug("Path seach failed for " + file);
} }
return false; return false;
} }

View File

@@ -188,6 +188,11 @@ public class CPEAnalyzer extends AbstractAnalyzer {
} }
} }
/**
* Returns whether or not the analyzer is open.
*
* @return <code>true</code> if the analyzer is open
*/
public boolean isOpen() { public boolean isOpen() {
return cpe != null && cpe.isOpen(); return cpe != null && cpe.isOpen();
} }
@@ -291,7 +296,7 @@ public class CPEAnalyzer extends AbstractAnalyzer {
protected List<IndexEntry> searchCPE(String vendor, String product, protected List<IndexEntry> searchCPE(String vendor, String product,
Set<String> vendorWeightings, Set<String> productWeightings) { Set<String> vendorWeightings, Set<String> productWeightings) {
final List<IndexEntry> ret = new ArrayList<IndexEntry>(MAX_QUERY_RESULTS); final List<IndexEntry> ret = new ArrayList<>(MAX_QUERY_RESULTS);
final String searchString = buildSearch(vendor, product, vendorWeightings, productWeightings); final String searchString = buildSearch(vendor, product, vendorWeightings, productWeightings);
if (searchString == null) { if (searchString == null) {
@@ -477,7 +482,7 @@ public class CPEAnalyzer extends AbstractAnalyzer {
return false; return false;
} }
final String[] words = text.split("[\\s_-]"); final String[] words = text.split("[\\s_-]");
final List<String> list = new ArrayList<String>(); final List<String> list = new ArrayList<>();
String tempWord = null; String tempWord = null;
for (String word : words) { for (String word : words) {
/* /*
@@ -555,7 +560,7 @@ public class CPEAnalyzer extends AbstractAnalyzer {
DependencyVersion bestGuess = new DependencyVersion("-"); DependencyVersion bestGuess = new DependencyVersion("-");
Confidence bestGuessConf = null; Confidence bestGuessConf = null;
boolean hasBroadMatch = false; boolean hasBroadMatch = false;
final List<IdentifierMatch> collected = new ArrayList<IdentifierMatch>(); final List<IdentifierMatch> collected = new ArrayList<>();
//TODO the following algorithm incorrectly identifies things as a lower version //TODO the following algorithm incorrectly identifies things as a lower version
// if there lower confidence evidence when the current (highest) version number // if there lower confidence evidence when the current (highest) version number

View File

@@ -145,7 +145,7 @@ public class DependencyBundlingAnalyzer extends AbstractAnalyzer {
protected synchronized void analyzeDependency(Dependency ignore, Engine engine) throws AnalysisException { protected synchronized void analyzeDependency(Dependency ignore, Engine engine) throws AnalysisException {
if (!analyzed) { if (!analyzed) {
analyzed = true; analyzed = true;
final Set<Dependency> dependenciesToRemove = new HashSet<Dependency>(); final Set<Dependency> dependenciesToRemove = new HashSet<>();
final ListIterator<Dependency> mainIterator = engine.getDependencies().listIterator(); final ListIterator<Dependency> mainIterator = engine.getDependencies().listIterator();
//for (Dependency nextDependency : engine.getDependencies()) { //for (Dependency nextDependency : engine.getDependencies()) {
while (mainIterator.hasNext()) { while (mainIterator.hasNext()) {

View File

@@ -129,7 +129,7 @@ public class DependencyMergingAnalyzer extends AbstractAnalyzer {
protected synchronized void analyzeDependency(Dependency ignore, Engine engine) throws AnalysisException { protected synchronized void analyzeDependency(Dependency ignore, Engine engine) throws AnalysisException {
if (!analyzed) { if (!analyzed) {
analyzed = true; analyzed = true;
final Set<Dependency> dependenciesToRemove = new HashSet<Dependency>(); final Set<Dependency> dependenciesToRemove = new HashSet<>();
final ListIterator<Dependency> mainIterator = engine.getDependencies().listIterator(); final ListIterator<Dependency> mainIterator = engine.getDependencies().listIterator();
//for (Dependency nextDependency : engine.getDependencies()) { //for (Dependency nextDependency : engine.getDependencies()) {
while (mainIterator.hasNext()) { while (mainIterator.hasNext()) {
@@ -138,7 +138,7 @@ public class DependencyMergingAnalyzer extends AbstractAnalyzer {
final ListIterator<Dependency> subIterator = engine.getDependencies().listIterator(mainIterator.nextIndex()); final ListIterator<Dependency> subIterator = engine.getDependencies().listIterator(mainIterator.nextIndex());
while (subIterator.hasNext()) { while (subIterator.hasNext()) {
final Dependency nextDependency = subIterator.next(); final Dependency nextDependency = subIterator.next();
Dependency main = null; Dependency main;
if ((main = getMainGemspecDependency(dependency, nextDependency)) != null) { if ((main = getMainGemspecDependency(dependency, nextDependency)) != null) {
if (main == dependency) { if (main == dependency) {
mergeDependencies(dependency, nextDependency, dependenciesToRemove); mergeDependencies(dependency, nextDependency, dependenciesToRemove);

View File

@@ -173,7 +173,7 @@ public class FalsePositiveAnalyzer extends AbstractAnalyzer {
*/ */
@SuppressWarnings("null") @SuppressWarnings("null")
private void removeSpuriousCPE(Dependency dependency) { private void removeSpuriousCPE(Dependency dependency) {
final List<Identifier> ids = new ArrayList<Identifier>(dependency.getIdentifiers()); final List<Identifier> ids = new ArrayList<>(dependency.getIdentifiers());
Collections.sort(ids); Collections.sort(ids);
final ListIterator<Identifier> mainItr = ids.listIterator(); final ListIterator<Identifier> mainItr = ids.listIterator();
while (mainItr.hasNext()) { while (mainItr.hasNext()) {

View File

@@ -255,7 +255,7 @@ public class JarAnalyzer extends AbstractFileTypeAnalyzer {
*/ */
protected boolean analyzePOM(Dependency dependency, List<ClassNameInformation> classes, Engine engine) throws AnalysisException { protected boolean analyzePOM(Dependency dependency, List<ClassNameInformation> classes, Engine engine) throws AnalysisException {
JarFile jar = null; JarFile jar = null;
List<String> pomEntries = null; List<String> pomEntries;
try { try {
jar = new JarFile(dependency.getActualFilePath()); jar = new JarFile(dependency.getActualFilePath());
pomEntries = retrievePomListing(jar); pomEntries = retrievePomListing(jar);
@@ -636,9 +636,7 @@ public class JarAnalyzer extends AbstractFileTypeAnalyzer {
protected boolean parseManifest(Dependency dependency, List<ClassNameInformation> classInformation) protected boolean parseManifest(Dependency dependency, List<ClassNameInformation> classInformation)
throws IOException { throws IOException {
boolean foundSomething = false; boolean foundSomething = false;
JarFile jar = null; try (JarFile jar = new JarFile(dependency.getActualFilePath())) {
try {
jar = new JarFile(dependency.getActualFilePath());
final Manifest manifest = jar.getManifest(); final Manifest manifest = jar.getManifest();
if (manifest == null) { if (manifest == null) {
if (!dependency.getFileName().toLowerCase().endsWith("-sources.jar") if (!dependency.getFileName().toLowerCase().endsWith("-sources.jar")
@@ -793,10 +791,6 @@ public class JarAnalyzer extends AbstractFileTypeAnalyzer {
foundSomething = true; foundSomething = true;
versionEvidence.addEvidence(source, "specification-version", specificationVersion, Confidence.HIGH); versionEvidence.addEvidence(source, "specification-version", specificationVersion, Confidence.HIGH);
} }
} finally {
if (jar != null) {
jar.close();
}
} }
return foundSomething; return foundSomething;
} }
@@ -1124,7 +1118,7 @@ public class JarAnalyzer extends AbstractFileTypeAnalyzer {
* Up to the first four levels of the package structure, excluding a * Up to the first four levels of the package structure, excluding a
* leading "org" or "com". * leading "org" or "com".
*/ */
private final ArrayList<String> packageStructure = new ArrayList<String>(); private final ArrayList<String> packageStructure = new ArrayList<>();
/** /**
* <p> * <p>

View File

@@ -136,9 +136,7 @@ public class NuspecAnalyzer extends AbstractFileTypeAnalyzer {
try { try {
fis = new FileInputStream(dependency.getActualFilePath()); fis = new FileInputStream(dependency.getActualFilePath());
np = parser.parse(fis); np = parser.parse(fis);
} catch (NuspecParseException ex) { } catch (NuspecParseException | FileNotFoundException ex) {
throw new AnalysisException(ex);
} catch (FileNotFoundException ex) {
throw new AnalysisException(ex); throw new AnalysisException(ex);
} finally { } finally {
if (fis != null) { if (fis != null) {

View File

@@ -364,9 +364,7 @@ public class PythonDistributionAnalyzer extends AbstractFileTypeAnalyzer {
try { try {
in = new BufferedInputStream(new FileInputStream(manifest)); in = new BufferedInputStream(new FileInputStream(manifest));
result.load(in); result.load(in);
} catch (MessagingException e) { } catch (MessagingException | FileNotFoundException e) {
LOGGER.warn(e.getMessage(), e);
} catch (FileNotFoundException e) {
LOGGER.warn(e.getMessage(), e); LOGGER.warn(e.getMessage(), e);
} finally { } finally {
if (in != null) { if (in != null) {

View File

@@ -113,7 +113,7 @@ public class RubyBundleAuditAnalyzer extends AbstractFileTypeAnalyzer {
if (!folder.isDirectory()) { if (!folder.isDirectory()) {
throw new AnalysisException(String.format("%s should have been a directory.", folder.getAbsolutePath())); throw new AnalysisException(String.format("%s should have been a directory.", folder.getAbsolutePath()));
} }
final List<String> args = new ArrayList<String>(); final List<String> args = new ArrayList<>();
final String bundleAuditPath = Settings.getString(Settings.KEYS.ANALYZER_BUNDLE_AUDIT_PATH); final String bundleAuditPath = Settings.getString(Settings.KEYS.ANALYZER_BUNDLE_AUDIT_PATH);
File bundleAudit = null; File bundleAudit = null;
if (bundleAuditPath != null) { if (bundleAuditPath != null) {
@@ -342,7 +342,7 @@ public class RubyBundleAuditAnalyzer extends AbstractFileTypeAnalyzer {
Dependency dependency = null; Dependency dependency = null;
Vulnerability vulnerability = null; Vulnerability vulnerability = null;
String gem = null; String gem = null;
final Map<String, Dependency> map = new HashMap<String, Dependency>(); final Map<String, Dependency> map = new HashMap<>();
boolean appendToDescription = false; boolean appendToDescription = false;
while (rdr.ready()) { while (rdr.ready()) {
final String nextLine = rdr.readLine(); final String nextLine = rdr.readLine();

View File

@@ -24,8 +24,10 @@ import java.net.URL;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath; import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory; import javax.xml.xpath.XPathFactory;
import org.owasp.dependencycheck.data.nexus.MavenArtifact; import org.owasp.dependencycheck.data.nexus.MavenArtifact;
import org.owasp.dependencycheck.utils.Settings; import org.owasp.dependencycheck.utils.Settings;
@@ -35,6 +37,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.w3c.dom.Document; import org.w3c.dom.Document;
import org.w3c.dom.NodeList; import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/** /**
* Class of methods to search Maven Central via Central. * Class of methods to search Maven Central via Central.
@@ -117,7 +120,7 @@ public class CentralSearch {
if ("0".equals(numFound)) { if ("0".equals(numFound)) {
missing = true; missing = true;
} else { } else {
result = new ArrayList<MavenArtifact>(); result = new ArrayList<>();
final NodeList docs = (NodeList) xpath.evaluate("/response/result/doc", doc, XPathConstants.NODESET); final NodeList docs = (NodeList) xpath.evaluate("/response/result/doc", doc, XPathConstants.NODESET);
for (int i = 0; i < docs.getLength(); i++) { for (int i = 0; i < docs.getLength(); i++) {
final String g = xpath.evaluate("./str[@name='g']", docs.item(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)); 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 // Anything else is jacked up XML stuff that we really can't recover from well
throw new IOException(e.getMessage(), e); throw new IOException(e.getMessage(), e);
} }

View File

@@ -66,7 +66,7 @@ public class ComposerLockParser {
LOGGER.info("Creating a ComposerLockParser"); LOGGER.info("Creating a ComposerLockParser");
this.inputStream = inputStream; this.inputStream = inputStream;
this.jsonReader = Json.createReader(inputStream); this.jsonReader = Json.createReader(inputStream);
this.composerDependencies = new ArrayList<ComposerDependency>(); this.composerDependencies = new ArrayList<>();
} }
/** /**

View File

@@ -149,7 +149,7 @@ public final class CpeMemoryIndex {
* @return the CPE Analyzer. * @return the CPE Analyzer.
*/ */
private Analyzer createSearchingAnalyzer() { private Analyzer createSearchingAnalyzer() {
final Map<String, Analyzer> fieldAnalyzers = new HashMap<String, Analyzer>(); final Map<String, Analyzer> fieldAnalyzers = new HashMap<>();
fieldAnalyzers.put(Fields.DOCUMENT_KEY, new KeywordAnalyzer()); fieldAnalyzers.put(Fields.DOCUMENT_KEY, new KeywordAnalyzer());
productFieldAnalyzer = new SearchFieldAnalyzer(LuceneUtils.CURRENT_VERSION); productFieldAnalyzer = new SearchFieldAnalyzer(LuceneUtils.CURRENT_VERSION);
vendorFieldAnalyzer = new SearchFieldAnalyzer(LuceneUtils.CURRENT_VERSION); vendorFieldAnalyzer = new SearchFieldAnalyzer(LuceneUtils.CURRENT_VERSION);

View File

@@ -32,7 +32,7 @@ public class CweHandler extends DefaultHandler {
/** /**
* a HashMap containing the CWE data. * a HashMap containing the CWE data.
*/ */
private final HashMap<String, String> cwe = new HashMap<String, String>(); private final HashMap<String, String> cwe = new HashMap<>();
/** /**
* Returns the HashMap of CWE entries (CWE-ID, Full CWE Name). * Returns the HashMap of CWE entries (CWE-ID, Full CWE Name).

View File

@@ -63,7 +63,7 @@ public abstract class AbstractTokenizingFilter extends TokenFilter {
*/ */
public AbstractTokenizingFilter(TokenStream stream) { public AbstractTokenizingFilter(TokenStream stream) {
super(stream); super(stream);
tokens = new LinkedList<String>(); tokens = new LinkedList<>();
} }
/** /**

View File

@@ -71,7 +71,7 @@ public final class TokenPairConcatenatingFilter extends TokenFilter {
*/ */
public TokenPairConcatenatingFilter(TokenStream stream) { public TokenPairConcatenatingFilter(TokenStream stream) {
super(stream); super(stream);
words = new LinkedList<String>(); words = new LinkedList<>();
} }
/** /**

View File

@@ -22,7 +22,9 @@ import java.io.IOException;
import java.net.HttpURLConnection; import java.net.HttpURLConnection;
import java.net.URL; import java.net.URL;
import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath; import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory; import javax.xml.xpath.XPathFactory;
import org.owasp.dependencycheck.utils.URLConnectionFactory; import org.owasp.dependencycheck.utils.URLConnectionFactory;
@@ -30,6 +32,7 @@ import org.owasp.dependencycheck.utils.XmlUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.w3c.dom.Document; import org.w3c.dom.Document;
import org.xml.sax.SAXException;
/** /**
* Class of methods to search Nexus repositories. * Class of methods to search Nexus repositories.
@@ -132,7 +135,7 @@ public class NexusSearch {
ma.setPomUrl(pomLink); ma.setPomUrl(pomLink);
} }
return ma; return ma;
} catch (Throwable e) { } catch (ParserConfigurationException | IOException | SAXException | XPathExpressionException e) {
// Anything else is jacked-up XML stuff that we really can't recover // Anything else is jacked-up XML stuff that we really can't recover
// from well // from well
throw new IOException(e.getMessage(), e); 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()); LOGGER.warn("Expected root node name of status, got {}", doc.getDocumentElement().getNodeName());
return false; return false;
} }
} catch (Throwable e) { } catch (IOException | ParserConfigurationException | SAXException e) {
return false; return false;
} }

View File

@@ -17,14 +17,18 @@
*/ */
package org.owasp.dependencycheck.data.nuget; package org.owasp.dependencycheck.data.nuget;
import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath; import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory; import javax.xml.xpath.XPathFactory;
import org.owasp.dependencycheck.utils.XmlUtils; import org.owasp.dependencycheck.utils.XmlUtils;
import org.w3c.dom.Document; import org.w3c.dom.Document;
import org.w3c.dom.Node; import org.w3c.dom.Node;
import org.xml.sax.SAXException;
/** /**
* Parse a Nuspec file using XPath. * 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.setLicenseUrl(getOrNull((Node) xpath.evaluate("/package/metadata/licenseUrl", d, XPathConstants.NODE)));
nuspec.setTitle(getOrNull((Node) xpath.evaluate("/package/metadata/title", d, XPathConstants.NODE))); nuspec.setTitle(getOrNull((Node) xpath.evaluate("/package/metadata/title", d, XPathConstants.NODE)));
return nuspec; return nuspec;
} catch (Throwable e) { } catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException | NuspecParseException e) {
throw new NuspecParseException("Unable to parse nuspec", e); throw new NuspecParseException("Unable to parse nuspec", e);
} }
} }

View File

@@ -228,7 +228,7 @@ public final class CveDB {
private EnumMap<PreparedStatementCveDb, PreparedStatement> prepareStatements() private EnumMap<PreparedStatementCveDb, PreparedStatement> prepareStatements()
throws DatabaseException { throws DatabaseException {
final EnumMap<PreparedStatementCveDb, PreparedStatement> result = new EnumMap<PreparedStatementCveDb, PreparedStatement>(PreparedStatementCveDb.class); final EnumMap<PreparedStatementCveDb, PreparedStatement> result = new EnumMap<>(PreparedStatementCveDb.class);
for (PreparedStatementCveDb key : values()) { for (PreparedStatementCveDb key : values()) {
final String statementString = statementBundle.getString(key.name()); final String statementString = statementBundle.getString(key.name());
final PreparedStatement preparedStatement; final PreparedStatement preparedStatement;
@@ -777,7 +777,7 @@ public final class CveDB {
final boolean isVersionTwoADifferentProduct = "apache".equals(vendor) && "struts".equals(product); final boolean isVersionTwoADifferentProduct = "apache".equals(vendor) && "struts".equals(product);
final Set<String> majorVersionsAffectingAllPrevious = new HashSet<String>(); final Set<String> majorVersionsAffectingAllPrevious = new HashSet<>();
final boolean matchesAnyPrevious = identifiedVersion == null || "-".equals(identifiedVersion.toString()); final boolean matchesAnyPrevious = identifiedVersion == null || "-".equals(identifiedVersion.toString());
String majorVersionMatch = null; String majorVersionMatch = null;
for (Entry<String, Boolean> entry : vulnerableSoftware.entrySet()) { for (Entry<String, Boolean> entry : vulnerableSoftware.entrySet()) {
@@ -806,12 +806,12 @@ public final class CveDB {
if (!entry.getValue()) { if (!entry.getValue()) {
final DependencyVersion v = parseDependencyVersion(entry.getKey()); final DependencyVersion v = parseDependencyVersion(entry.getKey());
//this can't dereference a null 'majorVersionMatch' as canSkipVersions accounts for this. //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; continue;
} }
//this can't dereference a null 'identifiedVersion' because if it was null we would have exited //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). //in the above loop or just after loop (if matchesAnyPrevious return null).
if (identifiedVersion.equals(v)) { if (identifiedVersion != null && identifiedVersion.equals(v)) {
return entry; return entry;
} }
} }
@@ -820,12 +820,12 @@ public final class CveDB {
if (entry.getValue()) { if (entry.getValue()) {
final DependencyVersion v = parseDependencyVersion(entry.getKey()); final DependencyVersion v = parseDependencyVersion(entry.getKey());
//this can't dereference a null 'majorVersionMatch' as canSkipVersions accounts for this. //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; continue;
} }
//this can't dereference a null 'identifiedVersion' because if it was null we would have exited //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). //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)))) { if (!(isVersionTwoADifferentProduct && !identifiedVersion.getVersionParts().get(0).equals(v.getVersionParts().get(0)))) {
return entry; return entry;
} }

View File

@@ -166,7 +166,7 @@ public class DatabaseProperties {
* @return a map of the database meta data * @return a map of the database meta data
*/ */
public Map<String, String> getMetaData() { public Map<String, String> getMetaData() {
final Map<String, String> map = new TreeMap<String, String>(); final Map<String, String> map = new TreeMap<>();
for (Entry<Object, Object> entry : properties.entrySet()) { for (Entry<Object, Object> entry : properties.entrySet()) {
final String key = (String) entry.getKey(); final String key = (String) entry.getKey();
if (!"version".equals(key)) { if (!"version".equals(key)) {

View File

@@ -75,7 +75,7 @@ public final class DriverLoader {
*/ */
public static Driver load(String className, String pathToDriver) throws DriverLoadException { public static Driver load(String className, String pathToDriver) throws DriverLoadException {
final URLClassLoader parent = (URLClassLoader) ClassLoader.getSystemClassLoader(); final URLClassLoader parent = (URLClassLoader) ClassLoader.getSystemClassLoader();
final List<URL> urls = new ArrayList<URL>(); final List<URL> urls = new ArrayList<>();
final String[] paths = pathToDriver.split(File.pathSeparator); final String[] paths = pathToDriver.split(File.pathSeparator);
for (String path : paths) { for (String path : paths) {
final File file = new File(path); 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 //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); DriverManager.registerDriver(shim);
return shim; return shim;
} catch (ClassNotFoundException 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);
} 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) {
final String msg = String.format("Unable to load database driver '%s'", className); final String msg = String.format("Unable to load database driver '%s'", className);
LOGGER.debug(msg, ex); LOGGER.debug(msg, ex);
throw new DriverLoadException(msg, ex); throw new DriverLoadException(msg, ex);

View File

@@ -126,11 +126,7 @@ class DriverShim implements Driver {
if (m != null) { if (m != null) {
try { try {
return (java.util.logging.Logger) m.invoke(m); return (java.util.logging.Logger) m.invoke(m);
} catch (IllegalAccessException ex) { } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
LOGGER.trace("", ex);
} catch (IllegalArgumentException ex) {
LOGGER.trace("", ex);
} catch (InvocationTargetException ex) {
LOGGER.trace("", ex); LOGGER.trace("", ex);
} }
} }

View File

@@ -16,7 +16,7 @@
* Copyright (c) 2015 Jeremy Long. All Rights Reserved. * Copyright (c) 2015 Jeremy Long. All Rights Reserved.
*/ */
package org.owasp.dependencycheck.data.update; package org.owasp.dependencycheck.data.update;
/*
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.net.MalformedURLException; import java.net.MalformedURLException;
@@ -37,7 +37,7 @@ import org.owasp.dependencycheck.utils.XmlUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.xml.sax.SAXException; import org.xml.sax.SAXException;
*/
/** /**
* *
* This class is currently unused and if enabled will likely not work on MySQL * This class is currently unused and if enabled will likely not work on MySQL

View File

@@ -24,13 +24,13 @@ import java.util.HashSet;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import java.net.URL; import java.net.URL;
import java.util.Properties;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.Future; import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.owasp.dependencycheck.data.nvdcve.CveDB; import org.owasp.dependencycheck.data.nvdcve.CveDB;
import org.owasp.dependencycheck.data.nvdcve.DatabaseException; import org.owasp.dependencycheck.data.nvdcve.DatabaseException;
import org.owasp.dependencycheck.data.nvdcve.DatabaseProperties; 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() { protected void initializeExecutorServices() {
processingExecutorService = Executors.newFixedThreadPool(PROCESSING_THREAD_POOL_SIZE); processingExecutorService = Executors.newFixedThreadPool(PROCESSING_THREAD_POOL_SIZE);
downloadExecutorService = Executors.newFixedThreadPool(DOWNLOAD_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); LOGGER.debug("#processing threads: {}", PROCESSING_THREAD_POOL_SIZE);
} }
/**
* Shutdown and cleanup of resources used by the executor services.
*/
private void shutdownExecutorServices() { private void shutdownExecutorServices() {
if (processingExecutorService != null) { if (processingExecutorService != null) {
processingExecutorService.shutdownNow(); processingExecutorService.shutdownNow();
@@ -427,7 +434,7 @@ public class NvdCveUpdater implements CachedWebDataSource {
final long timestamp; final long timestamp;
try { try {
timestamp = timestampFuture.get(60, TimeUnit.SECONDS); timestamp = timestampFuture.get(60, TimeUnit.SECONDS);
} catch (Exception e) { } catch (InterruptedException | ExecutionException | TimeoutException e) {
throw new DownloadFailedException(e); throw new DownloadFailedException(e);
} }
lastModifiedDates.put(url, timestamp); lastModifiedDates.put(url, timestamp);
@@ -441,7 +448,7 @@ public class NvdCveUpdater implements CachedWebDataSource {
*/ */
private static class TimestampRetriever implements Callable<Long> { private static class TimestampRetriever implements Callable<Long> {
private String url; private final String url;
TimestampRetriever(String url) { TimestampRetriever(String url) {
this.url = url; this.url = url;

View File

@@ -60,7 +60,7 @@ public class CPEHandler extends DefaultHandler {
/** /**
* The list of CPE values. * The list of CPE values.
*/ */
private final List<Cpe> data = new ArrayList<Cpe>(); private final List<Cpe> data = new ArrayList<>();
/** /**
* Returns the list of CPE values. * Returns the list of CPE values.

View File

@@ -229,7 +229,7 @@ public class DownloadTask implements Callable<Future<ProcessTask>> {
is = new FileInputStream(file); is = new FileInputStream(file);
final byte[] buf = new byte[5]; final byte[] buf = new byte[5];
int read = 0; int read;
try { try {
read = is.read(buf); read = is.read(buf);
} catch (IOException ex) { } catch (IOException ex) {

View File

@@ -93,7 +93,7 @@ public class NvdCve12Handler extends DefaultHandler {
skip = "1".equals(reject); skip = "1".equals(reject);
if (!skip) { if (!skip) {
vulnerability = attributes.getValue("name"); vulnerability = attributes.getValue("name");
software = new ArrayList<VulnerableSoftware>(); software = new ArrayList<>();
} else { } else {
vulnerability = null; vulnerability = null;
software = null; software = null;
@@ -132,7 +132,7 @@ public class NvdCve12Handler extends DefaultHandler {
if (!CURRENT_SCHEMA_VERSION.equals(nvdVer)) { if (!CURRENT_SCHEMA_VERSION.equals(nvdVer)) {
throw new SAXNotSupportedException("Schema version " + nvdVer + " is not supported"); throw new SAXNotSupportedException("Schema version " + nvdVer + " is not supported");
} }
vulnerabilities = new HashMap<String, List<VulnerableSoftware>>(); vulnerabilities = new HashMap<>();
} }
} }

View File

@@ -169,17 +169,7 @@ public class ProcessTask implements Callable<ProcessTask> {
properties.save(filePair.getNvdCveInfo()); properties.save(filePair.getNvdCveInfo());
} catch (FileNotFoundException ex) { } catch (FileNotFoundException ex) {
throw new UpdateException(ex); throw new UpdateException(ex);
} catch (ParserConfigurationException ex) { } catch (ParserConfigurationException | SAXException | SQLException | DatabaseException | ClassNotFoundException | IOException 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) {
throw new UpdateException(ex); throw new UpdateException(ex);
} finally { } finally {
filePair.cleanup(); filePair.cleanup();

View File

@@ -33,7 +33,7 @@ public class UpdateableNvdCve implements Iterable<NvdCveInfo>, Iterator<NvdCveIn
/** /**
* A collection of sources of data. * A collection of sources of data.
*/ */
private final Map<String, NvdCveInfo> collection = new TreeMap<String, NvdCveInfo>(); private final Map<String, NvdCveInfo> collection = new TreeMap<>();
/** /**
* Returns the collection of NvdCveInfo objects. This method is mainly used for testing. * Returns the collection of NvdCveInfo objects. This method is mainly used for testing.

View File

@@ -128,15 +128,15 @@ public class Dependency implements Serializable, Comparable<Dependency> {
/** /**
* A collection of related dependencies. * A collection of related dependencies.
*/ */
private Set<Dependency> relatedDependencies = new TreeSet<Dependency>(); private Set<Dependency> relatedDependencies = new TreeSet<>();
/** /**
* A list of projects that reference this dependency. * A list of projects that reference this dependency.
*/ */
private Set<String> projectReferences = new HashSet<String>(); private Set<String> projectReferences = new HashSet<>();
/** /**
* A list of available versions. * A list of available versions.
*/ */
private List<String> availableVersions = new ArrayList<String>(); private List<String> availableVersions = new ArrayList<>();
/** /**
* Returns the package path. * Returns the package path.

View File

@@ -114,23 +114,27 @@ public class EvidenceCollection implements Serializable, Iterable<Evidence> {
* @return Iterable&lt;Evidence&gt; an iterable collection of evidence * @return Iterable&lt;Evidence&gt; an iterable collection of evidence
*/ */
public final Iterable<Evidence> iterator(Confidence confidence) { public final Iterable<Evidence> iterator(Confidence confidence) {
if (confidence == Confidence.HIGHEST) { if (null != confidence) {
return EvidenceCollection.HIGHEST_CONFIDENCE.filter(this.list); switch (confidence) {
} else if (confidence == Confidence.HIGH) { case HIGHEST:
return EvidenceCollection.HIGH_CONFIDENCE.filter(this.list); return EvidenceCollection.HIGHEST_CONFIDENCE.filter(this.list);
} else if (confidence == Confidence.MEDIUM) { case HIGH:
return EvidenceCollection.MEDIUM_CONFIDENCE.filter(this.list); return EvidenceCollection.HIGH_CONFIDENCE.filter(this.list);
} else { case MEDIUM:
return EvidenceCollection.LOW_CONFIDENCE.filter(this.list); return EvidenceCollection.MEDIUM_CONFIDENCE.filter(this.list);
default:
return EvidenceCollection.LOW_CONFIDENCE.filter(this.list);
}
} }
return null;
} }
/** /**
* Creates a new EvidenceCollection. * Creates a new EvidenceCollection.
*/ */
public EvidenceCollection() { public EvidenceCollection() {
list = new TreeSet<Evidence>(); list = new TreeSet<>();
weightedStrings = new HashSet<String>(); weightedStrings = new HashSet<>();
} }
/** /**
@@ -204,7 +208,7 @@ public class EvidenceCollection implements Serializable, Iterable<Evidence> {
if (source == null) { if (source == null) {
return null; return null;
} }
final Set<Evidence> ret = new HashSet<Evidence>(); final Set<Evidence> ret = new HashSet<>();
for (Evidence e : list) { for (Evidence e : list) {
if (source.equals(e.getSource())) { if (source.equals(e.getSource())) {
ret.add(e); ret.add(e);
@@ -224,7 +228,7 @@ public class EvidenceCollection implements Serializable, Iterable<Evidence> {
if (source == null || name == null) { if (source == null || name == null) {
return null; return null;
} }
final Set<Evidence> ret = new HashSet<Evidence>(); final Set<Evidence> ret = new HashSet<>();
for (Evidence e : list) { for (Evidence e : list) {
if (source.equals(e.getSource()) && name.equals(e.getName())) { if (source.equals(e.getSource()) && name.equals(e.getName())) {
ret.add(e); ret.add(e);
@@ -345,7 +349,7 @@ public class EvidenceCollection implements Serializable, Iterable<Evidence> {
* collections * collections
*/ */
public static Set<Evidence> mergeForDisplay(EvidenceCollection... ec) { public static Set<Evidence> mergeForDisplay(EvidenceCollection... ec) {
final Set<Evidence> ret = new TreeSet<Evidence>(); final Set<Evidence> ret = new TreeSet<>();
for (EvidenceCollection col : ec) { for (EvidenceCollection col : ec) {
for (Evidence e : col) { for (Evidence e : col) {
//if (e.isUsed()) { //if (e.isUsed()) {

View File

@@ -47,11 +47,11 @@ public class Vulnerability implements Serializable, Comparable<Vulnerability> {
/** /**
* References for this vulnerability. * References for this vulnerability.
*/ */
private Set<Reference> references = new HashSet<Reference>(); private Set<Reference> references = new HashSet<>();
/** /**
* A set of vulnerable software. * A set of vulnerable software.
*/ */
private Set<VulnerableSoftware> vulnerableSoftware = new HashSet<VulnerableSoftware>(); private Set<VulnerableSoftware> vulnerableSoftware = new HashSet<>();
/** /**
* The CWE for the vulnerability. * The CWE for the vulnerability.
*/ */

View File

@@ -35,7 +35,7 @@ public class ExceptionCollection extends Exception {
/** /**
* A collection of exceptions. * A collection of exceptions.
*/ */
private List<Throwable> exceptions; private final List<Throwable> exceptions;
/** /**
* Flag indicating if a fatal exception occurred that would prevent the * Flag indicating if a fatal exception occurred that would prevent the
* attempt at completing the analysis even if exceptions occurred. * attempt at completing the analysis even if exceptions occurred.
@@ -99,7 +99,7 @@ public class ExceptionCollection extends Exception {
*/ */
public ExceptionCollection(Throwable exceptions, boolean fatal) { public ExceptionCollection(Throwable exceptions, boolean fatal) {
super(); super();
this.exceptions = new ArrayList<Throwable>(); this.exceptions = new ArrayList<>();
this.exceptions.add(exceptions); this.exceptions.add(exceptions);
this.fatal = fatal; this.fatal = fatal;
} }

View File

@@ -66,7 +66,7 @@ public class DependencyVersion implements Iterable<String>, Comparable<Dependenc
* @param version the version string to parse * @param version the version string to parse
*/ */
public final void parseVersion(String version) { public final void parseVersion(String version) {
versionParts = new ArrayList<String>(); versionParts = new ArrayList<>();
if (version != null) { if (version != null) {
final Pattern rx = Pattern.compile("(\\d+[a-z]{1,3}$|[a-z]+\\d+|\\d+|(release|beta|alpha)$)"); final Pattern rx = Pattern.compile("(\\d+[a-z]{1,3}$|[a-z]+\\d+|\\d+|(release|beta|alpha)$)");
final Matcher matcher = rx.matcher(version.toLowerCase()); final Matcher matcher = rx.matcher(version.toLowerCase());

View File

@@ -74,7 +74,7 @@ public final class DependencyVersionUtil {
//'-' is a special case used within the CVE entries, just include it as the version. //'-' is a special case used within the CVE entries, just include it as the version.
if ("-".equals(text)) { if ("-".equals(text)) {
final DependencyVersion dv = new DependencyVersion(); final DependencyVersion dv = new DependencyVersion();
final List<String> list = new ArrayList<String>(); final List<String> list = new ArrayList<>();
list.add(text); list.add(text);
dv.setVersionParts(list); dv.setVersionParts(list);
return dv; return dv;

View File

@@ -197,9 +197,7 @@ public final class ExtractionUtil {
extractFile(input, destination, filter, entry); extractFile(input, destination, filter, entry);
} }
} }
} catch (IOException ex) { } catch (IOException | AnalysisException ex) {
throw new ArchiveExtractionException(ex);
} catch (Throwable ex) {
throw new ArchiveExtractionException(ex); throw new ArchiveExtractionException(ex);
} finally { } finally {
FileUtils.close(input); FileUtils.close(input);

View File

@@ -48,15 +48,15 @@ public class FileFilterBuilder {
/** /**
* A set of filenames to filter. * A set of filenames to filter.
*/ */
private final Set<String> filenames = new HashSet<String>(); private final Set<String> filenames = new HashSet<>();
/** /**
* A set of extensions to filter. * A set of extensions to filter.
*/ */
private final Set<String> extensions = new HashSet<String>(); private final Set<String> extensions = new HashSet<>();
/** /**
* An array list of file filters. * An array list of file filters.
*/ */
private final List<IOFileFilter> fileFilters = new ArrayList<IOFileFilter>(); private final List<IOFileFilter> fileFilters = new ArrayList<>();
/** /**
* Create a new instance and return it. This method is for convenience in using the builder pattern within a single statement. * 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(); final OrFileFilter filter = new OrFileFilter();
if (!filenames.isEmpty()) { if (!filenames.isEmpty()) {
filter.addFileFilter(new NameFileFilter(new ArrayList<String>(filenames))); filter.addFileFilter(new NameFileFilter(new ArrayList<>(filenames)));
} }
if (!extensions.isEmpty()) { if (!extensions.isEmpty()) {
filter.addFileFilter(new SuffixFileFilter(new ArrayList<String>(extensions), IOCase.INSENSITIVE)); filter.addFileFilter(new SuffixFileFilter(new ArrayList<>(extensions), IOCase.INSENSITIVE));
} }
for (IOFileFilter iof : fileFilters) { for (IOFileFilter iof : fileFilters) {
filter.addFileFilter(iof); filter.addFileFilter(iof);

View File

@@ -3,7 +3,7 @@ package org.owasp.dependencycheck.utils;
import java.util.Iterator; import java.util.Iterator;
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
/* /**
* This is an abstract filter that can be used to filter iterable list. * This is an abstract filter that can be used to filter iterable list.
* *
* This Filter class was copied from: * This Filter class was copied from:
@@ -11,15 +11,35 @@ import java.util.NoSuchElementException;
* *
* Erik Rasmussen - © 2006 - 2012 All Rights Reserved. @author Erik Rasmussen * Erik Rasmussen - © 2006 - 2012 All Rights Reserved. @author Erik Rasmussen
* https://plus.google.com/115403795880834599019/?rel=author * https://plus.google.com/115403795880834599019/?rel=author
*
* @param <T> the type to filter
*/ */
public abstract class Filter<T> { public abstract class Filter<T> {
/**
* 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); public abstract boolean passes(T object);
/**
* Filters a given iterator.
*
* @param iterator the iterator to filter
* @return the filtered iterator
*/
public Iterator<T> filter(Iterator<T> iterator) { public Iterator<T> filter(Iterator<T> iterator) {
return new FilterIterator(iterator); return new FilterIterator(iterator);
} }
/**
* Filters a given iterable.
*
* @param iterable the iterable to filter
* @return the filtered iterable
*/
public Iterable<T> filter(final Iterable<T> iterable) { public Iterable<T> filter(final Iterable<T> iterable) {
return new Iterable<T>() { return new Iterable<T>() {

View File

@@ -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. * A listing of domain parts that should not be used as evidence. Yes, this is an incomplete list.
*/ */
private static final Set<String> IGNORE_LIST = new HashSet<String>( private static final Set<String> IGNORE_LIST = new HashSet<>(
Arrays.asList("www", "com", "org", "gov", "info", "name", "net", "pro", "tel", "mobi", "xxx")); 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 * @throws MalformedURLException thrown if the URL is malformed
*/ */
public static List<String> extractImportantUrlData(String text) throws MalformedURLException { public static List<String> extractImportantUrlData(String text) throws MalformedURLException {
final List<String> importantParts = new ArrayList<String>(); final List<String> importantParts = new ArrayList<>();
final URL url = new URL(text); final URL url = new URL(text);
final String[] domain = url.getHost().split("\\."); final String[] domain = url.getHost().split("\\.");
//add the domain except www and the tld. //add the domain except www and the tld.

View File

@@ -74,7 +74,7 @@ public class Model {
/** /**
* The list of licenses. * The list of licenses.
*/ */
private final List<License> licenses = new ArrayList<License>(); private final List<License> licenses = new ArrayList<>();
/** /**
* The project URL. * The project URL.
*/ */

View File

@@ -91,7 +91,7 @@ public class PomHandler extends DefaultHandler {
/** /**
* The stack of elements processed; used to determine the parent node. * The stack of elements processed; used to determine the parent node.
*/ */
private final Deque<String> stack = new ArrayDeque<String>(); private final Deque<String> stack = new ArrayDeque<>();
/** /**
* The license object. * The license object.
*/ */

View File

@@ -71,7 +71,7 @@ public class SuppressionHandler extends DefaultHandler {
/** /**
* A list of suppression rules. * A list of suppression rules.
*/ */
private final List<SuppressionRule> suppressionRules = new ArrayList<SuppressionRule>(); private final List<SuppressionRule> suppressionRules = new ArrayList<>();
/** /**
* Get the value of suppressionRules. * Get the value of suppressionRules.

View File

@@ -26,7 +26,6 @@ import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream; import java.util.zip.ZipInputStream;
import org.junit.AfterClass; import org.junit.AfterClass;
import org.junit.Before; import org.junit.Before;
import org.junit.BeforeClass;
import org.owasp.dependencycheck.data.nvdcve.CveDB; import org.owasp.dependencycheck.data.nvdcve.CveDB;
import org.owasp.dependencycheck.utils.Settings; import org.owasp.dependencycheck.utils.Settings;
import org.slf4j.Logger; import org.slf4j.Logger;

View File

@@ -136,7 +136,7 @@ public class JarAnalyzerTest extends BaseTest {
File file = BaseTest.getResourceAsFile(this, "xalan-2.7.0.jar"); File file = BaseTest.getResourceAsFile(this, "xalan-2.7.0.jar");
Dependency result = new Dependency(file); Dependency result = new Dependency(file);
JarAnalyzer instance = new JarAnalyzer(); JarAnalyzer instance = new JarAnalyzer();
List<JarAnalyzer.ClassNameInformation> cni = new ArrayList<JarAnalyzer.ClassNameInformation>(); List<JarAnalyzer.ClassNameInformation> cni = new ArrayList<>();
instance.parseManifest(result, cni); instance.parseManifest(result, cni);
assertTrue(result.getVersionEvidence().getEvidence("manifest: org/apache/xalan/").size() > 0); assertTrue(result.getVersionEvidence().getEvidence("manifest: org/apache/xalan/").size() > 0);

View File

@@ -45,6 +45,7 @@ import org.owasp.dependencycheck.utils.Settings;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import org.owasp.dependencycheck.exception.InitializationException;
/** /**
* Unit tests for {@link RubyBundleAuditAnalyzer}. * 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.getVersionEvidence().toString().toLowerCase().contains("2.2.2"));
assertTrue(dependency.getFilePath().endsWith(resource)); assertTrue(dependency.getFilePath().endsWith(resource));
assertTrue(dependency.getFileName().equals("Gemfile.lock")); 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\"."); 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); 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(); Vulnerability vulnerability = dependency.getVulnerabilities().first();
assertEquals(vulnerability.getCvssScore(), 5.0f, 0.0); 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\"."); 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); Assume.assumeNoException("Exception setting up RubyBundleAuditAnalyzer; bundle audit may not be installed, or property \"analyzer.bundle.audit.path\" may not be set.", e);
} }

View File

@@ -61,19 +61,19 @@ public class FieldAnalyzerTest extends BaseTest {
String field2 = "vendor"; String field2 = "vendor";
String text2 = "springsource"; String text2 = "springsource";
IndexWriter w = createIndex(analyzer, index); try (IndexWriter w = createIndex(analyzer, index)) {
addDoc(w, field1, text1, field2, text2); addDoc(w, field1, text1, field2, text2);
text1 = "x-stream"; text1 = "x-stream";
text2 = "xstream"; text2 = "xstream";
addDoc(w, field1, text1, field2, text2); addDoc(w, field1, text1, field2, text2);
w.close(); }
//Analyzer searchingAnalyzer = new SearchFieldAnalyzer(LuceneUtils.CURRENT_VERSION); //Analyzer searchingAnalyzer = new SearchFieldAnalyzer(LuceneUtils.CURRENT_VERSION);
String querystr = "product:\"(Spring Framework Core)\" vendor:(SpringSource)"; String querystr = "product:\"(Spring Framework Core)\" vendor:(SpringSource)";
SearchFieldAnalyzer searchAnalyzerProduct = new SearchFieldAnalyzer(LuceneUtils.CURRENT_VERSION); SearchFieldAnalyzer searchAnalyzerProduct = new SearchFieldAnalyzer(LuceneUtils.CURRENT_VERSION);
SearchFieldAnalyzer searchAnalyzerVendor = new SearchFieldAnalyzer(LuceneUtils.CURRENT_VERSION); SearchFieldAnalyzer searchAnalyzerVendor = new SearchFieldAnalyzer(LuceneUtils.CURRENT_VERSION);
HashMap<String, Analyzer> map = new HashMap<String, Analyzer>(); HashMap<String, Analyzer> map = new HashMap<>();
map.put(field1, searchAnalyzerProduct); map.put(field1, searchAnalyzerProduct);
map.put(field2, searchAnalyzerVendor); map.put(field2, searchAnalyzerVendor);
PerFieldAnalyzerWrapper wrapper = new PerFieldAnalyzerWrapper(new StandardAnalyzer(LuceneUtils.CURRENT_VERSION), map); PerFieldAnalyzerWrapper wrapper = new PerFieldAnalyzerWrapper(new StandardAnalyzer(LuceneUtils.CURRENT_VERSION), map);

View File

@@ -31,7 +31,7 @@ import org.apache.lucene.analysis.core.KeywordTokenizer;
*/ */
public class UrlTokenizingFilterTest extends BaseTokenStreamTestCase { public class UrlTokenizingFilterTest extends BaseTokenStreamTestCase {
private Analyzer analyzer; private final Analyzer analyzer;
public UrlTokenizingFilterTest() { public UrlTokenizingFilterTest() {
analyzer = new Analyzer() { analyzer = new Analyzer() {

View File

@@ -36,9 +36,9 @@ public class ConnectionFactoryTest extends BaseDBTestCase {
@Test @Test
public void testInitialize() throws DatabaseException, SQLException { public void testInitialize() throws DatabaseException, SQLException {
ConnectionFactory.initialize(); ConnectionFactory.initialize();
Connection result = ConnectionFactory.getConnection(); try (Connection result = ConnectionFactory.getConnection()) {
assertNotNull(result); assertNotNull(result);
result.close(); }
ConnectionFactory.cleanup(); ConnectionFactory.cleanup();
} }
} }

View File

@@ -21,7 +21,6 @@ import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import org.junit.Test; import org.junit.Test;
import org.owasp.dependencycheck.BaseTest; 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.exception.UpdateException;
import org.owasp.dependencycheck.data.update.nvd.UpdateableNvdCve; import org.owasp.dependencycheck.data.update.nvd.UpdateableNvdCve;

View File

@@ -17,7 +17,6 @@
*/ */
package org.owasp.dependencycheck.data.update.nvd; package org.owasp.dependencycheck.data.update.nvd;
import org.owasp.dependencycheck.data.update.nvd.NvdCveInfo;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import org.junit.Test; import org.junit.Test;
import org.owasp.dependencycheck.BaseTest; import org.owasp.dependencycheck.BaseTest;

View File

@@ -17,7 +17,6 @@
*/ */
package org.owasp.dependencycheck.data.update.nvd; package org.owasp.dependencycheck.data.update.nvd;
import org.owasp.dependencycheck.data.update.nvd.NvdCve12Handler;
import java.io.File; import java.io.File;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;

View File

@@ -17,10 +17,11 @@
*/ */
package org.owasp.dependencycheck.data.update.nvd; package org.owasp.dependencycheck.data.update.nvd;
import org.owasp.dependencycheck.data.update.nvd.NvdCve20Handler;
import java.io.File; import java.io.File;
import java.io.IOException;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory; import javax.xml.parsers.SAXParserFactory;
@@ -29,6 +30,7 @@ import static org.junit.Assert.assertTrue;
import org.junit.Test; import org.junit.Test;
import org.owasp.dependencycheck.BaseTest; import org.owasp.dependencycheck.BaseTest;
import org.owasp.dependencycheck.dependency.VulnerableSoftware; 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(); NvdCve20Handler instance = new NvdCve20Handler();
saxParser.parse(file, instance); saxParser.parse(file, instance);
} catch (Throwable ex) { } catch (ParserConfigurationException | SAXException | IOException ex) {
ex.printStackTrace(); ex.printStackTrace();
results = ex; results = ex;
} }
@@ -80,7 +82,7 @@ public class NvdCve_2_0_HandlerTest extends BaseTest {
saxParser.parse(file20, instance); saxParser.parse(file20, instance);
assertTrue(instance.getTotalNumberOfEntries()==1); assertTrue(instance.getTotalNumberOfEntries()==1);
} catch (Throwable ex) { } catch (ParserConfigurationException | SAXException | IOException ex) {
results = ex; results = ex;
} }
assertTrue("Exception thrown during parse of 2012 CVE version 2.0?", results == null); assertTrue("Exception thrown during parse of 2012 CVE version 2.0?", results == null);

View File

@@ -48,12 +48,12 @@ public class FilterTest extends BaseTest {
*/ */
@Test @Test
public void testFilter_Iterable() { public void testFilter_Iterable() {
List<String> testData = new ArrayList<String>(); List<String> testData = new ArrayList<>();
testData.add("keep"); testData.add("keep");
testData.add("remove"); testData.add("remove");
testData.add("keep"); testData.add("keep");
List<String> expResults = new ArrayList<String>(); List<String> expResults = new ArrayList<>();
expResults.add("keep"); expResults.add("keep");
expResults.add("keep"); expResults.add("keep");

View File

@@ -248,7 +248,7 @@ public class ModelTest extends BaseTest {
public void testGetLicenses() { public void testGetLicenses() {
Model instance = new Model(); Model instance = new Model();
instance.addLicense(new License("name", "url")); instance.addLicense(new License("name", "url"));
List<License> expResult = new ArrayList<License>(); List<License> expResult = new ArrayList<>();
expResult.add(new License("name", "url")); expResult.add(new License("name", "url"));
List<License> result = instance.getLicenses(); List<License> result = instance.getLicenses();
assertEquals(expResult, result); assertEquals(expResult, result);

View File

@@ -86,7 +86,7 @@ public class SuppressionRuleTest extends BaseTest {
@Test @Test
public void testGetCvssBelow() { public void testGetCvssBelow() {
SuppressionRule instance = new SuppressionRule(); SuppressionRule instance = new SuppressionRule();
List<Float> cvss = new ArrayList<Float>(); List<Float> cvss = new ArrayList<>();
instance.setCvssBelow(cvss); instance.setCvssBelow(cvss);
assertFalse(instance.hasCvssBelow()); assertFalse(instance.hasCvssBelow());
instance.addCvssBelow(0.7f); instance.addCvssBelow(0.7f);
@@ -101,7 +101,7 @@ public class SuppressionRuleTest extends BaseTest {
@Test @Test
public void testCwe() { public void testCwe() {
SuppressionRule instance = new SuppressionRule(); SuppressionRule instance = new SuppressionRule();
List<String> cwe = new ArrayList<String>(); List<String> cwe = new ArrayList<>();
instance.setCwe(cwe); instance.setCwe(cwe);
assertFalse(instance.hasCwe()); assertFalse(instance.hasCwe());
instance.addCwe("2"); instance.addCwe("2");
@@ -116,7 +116,7 @@ public class SuppressionRuleTest extends BaseTest {
@Test @Test
public void testCve() { public void testCve() {
SuppressionRule instance = new SuppressionRule(); SuppressionRule instance = new SuppressionRule();
List<String> cve = new ArrayList<String>(); List<String> cve = new ArrayList<>();
instance.setCve(cve); instance.setCve(cve);
assertFalse(instance.hasCve()); assertFalse(instance.hasCve());
instance.addCve("CVE-2013-1337"); instance.addCve("CVE-2013-1337");

View File

@@ -153,8 +153,8 @@ public class AggregateMojo extends BaseDependencyCheckMojo {
if (project == null) { if (project == null) {
return Collections.emptySet(); return Collections.emptySet();
} }
final Set<MavenProject> descendants = new HashSet<MavenProject>(); final Set<MavenProject> descendants = new HashSet<>();
int size = 0; int size;
if (getLog().isDebugEnabled()) { if (getLog().isDebugEnabled()) {
getLog().debug(String.format("Collecting descendants of %s", project.getName())); getLog().debug(String.format("Collecting descendants of %s", project.getName()));
} }
@@ -191,7 +191,7 @@ public class AggregateMojo extends BaseDependencyCheckMojo {
} }
} }
} }
final Set<MavenProject> addedDescendants = new HashSet<MavenProject>(); final Set<MavenProject> addedDescendants = new HashSet<>();
for (MavenProject dec : descendants) { for (MavenProject dec : descendants) {
for (String mod : dec.getModules()) { for (String mod : dec.getModules()) {
try { try {

View File

@@ -114,6 +114,9 @@ public abstract class BaseDependencyCheckMojo extends AbstractMojo implements Ma
@Component @Component
private ArtifactResolver artifactResolver; private ArtifactResolver artifactResolver;
/**
* The Maven Session.
*/
@Parameter( defaultValue = "${session}", readonly = true, required = true ) @Parameter( defaultValue = "${session}", readonly = true, required = true )
protected MavenSession session; protected MavenSession session;

View File

@@ -70,7 +70,7 @@ public class BaseDependencyCheckMojoTest extends BaseTest {
MavenProject project = new MockUp<MavenProject>() { MavenProject project = new MockUp<MavenProject>() {
@Mock @Mock
public Set<Artifact> getArtifacts() { public Set<Artifact> getArtifacts() {
Set<Artifact> artifacts = new HashSet<Artifact>(); Set<Artifact> artifacts = new HashSet<>();
Artifact a = new ArtifactStub(); Artifact a = new ArtifactStub();
try { try {
File file = new File(Test.class.getProtectionDomain().getCodeSource().getLocation().toURI()); 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 { public class BaseDependencyCheckMojoImpl extends BaseDependencyCheckMojo {
@Override @Override

View File

@@ -36,7 +36,7 @@ public class ExpectedOjectInputStream extends ObjectInputStream {
/** /**
* The list of fully qualified class names that are able to be deserialized. * The list of fully qualified class names that are able to be deserialized.
*/ */
private List<String> expected = new ArrayList<String>(); private List<String> expected = new ArrayList<>();
/** /**
* Constructs a new ExpectedOjectInputStream that can be used to securely deserialize an object by restricting the classes * Constructs a new ExpectedOjectInputStream that can be used to securely deserialize an object by restricting the classes

View File

@@ -283,7 +283,7 @@ public class SSLSocketFactoryEx extends SSLSocketFactory {
} }
} }
final List<String> aa = new ArrayList<String>(); final List<String> aa = new ArrayList<>();
for (String preferredProtocol : preferredProtocols) { for (String preferredProtocol : preferredProtocols) {
final int idx = Arrays.binarySearch(availableProtocols, preferredProtocol); final int idx = Arrays.binarySearch(availableProtocols, preferredProtocol);
if (idx >= 0) { if (idx >= 0) {

View File

@@ -49,7 +49,7 @@ public final class Settings {
/** /**
* Thread local settings. * Thread local settings.
*/ */
private static final ThreadLocal<Settings> LOCAL_SETTINGS = new ThreadLocal<Settings>(); private static final ThreadLocal<Settings> LOCAL_SETTINGS = new ThreadLocal<>();
/** /**
* The properties. * The properties.
*/ */
@@ -530,9 +530,7 @@ public final class Settings {
private static void logProperties(String header, Properties properties) { private static void logProperties(String header, Properties properties) {
if (LOGGER.isDebugEnabled()) { if (LOGGER.isDebugEnabled()) {
final StringWriter sw = new StringWriter(); final StringWriter sw = new StringWriter();
PrintWriter pw = null; try (PrintWriter pw = new PrintWriter(sw)) {
try {
pw = new PrintWriter(sw);
pw.format("%s:%n%n", header); pw.format("%s:%n%n", header);
final Enumeration<?> e = properties.propertyNames(); final Enumeration<?> e = properties.propertyNames();
while (e.hasMoreElements()) { while (e.hasMoreElements()) {
@@ -548,10 +546,6 @@ public final class Settings {
} }
pw.flush(); pw.flush();
LOGGER.debug(sw.toString()); LOGGER.debug(sw.toString());
} finally {
if (pw != null) {
pw.close();
}
} }
} }

View File

@@ -20,7 +20,6 @@ package org.owasp.dependencycheck.utils;
import java.io.File; import java.io.File;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import org.junit.Test; import org.junit.Test;
import org.owasp.dependencycheck.utils.Downloader;
/** /**
* *

View File

@@ -69,15 +69,16 @@ public class ExpectedOjectInputStreamTest {
*/ */
@Test(expected = java.io.InvalidClassException.class) @Test(expected = java.io.InvalidClassException.class)
public void testResolveClassException() throws Exception { public void testResolveClassException() throws Exception {
List<SimplePojo> data = new ArrayList<SimplePojo>(); List<SimplePojo> data = new ArrayList<>();
data.add(new SimplePojo()); data.add(new SimplePojo());
ByteArrayOutputStream mem = new ByteArrayOutputStream(); ByteArrayOutputStream mem = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(mem)); byte[] buf;
out.writeObject(data); try (ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(mem))) {
out.flush(); out.writeObject(data);
byte[] buf = mem.toByteArray(); out.flush();
out.close(); buf = mem.toByteArray();
}
ByteArrayInputStream in = new ByteArrayInputStream(buf); ByteArrayInputStream in = new ByteArrayInputStream(buf);
ExpectedOjectInputStream instance = new ExpectedOjectInputStream(in, "java.util.ArrayList", "org.owasp.dependencycheck.utils.SimplePojo"); ExpectedOjectInputStream instance = new ExpectedOjectInputStream(in, "java.util.ArrayList", "org.owasp.dependencycheck.utils.SimplePojo");