fixed issues related to making the cveDb a singleton

This commit is contained in:
Jeremy Long
2017-03-31 06:58:37 -04:00
parent 539bd754df
commit e2a1a59543
20 changed files with 153 additions and 110 deletions

View File

@@ -941,14 +941,11 @@ public class Check extends Update {
} }
} }
DatabaseProperties prop = null; DatabaseProperties prop = null;
try { try (CveDB cve = CveDB.getInstance()) {
final CveDB cve = CveDB.getInstance();
prop = cve.getDatabaseProperties(); prop = cve.getDatabaseProperties();
} catch (DatabaseException ex) { } catch (DatabaseException ex) {
//TODO shouldn't this be a fatal exception //TODO shouldn't this be a fatal exception
log("Unable to retrieve DB Properties", ex, Project.MSG_DEBUG); log("Unable to retrieve DB Properties", ex, Project.MSG_DEBUG);
} finally {
CveDB.close();
} }
final ReportGenerator reporter = new ReportGenerator(getProjectName(), engine.getDependencies(), engine.getAnalyzers(), prop); final ReportGenerator reporter = new ReportGenerator(getProjectName(), engine.getDependencies(), engine.getAnalyzers(), prop);

View File

@@ -33,7 +33,6 @@ import static org.junit.Assert.assertTrue;
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;
/** /**
* *
* @author Jeremy Long * @author Jeremy Long
@@ -50,7 +49,6 @@ public class DependencyCheckTaskTest {
public void setUp() throws Exception { public void setUp() throws Exception {
Settings.initialize(); Settings.initialize();
BaseDBTestCase.ensureDBExists(); BaseDBTestCase.ensureDBExists();
CveDB.getInstance().openDatabase();
final String buildFile = this.getClass().getClassLoader().getResource("build.xml").getPath(); final String buildFile = this.getClass().getClassLoader().getResource("build.xml").getPath();
buildFileRule.configureProject(buildFile); buildFileRule.configureProject(buildFile);
} }
@@ -60,10 +58,6 @@ public class DependencyCheckTaskTest {
//no cleanup... //no cleanup...
//executeTarget("cleanup"); //executeTarget("cleanup");
Settings.cleanup(true); Settings.cleanup(true);
try {
CveDB.getInstance().closeDatabase();
} catch (DatabaseException ex) {
}
} }
/** /**

View File

@@ -282,10 +282,15 @@ public class App {
exCol = ex; exCol = ex;
} }
final List<Dependency> dependencies = engine.getDependencies(); final List<Dependency> dependencies = engine.getDependencies();
final CveDB cve = CveDB.getInstance(); DatabaseProperties prop = null;
final DatabaseProperties prop = cve.getDatabaseProperties(); try (CveDB cve = CveDB.getInstance()) {
prop = cve.getDatabaseProperties();
} catch (DatabaseException ex) {
//TODO shouldn't this be a fatal exception
LOGGER.debug("Unable to retrieve DB Properties", ex);
}
final ReportGenerator report = new ReportGenerator(applicationName, dependencies, engine.getAnalyzers(), prop); final ReportGenerator report = new ReportGenerator(applicationName, dependencies, engine.getAnalyzers(), prop);
CveDB.close();
try { try {
report.generateReports(reportDirectory, outputFormat); report.generateReports(reportDirectory, outputFormat);
} catch (ReportException ex) { } catch (ReportException ex) {

View File

@@ -38,6 +38,7 @@ import org.slf4j.LoggerFactory;
import java.io.File; import java.io.File;
import java.io.FileFilter; import java.io.FileFilter;
import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.Collections; import java.util.Collections;
@@ -83,6 +84,10 @@ public class Engine implements FileFilter {
* services. * services.
*/ */
private ClassLoader serviceClassLoader = Thread.currentThread().getContextClassLoader(); private ClassLoader serviceClassLoader = Thread.currentThread().getContextClassLoader();
/**
* A reference to the database.
*/
private CveDB database = null;
/** /**
* The Logger for use throughout the class. * The Logger for use throughout the class.
*/ */
@@ -126,7 +131,10 @@ public class Engine implements FileFilter {
* Properly cleans up resources allocated during analysis. * Properly cleans up resources allocated during analysis.
*/ */
public void cleanup() { public void cleanup() {
CveDB.close(); if (database != null) {
database.close();
database = null;
}
ConnectionFactory.cleanup(); ConnectionFactory.cleanup();
} }
@@ -479,31 +487,14 @@ public class Engine implements FileFilter {
*/ */
public void analyzeDependencies() throws ExceptionCollection { public void analyzeDependencies() throws ExceptionCollection {
final List<Throwable> exceptions = Collections.synchronizedList(new ArrayList<Throwable>()); final List<Throwable> exceptions = Collections.synchronizedList(new ArrayList<Throwable>());
boolean autoUpdate = true;
try { initializeAndUpdateDatabase(exceptions);
autoUpdate = Settings.getBoolean(Settings.KEYS.AUTO_UPDATE);
} catch (InvalidSettingException ex) {
LOGGER.debug("Invalid setting for auto-update; using true.");
exceptions.add(ex);
}
if (autoUpdate) {
try {
doUpdates();
} catch (UpdateException ex) {
exceptions.add(ex);
LOGGER.warn("Unable to update Cached Web DataSource, using local "
+ "data instead. Results may not include recent vulnerabilities.");
LOGGER.debug("Update Error", ex);
}
}
//need to ensure that data exists //need to ensure that data exists
try { try {
ensureDataExists(); ensureDataExists();
} catch (NoDataException ex) { } catch (NoDataException ex) {
throwFatalExceptionCollection("Unable to continue dependency-check analysis.", ex, exceptions); throwFatalExceptionCollection("Unable to continue dependency-check analysis.", ex, exceptions);
} catch (DatabaseException ex) {
throwFatalExceptionCollection("Unable to connect to the dependency-check database.", ex, exceptions);
} }
LOGGER.debug("\n----------------------------------------------------\nBEGIN ANALYSIS\n----------------------------------------------------"); LOGGER.debug("\n----------------------------------------------------\nBEGIN ANALYSIS\n----------------------------------------------------");
@@ -550,6 +541,47 @@ public class Engine implements FileFilter {
} }
} }
/**
* Performs any necessary updates and initializes the database.
*
* @param exceptions a collection to store non-fatal exceptions
* @throws ExceptionCollection thrown if fatal exceptions occur
*/
private void initializeAndUpdateDatabase(final List<Throwable> exceptions) throws ExceptionCollection {
boolean autoUpdate = true;
try {
autoUpdate = Settings.getBoolean(Settings.KEYS.AUTO_UPDATE);
} catch (InvalidSettingException ex) {
LOGGER.debug("Invalid setting for auto-update; using true.");
exceptions.add(ex);
}
if (autoUpdate) {
try {
database = CveDB.getInstance();
doUpdates();
} catch (UpdateException ex) {
exceptions.add(ex);
LOGGER.warn("Unable to update Cached Web DataSource, using local "
+ "data instead. Results may not include recent vulnerabilities.");
LOGGER.debug("Update Error", ex);
} catch (DatabaseException ex) {
throw new ExceptionCollection("Unable to connect to the database", ex);
}
} else {
try {
if (ConnectionFactory.isH2Connection() && !ConnectionFactory.h2DataFileExists()) {
throw new ExceptionCollection(new NoDataException("Autoupdate is disabled and the database does not exist"), true);
} else {
database = CveDB.getInstance();
}
} catch (IOException ex) {
throw new ExceptionCollection(new DatabaseException("Autoupdate is disabled and unable to connect to the database"), true);
} catch (DatabaseException ex) {
throwFatalExceptionCollection("Unable to connect to the dependency-check database.", ex, exceptions);
}
}
}
/** /**
* Executes executes the analyzer using multiple threads. * Executes executes the analyzer using multiple threads.
* *
@@ -742,15 +774,11 @@ public class Engine implements FileFilter {
* NoDataException is thrown. * NoDataException is thrown.
* *
* @throws NoDataException thrown if no data exists in the CPE Index * @throws NoDataException thrown if no data exists in the CPE Index
* @throws DatabaseException thrown if there is an exception opening the
* database
*/ */
private void ensureDataExists() throws NoDataException, DatabaseException { private void ensureDataExists() throws NoDataException {
final CveDB cve = CveDB.getInstance(); if (database == null || !database.dataExists()) {
if (!cve.dataExists()) {
throw new NoDataException("No documents exist"); throw new NoDataException("No documents exist");
} }
CveDB.close();
} }
/** /**

View File

@@ -843,15 +843,11 @@ 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; try (CveDB cve = CveDB.getInstance()) {
try {
cve = CveDB.getInstance();
prop = cve.getDatabaseProperties(); prop = cve.getDatabaseProperties();
} catch (DatabaseException ex) { } catch (DatabaseException ex) {
//TODO shouldn't this throw an exception or return? //TODO shouldn't this be a fatal exception
LOGGER.debug("Unable to retrieve DB Properties", ex); LOGGER.debug("Unable to retrieve DB Properties", ex);
} finally {
CveDB.close();
} }
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 {

View File

@@ -183,7 +183,7 @@ public class CPEAnalyzer extends AbstractAnalyzer {
@Override @Override
public void closeAnalyzer() { public void closeAnalyzer() {
if (cve != null) { if (cve != null) {
CveDB.close(); cve.close();
cve = null; cve = null;
} }
if (cpe != null) { if (cpe != null) {

View File

@@ -68,7 +68,7 @@ public class NvdCveAnalyzer extends AbstractAnalyzer {
*/ */
@Override @Override
public void closeAnalyzer() { public void closeAnalyzer() {
CveDB.close(); cveDB.close();
cveDB = null; cveDB = null;
} }

View File

@@ -132,7 +132,8 @@ public class RubyBundleAuditAnalyzer extends AbstractFileTypeAnalyzer {
LOGGER.info("Launching: " + args + " from " + folder); LOGGER.info("Launching: " + args + " from " + folder);
return builder.start(); return builder.start();
} catch (IOException ioe) { } catch (IOException ioe) {
throw new AnalysisException("bundle-audit failure", ioe); throw new AnalysisException("bundle-audit initialization failure; this error can be ignored if you are not analyzing Ruby. "
+ "Otherwise ensure that bundle-audit is installed and the path to bundle audit is correctly specified", ioe);
} }
} }
@@ -159,7 +160,6 @@ public class RubyBundleAuditAnalyzer extends AbstractFileTypeAnalyzer {
} catch (AnalysisException ae) { } catch (AnalysisException ae) {
setEnabled(false); setEnabled(false);
cvedb = null;
final String msg = String.format("Exception from bundle-audit process: %s. Disabling %s", ae.getCause(), ANALYZER_NAME); final String msg = String.format("Exception from bundle-audit process: %s. Disabling %s", ae.getCause(), ANALYZER_NAME);
throw new InitializationException(msg, ae); throw new InitializationException(msg, ae);
} catch (IOException ex) { } catch (IOException ex) {
@@ -213,9 +213,12 @@ public class RubyBundleAuditAnalyzer extends AbstractFileTypeAnalyzer {
*/ */
@Override @Override
public void closeAnalyzer() { public void closeAnalyzer() {
CveDB.close(); if (cvedb != null) {
cvedb.close();
cvedb = null; cvedb = null;
} }
}
/** /**
* Returns the name of the analyzer. * Returns the name of the analyzer.
* *

View File

@@ -241,13 +241,31 @@ public final class ConnectionFactory {
* @throws IOException thrown if the data directory does not exist and * @throws IOException thrown if the data directory does not exist and
* cannot be created * cannot be created
*/ */
private static boolean h2DataFileExists() throws IOException { public static boolean h2DataFileExists() throws IOException {
final File dir = Settings.getDataDirectory(); final File dir = Settings.getDataDirectory();
final String fileName = Settings.getString(Settings.KEYS.DB_FILE_NAME); final String fileName = Settings.getString(Settings.KEYS.DB_FILE_NAME);
final File file = new File(dir, fileName); final File file = new File(dir, fileName);
return file.exists(); return file.exists();
} }
/**
* Determines if the connection string is for an H2 database.
*
* @return true if the connection string is for an H2 database
*/
public static boolean isH2Connection() {
String connStr;
try {
connStr = Settings.getConnectionString(
Settings.KEYS.DB_CONNECTION_STRING,
Settings.KEYS.DB_FILE_NAME);
} catch (IOException ex) {
LOGGER.debug("Unable to get connectionn string", ex);
return false;
}
return connStr.startsWith("jdbc:h2:file:");
}
/** /**
* Creates the database structure (tables and indexes) to store the CVE * Creates the database structure (tables and indexes) to store the CVE
* data. * data.

View File

@@ -58,7 +58,7 @@ import static org.owasp.dependencycheck.data.nvdcve.CveDB.PreparedStatementCveDb
* @author Jeremy Long * @author Jeremy Long
*/ */
@ThreadSafe @ThreadSafe
public final class CveDB { public final class CveDB implements AutoCloseable {
/** /**
* Singleton instance of the CveDB. * Singleton instance of the CveDB.
@@ -253,7 +253,8 @@ public final class CveDB {
* Closes the database connection. Close should be called on this object * Closes the database connection. Close should be called on this object
* when it is done being used. * when it is done being used.
*/ */
public static synchronized void close() { @Override
public synchronized void close() {
if (instance != null) { if (instance != null) {
instance.usageCount -= 1; instance.usageCount -= 1;
if (instance.usageCount <= 0 && instance.isOpen()) { if (instance.usageCount <= 0 && instance.isOpen()) {
@@ -281,7 +282,7 @@ public final class CveDB {
* *
* @return whether the database connection is open or closed * @return whether the database connection is open or closed
*/ */
private synchronized boolean isOpen() { protected synchronized boolean isOpen() {
return connection != null; return connection != null;
} }

View File

@@ -93,8 +93,7 @@ public class EngineVersionCheck implements CachedWebDataSource {
*/ */
@Override @Override
public void update() throws UpdateException { public void update() throws UpdateException {
try { try (CveDB db = CveDB.getInstance()) {
final CveDB db = CveDB.getInstance();
final boolean autoupdate = Settings.getBoolean(Settings.KEYS.AUTO_UPDATE, true); final boolean autoupdate = Settings.getBoolean(Settings.KEYS.AUTO_UPDATE, true);
final boolean enabled = Settings.getBoolean(Settings.KEYS.UPDATE_VERSION_CHECK_ENABLED, true); final boolean enabled = Settings.getBoolean(Settings.KEYS.UPDATE_VERSION_CHECK_ENABLED, true);
final String original = Settings.getString(Settings.KEYS.CVE_ORIGINAL_MODIFIED_20_URL); final String original = Settings.getString(Settings.KEYS.CVE_ORIGINAL_MODIFIED_20_URL);
@@ -127,8 +126,6 @@ public class EngineVersionCheck implements CachedWebDataSource {
throw new UpdateException("Error occurred updating database properties."); throw new UpdateException("Error occurred updating database properties.");
} catch (InvalidSettingException ex) { } catch (InvalidSettingException ex) {
LOGGER.debug("Unable to determine if autoupdate is enabled", ex); LOGGER.debug("Unable to determine if autoupdate is enabled", ex);
} finally {
CveDB.close();
} }
} }

View File

@@ -104,7 +104,6 @@ public class NvdCveUpdater implements CachedWebDataSource {
LOGGER.trace("invalid setting UPDATE_NVDCVE_ENABLED", ex); LOGGER.trace("invalid setting UPDATE_NVDCVE_ENABLED", ex);
} }
try {
boolean autoUpdate = true; boolean autoUpdate = true;
try { try {
autoUpdate = Settings.getBoolean(Settings.KEYS.AUTO_UPDATE); autoUpdate = Settings.getBoolean(Settings.KEYS.AUTO_UPDATE);
@@ -115,6 +114,7 @@ public class NvdCveUpdater implements CachedWebDataSource {
return; return;
} }
initializeExecutorServices(); initializeExecutorServices();
try {
cveDb = CveDB.getInstance(); cveDb = CveDB.getInstance();
dbProperties = cveDb.getDatabaseProperties(); dbProperties = cveDb.getDatabaseProperties();
@@ -139,7 +139,7 @@ public class NvdCveUpdater implements CachedWebDataSource {
throw new UpdateException("Database Exception, unable to update the data to use the most current data.", ex); throw new UpdateException("Database Exception, unable to update the data to use the most current data.", ex);
} finally { } finally {
shutdownExecutorServices(); shutdownExecutorServices();
CveDB.close(); cveDb.close();
} }
} }
@@ -202,13 +202,10 @@ public class NvdCveUpdater implements CachedWebDataSource {
* @return true if the database contains data * @return true if the database contains data
*/ */
private boolean dataExists() { private boolean dataExists() {
try { try (CveDB cve = CveDB.getInstance()) {
final CveDB cve = CveDB.getInstance();
return cve.dataExists(); return cve.dataExists();
} catch (DatabaseException ex) { } catch (DatabaseException ex) {
return false; return false;
} finally {
CveDB.close();
} }
} }

View File

@@ -51,7 +51,6 @@ public abstract class BaseDBTestCase extends BaseTest {
@Before @Before
public void setUpDb() throws Exception { public void setUpDb() throws Exception {
ensureDBExists(); ensureDBExists();
CveDB.getInstance().openDatabase();
} }
public static void ensureDBExists() throws Exception { public static void ensureDBExists() throws Exception {

View File

@@ -71,10 +71,11 @@ public class EngineIntegrationTest extends BaseDBTestCase {
throw ex; throw ex;
} }
} }
CveDB cveDB = CveDB.getInstance(); DatabaseProperties prop = null;
DatabaseProperties dbProp = cveDB.getDatabaseProperties(); try (CveDB cve = CveDB.getInstance()) {
CveDB.close(); prop = cve.getDatabaseProperties();
ReportGenerator rg = new ReportGenerator("DependencyCheck", instance.getDependencies(), instance.getAnalyzers(), dbProp); }
ReportGenerator rg = new ReportGenerator("DependencyCheck", instance.getDependencies(), instance.getAnalyzers(), prop);
rg.generateReports("./target/", "ALL"); rg.generateReports("./target/", "ALL");
instance.cleanup(); instance.cleanup();
} }

View File

@@ -28,6 +28,7 @@ import java.util.List;
import java.util.Set; import java.util.Set;
import org.junit.After; import org.junit.After;
import static org.junit.Assert.assertNotNull;
import org.junit.Assume; import org.junit.Assume;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
@@ -82,9 +83,11 @@ public class RubyBundleAuditAnalyzerTest extends BaseDBTestCase {
*/ */
@After @After
public void tearDown() throws Exception { public void tearDown() throws Exception {
if (analyzer != null) {
analyzer.close(); analyzer.close();
analyzer = null; analyzer = null;
} }
}
/** /**
* Test Ruby Gemspec name. * Test Ruby Gemspec name.
@@ -166,7 +169,7 @@ public class RubyBundleAuditAnalyzerTest extends BaseDBTestCase {
analyzer.initialize(); analyzer.initialize();
} catch (Exception e) { } catch (Exception e) {
//expected, so ignore. //expected, so ignore.
LOGGER.error("Exception", e); assertNotNull(e);
} finally { } finally {
assertThat(analyzer.isEnabled(), is(false)); assertThat(analyzer.isEnabled(), is(false));
LOGGER.info("phantom-bundle-audit is not available. Ruby Bundle Audit Analyzer is disabled as expected."); LOGGER.info("phantom-bundle-audit is not available. Ruby Bundle Audit Analyzer is disabled as expected.");
@@ -191,6 +194,7 @@ public class RubyBundleAuditAnalyzerTest extends BaseDBTestCase {
fail(ex.getMessage()); fail(ex.getMessage());
} catch (ExceptionCollection ex) { } catch (ExceptionCollection ex) {
Assume.assumeNoException("Exception setting up RubyBundleAuditAnalyzer; bundle audit may not be installed, or property \"analyzer.bundle.audit.path\" may not be set.", ex); Assume.assumeNoException("Exception setting up RubyBundleAuditAnalyzer; bundle audit may not be installed, or property \"analyzer.bundle.audit.path\" may not be set.", ex);
return;
} }
List<Dependency> dependencies = engine.getDependencies(); List<Dependency> dependencies = engine.getDependencies();
LOGGER.info(dependencies.size() + " dependencies found."); LOGGER.info(dependencies.size() + " dependencies found.");

View File

@@ -29,6 +29,7 @@ import java.util.Map.Entry;
import java.util.Set; import java.util.Set;
import org.junit.Test; import org.junit.Test;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull; import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
@@ -52,7 +53,8 @@ public class CveDBIntegrationTest extends BaseDBTestCase {
} catch (DatabaseException | SQLException ex) { } catch (DatabaseException | SQLException ex) {
fail(ex.getMessage()); fail(ex.getMessage());
} finally { } finally {
CveDB.close(); instance.close();
assertFalse(instance.isOpen());
} }
} }
@@ -66,7 +68,7 @@ public class CveDBIntegrationTest extends BaseDBTestCase {
String product = "struts"; String product = "struts";
Set<VulnerableSoftware> result = instance.getCPEs(vendor, product); Set<VulnerableSoftware> result = instance.getCPEs(vendor, product);
assertTrue(result.size() > 5); assertTrue(result.size() > 5);
CveDB.close(); instance.close();
} }
/** /**
@@ -77,7 +79,7 @@ public class CveDBIntegrationTest extends BaseDBTestCase {
CveDB instance = CveDB.getInstance(); CveDB instance = CveDB.getInstance();
Vulnerability result = instance.getVulnerability("CVE-2014-0094"); Vulnerability result = instance.getVulnerability("CVE-2014-0094");
assertEquals("The ParametersInterceptor in Apache Struts before 2.3.16.1 allows remote attackers to \"manipulate\" the ClassLoader via the class parameter, which is passed to the getClass method.", result.getDescription()); assertEquals("The ParametersInterceptor in Apache Struts before 2.3.16.1 allows remote attackers to \"manipulate\" the ClassLoader via the class parameter, which is passed to the getClass method.", result.getDescription());
CveDB.close(); instance.close();
} }
/** /**
@@ -114,7 +116,7 @@ public class CveDBIntegrationTest extends BaseDBTestCase {
} }
} }
assertTrue("Expected " + expected + ", but was not identified", found); assertTrue("Expected " + expected + ", but was not identified", found);
CveDB.close(); instance.close();
} }
/** /**
@@ -170,6 +172,6 @@ public class CveDBIntegrationTest extends BaseDBTestCase {
identifiedVersion = new DependencyVersion("1.6.3"); identifiedVersion = new DependencyVersion("1.6.3");
results = instance.getMatchingSoftware(versions, "springsource", "spring_framework", identifiedVersion); results = instance.getMatchingSoftware(versions, "springsource", "spring_framework", identifiedVersion);
assertNotNull(results); assertNotNull(results);
CveDB.close(); instance.close();
} }
} }

View File

@@ -19,6 +19,7 @@ package org.owasp.dependencycheck.data.nvdcve;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
@@ -39,13 +40,15 @@ public class CveDBMySQLTest extends BaseTest {
*/ */
@Test @Test
public void testOpen() { public void testOpen() {
CveDB instance = null;
try { try {
CveDB instance = CveDB.getInstance(); instance = CveDB.getInstance();
} catch (DatabaseException ex) { } catch (DatabaseException ex) {
System.out.println("Unable to connect to the My SQL database; verify that the db server is running and that the schema has been generated"); System.out.println("Unable to connect to the My SQL database; verify that the db server is running and that the schema has been generated");
fail(ex.getMessage()); fail(ex.getMessage());
} finally { } finally {
CveDB.close(); instance.close();
assertFalse(instance.isOpen());
} }
} }
@@ -64,7 +67,7 @@ public class CveDBMySQLTest extends BaseTest {
System.out.println("Unable to access the My SQL database; verify that the db server is running and that the schema has been generated"); System.out.println("Unable to access the My SQL database; verify that the db server is running and that the schema has been generated");
throw ex; throw ex;
} finally { } finally {
CveDB.close(); instance.close();
} }
} }
@@ -82,7 +85,7 @@ public class CveDBMySQLTest extends BaseTest {
System.out.println("Unable to access the My SQL database; verify that the db server is running and that the schema has been generated"); System.out.println("Unable to access the My SQL database; verify that the db server is running and that the schema has been generated");
throw ex; throw ex;
} finally { } finally {
CveDB.close(); instance.close();
} }
} }
} }

View File

@@ -41,7 +41,7 @@ public class DatabasePropertiesIntegrationTest extends BaseDBTestCase {
assertNotNull(instance); assertNotNull(instance);
//no exception means the call worked... whether or not it is empty depends on if the db is new //no exception means the call worked... whether or not it is empty depends on if the db is new
//assertEquals(expResult, result); //assertEquals(expResult, result);
CveDB.close(); cveDB.close();
} }
/** /**
@@ -60,7 +60,7 @@ public class DatabasePropertiesIntegrationTest extends BaseDBTestCase {
instance = cveDB.reloadProperties(); instance = cveDB.reloadProperties();
long results = Long.parseLong(instance.getProperty("NVD CVE " + key)); long results = Long.parseLong(instance.getProperty("NVD CVE " + key));
assertEquals(expected, results); assertEquals(expected, results);
CveDB.close(); cveDB.close();
} }
/** /**
@@ -75,7 +75,7 @@ public class DatabasePropertiesIntegrationTest extends BaseDBTestCase {
String expResult = "default"; String expResult = "default";
String result = instance.getProperty(key, defaultValue); String result = instance.getProperty(key, defaultValue);
assertEquals(expResult, result); assertEquals(expResult, result);
CveDB.close(); cveDB.close();
} }
/** /**
@@ -90,7 +90,7 @@ public class DatabasePropertiesIntegrationTest extends BaseDBTestCase {
double version = Double.parseDouble(result); double version = Double.parseDouble(result);
assertTrue(version >= 2.8); assertTrue(version >= 2.8);
assertTrue(version <= 10); assertTrue(version <= 10);
CveDB.close(); cveDB.close();
} }
/** /**
@@ -102,6 +102,6 @@ public class DatabasePropertiesIntegrationTest extends BaseDBTestCase {
DatabaseProperties instance = cveDB.getDatabaseProperties(); DatabaseProperties instance = cveDB.getDatabaseProperties();
Properties result = instance.getProperties(); Properties result = instance.getProperties();
assertTrue(result.size() > 0); assertTrue(result.size() > 0);
CveDB.close(); cveDB.close();
} }
} }

View File

@@ -149,7 +149,7 @@ public class ReportGeneratorIntegrationTest extends BaseDBTestCase {
ReportGenerator generator = new ReportGenerator("Test Report", engine.getDependencies(), engine.getAnalyzers(), dbProp); ReportGenerator generator = new ReportGenerator("Test Report", engine.getDependencies(), engine.getAnalyzers(), dbProp);
generator.generateReport(templateName, writeTo); generator.generateReport(templateName, writeTo);
CveDB.close(); cveDB.close();
engine.cleanup(); engine.cleanup();

View File

@@ -1007,8 +1007,7 @@ public abstract class BaseDependencyCheckMojo extends AbstractMojo implements Ma
*/ */
protected void writeReports(Engine engine, MavenProject p, File outputDir) throws ReportException { protected void writeReports(Engine engine, MavenProject p, File outputDir) throws ReportException {
DatabaseProperties prop = null; DatabaseProperties prop = null;
try { try (CveDB cve = CveDB.getInstance()) {
final CveDB cve = CveDB.getInstance();
prop = cve.getDatabaseProperties(); prop = cve.getDatabaseProperties();
} catch (DatabaseException ex) { } catch (DatabaseException ex) {
//TODO shouldn't this throw an exception? //TODO shouldn't this throw an exception?
@@ -1017,7 +1016,6 @@ public abstract class BaseDependencyCheckMojo extends AbstractMojo implements Ma
} }
} }
final ReportGenerator r = new ReportGenerator(p.getName(), engine.getDependencies(), engine.getAnalyzers(), prop); final ReportGenerator r = new ReportGenerator(p.getName(), engine.getDependencies(), engine.getAnalyzers(), prop);
CveDB.close();
try { try {
r.generateReports(outputDir.getAbsolutePath(), format); r.generateReports(outputDir.getAbsolutePath(), format);
} catch (ReportException ex) { } catch (ReportException ex) {