checkstyle corrections

This commit is contained in:
Jeremy Long
2017-03-12 18:03:27 -04:00
parent 675349c06f
commit 371dba948d
24 changed files with 263 additions and 182 deletions

View File

@@ -257,7 +257,7 @@ public class Check extends Update {
* *
* @param r the reference to a path, fileset, dirset or filelist. * @param r the reference to a path, fileset, dirset or filelist.
*/ */
public void setRefId(Reference r) { public synchronized void setRefId(Reference r) {
if (path != null) { if (path != null) {
throw new BuildException("Nested elements are not allowed when using the refId attribute."); throw new BuildException("Nested elements are not allowed when using the refId attribute.");
} }
@@ -923,7 +923,7 @@ public class Check extends Update {
log(ex.getMessage(), Project.MSG_ERR); log(ex.getMessage(), Project.MSG_ERR);
} }
} else { } else {
for (Resource resource : path) { for (Resource resource : getPath()) {
final FileProvider provider = resource.as(FileProvider.class); final FileProvider provider = resource.as(FileProvider.class);
if (provider != null) { if (provider != null) {
final File file = provider.getFile(); final File file = provider.getFile();
@@ -987,7 +987,7 @@ public class Check extends Update {
* @throws BuildException if the task was not configured correctly. * @throws BuildException if the task was not configured correctly.
*/ */
private void validateConfiguration() throws BuildException { private void validateConfiguration() throws BuildException {
if (path == null) { if (getPath() == null) {
throw new BuildException("No project dependencies have been defined to analyze."); throw new BuildException("No project dependencies have been defined to analyze.");
} }
if (failBuildOnCVSS < 0 || failBuildOnCVSS > 11) { if (failBuildOnCVSS < 0 || failBuildOnCVSS > 11) {

View File

@@ -144,7 +144,6 @@ public class Purge extends Task {
*/ */
protected void populateSettings() throws BuildException { protected void populateSettings() throws BuildException {
Settings.initialize(); Settings.initialize();
try (InputStream taskProperties = this.getClass().getClassLoader().getResourceAsStream(PROPERTIES_FILE)) { try (InputStream taskProperties = this.getClass().getClassLoader().getResourceAsStream(PROPERTIES_FILE)) {
Settings.mergeProperties(taskProperties); Settings.mergeProperties(taskProperties);
} catch (IOException ex) { } catch (IOException ex) {

View File

@@ -282,8 +282,8 @@ public class App {
exCol = ex; exCol = ex;
} }
final List<Dependency> dependencies = engine.getDependencies(); final List<Dependency> dependencies = engine.getDependencies();
CveDB cve = CveDB.getInstance(); final CveDB cve = CveDB.getInstance();
DatabaseProperties prop = cve.getDatabaseProperties(); final DatabaseProperties 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);

View File

@@ -144,7 +144,8 @@ public class AssemblyAnalyzer extends AbstractFileTypeAnalyzer {
dependency.getActualFilePath()); dependency.getActualFilePath());
return; return;
} else if (rc != 0) { } else if (rc != 0) {
LOGGER.debug("Return code {} from GrokAssembly; dependency-check is unable to analyze the library: {}", rc, dependency.getActualFilePath()); LOGGER.debug("Return code {} from GrokAssembly; dependency-check is unable to analyze the library: {}",
rc, dependency.getActualFilePath());
return; return;
} }

View File

@@ -33,7 +33,6 @@ import org.slf4j.LoggerFactory;
import java.io.FileFilter; import java.io.FileFilter;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.security.MessageDigest; import java.security.MessageDigest;

View File

@@ -52,6 +52,7 @@ import org.xml.sax.SAXException;
* @author Jeremy Long * @author Jeremy Long
*/ */
public class HintAnalyzer extends AbstractAnalyzer { public class HintAnalyzer extends AbstractAnalyzer {
/** /**
* The Logger for use throughout the class * The Logger for use throughout the class
*/ */

View File

@@ -25,8 +25,16 @@ import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.io.Reader; import java.io.Reader;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.util.*; import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
import java.util.jar.Attributes; import java.util.jar.Attributes;
import java.util.jar.JarEntry; import java.util.jar.JarEntry;
@@ -248,7 +256,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 {
try (JarFile jar = new JarFile(dependency.getActualFilePath())) { try (JarFile jar = new JarFile(dependency.getActualFilePath())) {
List<String> pomEntries = retrievePomListing(jar); final List<String> pomEntries = retrievePomListing(jar);
if (pomEntries != null && pomEntries.size() <= 1) { if (pomEntries != null && pomEntries.size() <= 1) {
String path; String path;
File pomFile; File pomFile;

View File

@@ -144,7 +144,7 @@ public class NexusAnalyzer extends AbstractFileTypeAnalyzer {
LOGGER.debug("Initializing Nexus Analyzer"); LOGGER.debug("Initializing Nexus Analyzer");
LOGGER.debug("Nexus Analyzer enabled: {}", isEnabled()); LOGGER.debug("Nexus Analyzer enabled: {}", isEnabled());
if (isEnabled()) { if (isEnabled()) {
boolean useProxy = useProxy(); final boolean useProxy = useProxy();
final String searchUrl = Settings.getString(Settings.KEYS.ANALYZER_NEXUS_URL); final String searchUrl = Settings.getString(Settings.KEYS.ANALYZER_NEXUS_URL);
LOGGER.debug("Nexus Analyzer URL: {}", searchUrl); LOGGER.debug("Nexus Analyzer URL: {}", searchUrl);
try { try {

View File

@@ -33,7 +33,6 @@ import org.slf4j.LoggerFactory;
import java.io.FileFilter; import java.io.FileFilter;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.IOException;
import org.owasp.dependencycheck.exception.InitializationException; import org.owasp.dependencycheck.exception.InitializationException;
/** /**

View File

@@ -180,9 +180,7 @@ public class RubyBundleAuditAnalyzer extends AbstractFileTypeAnalyzer {
final String msg = String.format("Unexpected exit code from bundle-audit process. Disabling %s: %s", ANALYZER_NAME, exitValue); final String msg = String.format("Unexpected exit code from bundle-audit process. Disabling %s: %s", ANALYZER_NAME, exitValue);
throw new InitializationException(msg); throw new InitializationException(msg);
} else { } else {
BufferedReader reader = null; try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getErrorStream(), "UTF-8"))) {
try {
reader = new BufferedReader(new InputStreamReader(process.getErrorStream(), "UTF-8"));
if (!reader.ready()) { if (!reader.ready()) {
LOGGER.warn("Bundle-audit error stream unexpectedly not ready. Disabling " + ANALYZER_NAME); LOGGER.warn("Bundle-audit error stream unexpectedly not ready. Disabling " + ANALYZER_NAME);
setEnabled(false); setEnabled(false);
@@ -201,14 +199,6 @@ public class RubyBundleAuditAnalyzer extends AbstractFileTypeAnalyzer {
} catch (IOException ex) { } catch (IOException ex) {
setEnabled(false); setEnabled(false);
throw new InitializationException("Unable to read bundle-audit output.", ex); throw new InitializationException("Unable to read bundle-audit output.", ex);
} finally {
if (null != reader) {
try {
reader.close();
} catch (IOException ex) {
LOGGER.debug("Error closing reader", ex);
}
}
} }
} }
@@ -296,36 +286,20 @@ public class RubyBundleAuditAnalyzer extends AbstractFileTypeAnalyzer {
final String msg = String.format("Unexpected exit code from bundle-audit process; exit code: %s", exitValue); final String msg = String.format("Unexpected exit code from bundle-audit process; exit code: %s", exitValue);
throw new AnalysisException(msg); throw new AnalysisException(msg);
} }
BufferedReader rdr = null;
BufferedReader errReader = null;
try { try {
errReader = new BufferedReader(new InputStreamReader(process.getErrorStream(), "UTF-8")); try (BufferedReader errReader = new BufferedReader(new InputStreamReader(process.getErrorStream(), "UTF-8"))) {
while (errReader.ready()) { while (errReader.ready()) {
final String error = errReader.readLine(); final String error = errReader.readLine();
LOGGER.warn(error); LOGGER.warn(error);
} }
rdr = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); }
try (BufferedReader rdr = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8"))) {
processBundlerAuditOutput(dependency, engine, rdr); processBundlerAuditOutput(dependency, engine, rdr);
}
} catch (IOException ioe) { } catch (IOException ioe) {
LOGGER.warn("bundle-audit failure", ioe); LOGGER.warn("bundle-audit failure", ioe);
} finally {
if (errReader != null) {
try {
errReader.close();
} catch (IOException ioe) {
LOGGER.warn("bundle-audit close failure", ioe);
} }
} }
if (null != rdr) {
try {
rdr.close();
} catch (IOException ioe) {
LOGGER.warn("bundle-audit close failure", ioe);
}
}
}
}
/** /**
* Processes the bundler audit output. * Processes the bundler audit output.

View File

@@ -63,7 +63,7 @@ public final class CveDB {
/** /**
* Singleton instance of the CveDB. * Singleton instance of the CveDB.
*/ */
private static CveDB INSTANCE = null; private static CveDB instance = null;
/** /**
* The logger. * The logger.
*/ */
@@ -91,27 +91,93 @@ public final class CveDB {
* statement bundles "dbStatements*.properties". * statement bundles "dbStatements*.properties".
*/ */
enum PreparedStatementCveDb { enum PreparedStatementCveDb {
/**
* Key for SQL Statement.
*/
CLEANUP_ORPHANS, CLEANUP_ORPHANS,
/**
* Key for SQL Statement.
*/
COUNT_CPE, COUNT_CPE,
/**
* Key for SQL Statement.
*/
DELETE_REFERENCE, DELETE_REFERENCE,
/**
* Key for SQL Statement.
*/
DELETE_SOFTWARE, DELETE_SOFTWARE,
/**
* Key for SQL Statement.
*/
DELETE_VULNERABILITY, DELETE_VULNERABILITY,
/**
* Key for SQL Statement.
*/
INSERT_CPE, INSERT_CPE,
/**
* Key for SQL Statement.
*/
INSERT_PROPERTY, INSERT_PROPERTY,
/**
* Key for SQL Statement.
*/
INSERT_REFERENCE, INSERT_REFERENCE,
/**
* Key for SQL Statement.
*/
INSERT_SOFTWARE, INSERT_SOFTWARE,
/**
* Key for SQL Statement.
*/
INSERT_VULNERABILITY, INSERT_VULNERABILITY,
/**
* Key for SQL Statement.
*/
MERGE_PROPERTY, MERGE_PROPERTY,
/**
* Key for SQL Statement.
*/
SELECT_CPE_ENTRIES, SELECT_CPE_ENTRIES,
/**
* Key for SQL Statement.
*/
SELECT_CPE_ID, SELECT_CPE_ID,
/**
* Key for SQL Statement.
*/
SELECT_CVE_FROM_SOFTWARE, SELECT_CVE_FROM_SOFTWARE,
/**
* Key for SQL Statement.
*/
SELECT_PROPERTIES, SELECT_PROPERTIES,
/**
* Key for SQL Statement.
*/
SELECT_REFERENCES, SELECT_REFERENCES,
/**
* Key for SQL Statement.
*/
SELECT_SOFTWARE, SELECT_SOFTWARE,
/**
* Key for SQL Statement.
*/
SELECT_VENDOR_PRODUCT_LIST, SELECT_VENDOR_PRODUCT_LIST,
/**
* Key for SQL Statement.
*/
SELECT_VULNERABILITY, SELECT_VULNERABILITY,
/**
* Key for SQL Statement.
*/
SELECT_VULNERABILITY_ID, SELECT_VULNERABILITY_ID,
/**
* Key for SQL Statement.
*/
UPDATE_PROPERTY, UPDATE_PROPERTY,
/**
* Key for SQL Statement.
*/
UPDATE_VULNERABILITY UPDATE_VULNERABILITY
} }
@@ -121,11 +187,11 @@ public final class CveDB {
* @return the CveDB singleton * @return the CveDB singleton
* @throws DatabaseException thrown if there is a database error * @throws DatabaseException thrown if there is a database error
*/ */
public synchronized static CveDB getInstance() throws DatabaseException { public static synchronized CveDB getInstance() throws DatabaseException {
if (INSTANCE == null) { if (instance == null) {
INSTANCE = new CveDB(); instance = new CveDB();
} }
return INSTANCE; return instance;
} }
/** /**
@@ -150,9 +216,9 @@ public final class CveDB {
* *
* @return the product name of the database if successful, {@code null} else * @return the product name of the database if successful, {@code null} else
*/ */
private String determineDatabaseProductName() { private synchronized String determineDatabaseProductName() {
try { try {
final String databaseProductName = getConnection().getMetaData().getDatabaseProductName(); final String databaseProductName = connection.getMetaData().getDatabaseProductName();
LOGGER.debug("Database product: {}", databaseProductName); LOGGER.debug("Database product: {}", databaseProductName);
return databaseProductName; return databaseProductName;
} catch (SQLException se) { } catch (SQLException se) {
@@ -161,15 +227,6 @@ public final class CveDB {
} }
} }
/**
* Returns the database connection.
*
* @return the database connection
*/
private Connection getConnection() {
return connection;
}
/** /**
* Opens the database connection. If the database does not exist, it will * Opens the database connection. If the database does not exist, it will
* create a new one. * create a new one.
@@ -191,7 +248,7 @@ public final class CveDB {
if (isOpen()) { if (isOpen()) {
closeStatements(); closeStatements();
try { try {
getConnection().close(); connection.close();
} catch (SQLException ex) { } catch (SQLException ex) {
LOGGER.error("There was an error attempting to close the CveDB, see the log for more details."); LOGGER.error("There was an error attempting to close the CveDB, see the log for more details.");
LOGGER.debug("", ex); LOGGER.debug("", ex);
@@ -200,7 +257,7 @@ public final class CveDB {
LOGGER.debug("", ex); LOGGER.debug("", ex);
} }
connection = null; connection = null;
INSTANCE = null; instance = null;
} }
} }
@@ -210,7 +267,7 @@ public final class CveDB {
* @return whether the database connection is open or closed * @return whether the database connection is open or closed
*/ */
private boolean isOpen() { private boolean isOpen() {
return getConnection() != null; return connection != null;
} }
/** /**
@@ -229,9 +286,9 @@ public final class CveDB {
final PreparedStatement preparedStatement; final PreparedStatement preparedStatement;
try { try {
if (key == INSERT_VULNERABILITY || key == INSERT_CPE) { if (key == INSERT_VULNERABILITY || key == INSERT_CPE) {
preparedStatement = getConnection().prepareStatement(statementString, new String[]{"id"}); preparedStatement = connection.prepareStatement(statementString, new String[]{"id"});
} else { } else {
preparedStatement = getConnection().prepareStatement(statementString); preparedStatement = connection.prepareStatement(statementString);
} }
} catch (SQLException exception) { } catch (SQLException exception) {
throw new DatabaseException(exception); throw new DatabaseException(exception);
@@ -272,7 +329,7 @@ public final class CveDB {
public synchronized void commit() throws SQLException { public synchronized void commit() throws SQLException {
//temporary remove this as autocommit is on. //temporary remove this as autocommit is on.
//if (isOpen()) { //if (isOpen()) {
// getConnection().commit(); // connection.commit();
//} //}
} }
@@ -625,6 +682,7 @@ public final class CveDB {
insertReference.setString(4, r.getSource()); insertReference.setString(4, r.getSource());
insertReference.execute(); insertReference.execute();
} }
final PreparedStatement insertSoftware = getPreparedStatement(INSERT_SOFTWARE); final PreparedStatement insertSoftware = getPreparedStatement(INSERT_SOFTWARE);
for (VulnerableSoftware s : vuln.getVulnerableSoftware()) { for (VulnerableSoftware s : vuln.getVulnerableSoftware()) {
int cpeProductId = 0; int cpeProductId = 0;
@@ -671,6 +729,7 @@ public final class CveDB {
throw ex; throw ex;
} }
} }
} }
} catch (SQLException ex) { } catch (SQLException ex) {
final String msg = String.format("Error updating '%s'", vuln.getName()); final String msg = String.format("Error updating '%s'", vuln.getName());
@@ -856,10 +915,11 @@ public final class CveDB {
public synchronized void deleteUnusedCpe() { public synchronized void deleteUnusedCpe() {
PreparedStatement ps = null; PreparedStatement ps = null;
try { try {
ps = getConnection().prepareStatement(statementBundle.getString("DELETE_UNUSED_DICT_CPE")); ps = connection.prepareStatement(statementBundle.getString("DELETE_UNUSED_DICT_CPE"));
ps.executeUpdate(); ps.executeUpdate();
} catch (SQLException ex) { } catch (SQLException ex) {
LOGGER.error("Unable to delete CPE dictionary entries", ex); LOGGER.error("Unable to delete CPE dictionary entries", ex);
} finally {
DBUtils.closeStatement(ps); DBUtils.closeStatement(ps);
} }
} }
@@ -877,13 +937,14 @@ public final class CveDB {
public synchronized void addCpe(String cpe, String vendor, String product) { public synchronized void addCpe(String cpe, String vendor, String product) {
PreparedStatement ps = null; PreparedStatement ps = null;
try { try {
ps = getConnection().prepareStatement(statementBundle.getString("ADD_DICT_CPE")); ps = connection.prepareStatement(statementBundle.getString("ADD_DICT_CPE"));
ps.setString(1, cpe); ps.setString(1, cpe);
ps.setString(2, vendor); ps.setString(2, vendor);
ps.setString(3, product); ps.setString(3, product);
ps.executeUpdate(); ps.executeUpdate();
} catch (SQLException ex) { } catch (SQLException ex) {
LOGGER.error("Unable to add CPE dictionary entry", ex); LOGGER.error("Unable to add CPE dictionary entry", ex);
} finally {
DBUtils.closeStatement(ps); DBUtils.closeStatement(ps);
} }
} }

View File

@@ -78,7 +78,13 @@ public class NvdCveUpdater implements CachedWebDataSource {
*/ */
private ExecutorService downloadExecutorService = null; private ExecutorService downloadExecutorService = null;
/**
* Reference to the DAO.
*/
private CveDB cveDb = null; private CveDB cveDb = null;
/**
* The properties obtained from the database.
*/
private DatabaseProperties dbProperties = null; private DatabaseProperties dbProperties = null;
/** /**
@@ -448,8 +454,16 @@ public class NvdCveUpdater implements CachedWebDataSource {
*/ */
private static class TimestampRetriever implements Callable<Long> { private static class TimestampRetriever implements Callable<Long> {
/**
* The URL to obtain the timestamp from.
*/
private final String url; private final String url;
/**
* Instantiates a new timestamp retriever object.
*
* @param url the URL to hit
*/
TimestampRetriever(String url) { TimestampRetriever(String url) {
this.url = url; this.url = url;
} }

View File

@@ -19,7 +19,6 @@ package org.owasp.dependencycheck.data.update.nvd;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.net.URL; import java.net.URL;

View File

@@ -51,7 +51,8 @@ public class NvdCve20Handler extends DefaultHandler {
*/ */
private static final String CURRENT_SCHEMA_VERSION = "2.0"; private static final String CURRENT_SCHEMA_VERSION = "2.0";
/** /**
* a possible attribute value of the {@link AttributeValues#XML_LANG} attribute * a possible attribute value of the {@link AttributeValues#XML_LANG}
* attribute
*/ */
private static final String EN = "en"; private static final String EN = "en";
/** /**
@@ -97,7 +98,8 @@ public class NvdCve20Handler extends DefaultHandler {
private CveDB cveDB; private CveDB cveDB;
/** /**
* A list of CVE entries and associated VulnerableSoftware entries that contain previous entries. * A list of CVE entries and associated VulnerableSoftware entries that
* contain previous entries.
*/ */
private Map<String, List<VulnerableSoftware>> prevVersionVulnMap; private Map<String, List<VulnerableSoftware>> prevVersionVulnMap;
@@ -249,10 +251,12 @@ public class NvdCve20Handler extends DefaultHandler {
public void setCveDB(CveDB db) { public void setCveDB(CveDB db) {
cveDB = db; cveDB = db;
} }
/** /**
* Sets the prevVersionVulnMap. * Sets the prevVersionVulnMap.
* *
* @param map the map of vulnerable software with previous versions being vulnerable * @param map the map of vulnerable software with previous versions being
* vulnerable
*/ */
public void setPrevVersionVulnMap(Map<String, List<VulnerableSoftware>> map) { public void setPrevVersionVulnMap(Map<String, List<VulnerableSoftware>> map) {
prevVersionVulnMap = map; prevVersionVulnMap = map;
@@ -262,7 +266,8 @@ public class NvdCve20Handler extends DefaultHandler {
* Saves a vulnerability to the CVE Database. * Saves a vulnerability to the CVE Database.
* *
* @param vuln the vulnerability to store in the database * @param vuln the vulnerability to store in the database
* @throws DatabaseException thrown if there is an error writing to the database * @throws DatabaseException thrown if there is an error writing to the
* database
* @throws CorruptIndexException is thrown if the CPE Index is corrupt * @throws CorruptIndexException is thrown if the CPE Index is corrupt
* @throws IOException thrown if there is an IOException with the CPE Index * @throws IOException thrown if there is an IOException with the CPE Index
*/ */
@@ -281,7 +286,8 @@ public class NvdCve20Handler extends DefaultHandler {
// <editor-fold defaultstate="collapsed" desc="The Element Class that maintains state information about the current node"> // <editor-fold defaultstate="collapsed" desc="The Element Class that maintains state information about the current node">
/** /**
* A simple class to maintain information about the current element while parsing the NVD CVE XML. * A simple class to maintain information about the current element while
* parsing the NVD CVE XML.
*/ */
protected static class Element { protected static class Element {
@@ -506,7 +512,8 @@ public class NvdCve20Handler extends DefaultHandler {
// </editor-fold> // </editor-fold>
/** /**
* A simple class to maintain information about the attribute values encountered while parsing the NVD CVE XML. * A simple class to maintain information about the attribute values
* encountered while parsing the NVD CVE XML.
*/ */
protected static class AttributeValues { protected static class AttributeValues {

View File

@@ -153,7 +153,7 @@ public class Vulnerability implements Serializable, Comparable<Vulnerability> {
* @return the list of references * @return the list of references
*/ */
public List<Reference> getReferences(boolean sorted) { public List<Reference> getReferences(boolean sorted) {
List<Reference> sortedRefs = new ArrayList<>(this.references); final List<Reference> sortedRefs = new ArrayList<>(this.references);
if (sorted) { if (sorted) {
Collections.sort(sortedRefs); Collections.sort(sortedRefs);
} }
@@ -210,7 +210,7 @@ public class Vulnerability implements Serializable, Comparable<Vulnerability> {
* @return the list of vulnerable software * @return the list of vulnerable software
*/ */
public List<VulnerableSoftware> getVulnerableSoftware(boolean sorted) { public List<VulnerableSoftware> getVulnerableSoftware(boolean sorted) {
List<VulnerableSoftware> sortedVulnerableSoftware = new ArrayList<>(this.vulnerableSoftware); final List<VulnerableSoftware> sortedVulnerableSoftware = new ArrayList<>(this.vulnerableSoftware);
if (sorted) { if (sorted) {
Collections.sort(sortedVulnerableSoftware); Collections.sort(sortedVulnerableSoftware);
} }

View File

@@ -47,7 +47,8 @@ public final class DBUtils {
* *
* @param statement a prepared statement that just executed an insert * @param statement a prepared statement that just executed an insert
* @return a primary key * @return a primary key
* @throws DatabaseException thrown if there is an exception obtaining the key * @throws DatabaseException thrown if there is an exception obtaining the
* key
*/ */
public static int getGeneratedKey(PreparedStatement statement) throws DatabaseException { public static int getGeneratedKey(PreparedStatement statement) throws DatabaseException {
ResultSet rs = null; ResultSet rs = null;
@@ -72,27 +73,29 @@ public final class DBUtils {
* @param statement a Statement object * @param statement a Statement object
*/ */
public static void closeStatement(Statement statement) { public static void closeStatement(Statement statement) {
if (statement != null) {
try { try {
if (statement != null && !statement.isClosed()) {
statement.close(); statement.close();
}
} catch (SQLException ex) { } catch (SQLException ex) {
LOGGER.trace(statement.toString(), ex); LOGGER.trace(statement.toString(), ex);
} }
} }
}
/** /**
* Closes the result set capturing and ignoring any SQLExceptions that occur. * Closes the result set capturing and ignoring any SQLExceptions that
* occur.
* *
* @param rs a ResultSet to close * @param rs a ResultSet to close
*/ */
public static void closeResultSet(ResultSet rs) { public static void closeResultSet(ResultSet rs) {
if (rs != null) {
try { try {
if (rs != null && !rs.isClosed()) {
rs.close(); rs.close();
}
} catch (SQLException ex) { } catch (SQLException ex) {
LOGGER.trace(rs.toString(), ex); LOGGER.trace(rs.toString(), ex);
} }
} }
} }
}

View File

@@ -149,8 +149,17 @@ public class HintHandler extends DefaultHandler {
* Internal type to track the parent node state. * Internal type to track the parent node state.
*/ */
enum ParentType { enum ParentType {
/**
* Marks the add node.
*/
ADD, ADD,
/**
* Marks the given node.
*/
GIVEN, GIVEN,
/**
* Marks the remove node.
*/
REMOVE REMOVE
} }
/** /**

View File

@@ -132,9 +132,11 @@ public class PomHandler extends DefaultHandler {
public void endElement(String uri, String localName, String qName) throws SAXException { public void endElement(String uri, String localName, String qName) throws SAXException {
stack.pop(); stack.pop();
final String parentNode = stack.peek(); final String parentNode = stack.peek();
if (null != parentNode) switch (parentNode) { if (null != parentNode) {
switch (parentNode) {
case PROJECT: case PROJECT:
if (null != qName) switch (qName) { if (null != qName) {
switch (qName) {
case GROUPID: case GROUPID:
model.setGroupId(currentText.toString()); model.setGroupId(currentText.toString());
break; break;
@@ -155,15 +157,19 @@ public class PomHandler extends DefaultHandler {
break; break;
default: default:
break; break;
} break; }
}
break;
case ORGANIZATION: case ORGANIZATION:
if (NAME.equals(qName)) { if (NAME.equals(qName)) {
model.setOrganization(currentText.toString()); model.setOrganization(currentText.toString());
} else if (URL.equals(qName)) { } else if (URL.equals(qName)) {
model.setOrganizationUrl(currentText.toString()); model.setOrganizationUrl(currentText.toString());
} break; }
break;
case PARENT: case PARENT:
if (null != qName) switch (qName) { if (null != qName) {
switch (qName) {
case GROUPID: case GROUPID:
model.setParentGroupId(currentText.toString()); model.setParentGroupId(currentText.toString());
break; break;
@@ -175,7 +181,9 @@ public class PomHandler extends DefaultHandler {
break; break;
default: default:
break; break;
} break; }
}
break;
case LICENSE: case LICENSE:
if (license != null) { if (license != null) {
if (NAME.equals(qName)) { if (NAME.equals(qName)) {
@@ -183,17 +191,20 @@ public class PomHandler extends DefaultHandler {
} else if (URL.equals(qName)) { } else if (URL.equals(qName)) {
license.setUrl(currentText.toString()); license.setUrl(currentText.toString());
} }
} break; }
break;
case LICENSES: case LICENSES:
if (LICENSE.equals(qName)) { if (LICENSE.equals(qName)) {
if (license != null) { if (license != null) {
model.addLicense(license); model.addLicense(license);
} }
} break; }
break;
default: default:
break; break;
} }
} }
}
/** /**
* Collects the body text of the node being processed. * Collects the body text of the node being processed.

View File

@@ -80,10 +80,10 @@ public class PomParser {
final SAXParser saxParser = XmlUtils.buildSecureSaxParser(); final SAXParser saxParser = XmlUtils.buildSecureSaxParser();
final XMLReader xmlReader = saxParser.getXMLReader(); final XMLReader xmlReader = saxParser.getXMLReader();
xmlReader.setContentHandler(handler); xmlReader.setContentHandler(handler);
BOMInputStream bomStream = new BOMInputStream(inputStream); final BOMInputStream bomStream = new BOMInputStream(inputStream);
ByteOrderMark bom = bomStream.getBOM(); final ByteOrderMark bom = bomStream.getBOM();
String defaultEncoding = "UTF-8"; final String defaultEncoding = "UTF-8";
String charsetName = bom == null ? defaultEncoding : bom.getCharsetName(); final String charsetName = bom == null ? defaultEncoding : bom.getCharsetName();
final Reader reader = new InputStreamReader(bomStream, charsetName); final Reader reader = new InputStreamReader(bomStream, charsetName);
final InputSource in = new InputSource(reader); final InputSource in = new InputSource(reader);
xmlReader.parse(in); xmlReader.parse(in);

View File

@@ -17,13 +17,10 @@
*/ */
package org.owasp.dependencycheck.maven; package org.owasp.dependencycheck.maven;
import java.io.BufferedOutputStream;
import java.io.File; import java.io.File;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.Artifact;
@@ -109,8 +106,9 @@ public abstract class BaseDependencyCheckMojo extends AbstractMojo implements Ma
@Parameter(readonly = true, required = true, property = "reactorProjects") @Parameter(readonly = true, required = true, property = "reactorProjects")
private List<MavenProject> reactorProjects; private List<MavenProject> reactorProjects;
/** /**
* The entry point towards a Maven version independent way of resolving artifacts (handles both Maven 3.0 * The entry point towards a Maven version independent way of resolving
* Sonatype and Maven 3.1+ eclipse Aether implementations). * artifacts (handles both Maven 3.0 Sonatype and Maven 3.1+ eclipse Aether
* implementations).
*/ */
@Component @Component
private ArtifactResolver artifactResolver; private ArtifactResolver artifactResolver;
@@ -531,6 +529,7 @@ public abstract class BaseDependencyCheckMojo extends AbstractMojo implements Ma
protected String getConnectionString() { protected String getConnectionString() {
return connectionString; return connectionString;
} }
/** /**
* Returns if the mojo should fail the build if an exception occurs. * Returns if the mojo should fail the build if an exception occurs.
* *
@@ -624,6 +623,7 @@ public abstract class BaseDependencyCheckMojo extends AbstractMojo implements Ma
* @param project the project being scanned * @param project the project being scanned
* @param nodes the list of dependency nodes, generally obtained via the * @param nodes the list of dependency nodes, generally obtained via the
* DependencyGraphBuilder * DependencyGraphBuilder
* @param buildingRequest the Maven project building request
* @return a collection of exceptions that may have occurred while resolving * @return a collection of exceptions that may have occurred while resolving
* and scanning the dependencies * and scanning the dependencies
*/ */
@@ -683,16 +683,13 @@ public abstract class BaseDependencyCheckMojo extends AbstractMojo implements Ma
} }
/** /**
* @return Returns a new ProjectBuildingRequest populated from the current session and the current project remote * @return Returns a new ProjectBuildingRequest populated from the current
* repositories, used to resolve artifacts. * session and the current project remote repositories, used to resolve
* artifacts.
*/ */
public ProjectBuildingRequest newResolveArtifactProjectBuildingRequest() public ProjectBuildingRequest newResolveArtifactProjectBuildingRequest() {
{ final ProjectBuildingRequest buildingRequest = new DefaultProjectBuildingRequest(session.getProjectBuildingRequest());
ProjectBuildingRequest buildingRequest =
new DefaultProjectBuildingRequest( session.getProjectBuildingRequest() );
buildingRequest.setRemoteRepositories(remoteRepositories); buildingRequest.setRemoteRepositories(remoteRepositories);
return buildingRequest; return buildingRequest;
} }
@@ -1060,8 +1057,8 @@ public abstract class BaseDependencyCheckMojo extends AbstractMojo implements Ma
msg = String.format("%n%nOne or more dependencies were identified with vulnerabilities: %n%s%n%n" msg = String.format("%n%nOne or more dependencies were identified with vulnerabilities: %n%s%n%n"
+ "See the dependency-check report for more details.%n%n", ids.toString()); + "See the dependency-check report for more details.%n%n", ids.toString());
} else { } else {
msg = String.format("%n%nOne or more dependencies were identified with vulnerabilities that have a CVSS score greater than '%.1f': %n%s%n%n" msg = String.format("%n%nOne or more dependencies were identified with vulnerabilities that have a CVSS score greater than '%.1f': "
+ "See the dependency-check report for more details.%n%n", failBuildOnCVSS, ids.toString()); + "%n%s%n%nSee the dependency-check report for more details.%n%n", failBuildOnCVSS, ids.toString());
} }
throw new MojoFailureException(msg); throw new MojoFailureException(msg);
@@ -1136,5 +1133,4 @@ public abstract class BaseDependencyCheckMojo extends AbstractMojo implements Ma
} }
//</editor-fold> //</editor-fold>
} }