Merge branch 'master' of github.com:jeremylong/DependencyCheck

Former-commit-id: 0050abb5911eb52058d7e43a65d7f3df5dda6f24
This commit is contained in:
Jeremy Long
2015-06-17 20:16:54 -04:00
74 changed files with 1718 additions and 818 deletions

View File

@@ -0,0 +1,258 @@
/*
* This file is part of dependency-check-ant.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright (c) 2013 Jeremy Long. All Rights Reserved.
*/
package org.owasp.dependencycheck.ant.logging;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.Task;
import org.slf4j.helpers.FormattingTuple;
import org.slf4j.helpers.MarkerIgnoringBase;
import org.slf4j.helpers.MessageFormatter;
/**
* An instance of {@link org.slf4j.Logger} which simply calls the log method
* on the delegate Ant task
*
* @author colezlaw
*/
public class AntLoggerAdapter extends MarkerIgnoringBase {
private Task task;
public AntLoggerAdapter(Task task) {
super();
this.task = task;
}
public void setTask(Task task) {
this.task = task;
}
@Override
public boolean isTraceEnabled() {
// Might be a more efficient way to do this, but Ant doesn't enable or disable
// various levels globally - it just fires things at registered Listeners.
return true;
}
@Override
public void trace(String msg) {
task.log(msg, Project.MSG_VERBOSE);
}
@Override
public void trace(String format, Object arg) {
if (task != null) {
FormattingTuple tp = MessageFormatter.format(format, arg);
task.log(tp.getMessage(), Project.MSG_VERBOSE);
}
}
@Override
public void trace(String format, Object arg1, Object arg2) {
if (task != null) {
FormattingTuple tp = MessageFormatter.format(format, arg1, arg2);
task.log(tp.getMessage(), Project.MSG_VERBOSE);
}
}
@Override
public void trace(String format, Object... arguments) {
if (task != null) {
FormattingTuple tp = MessageFormatter.format(format, arguments);
task.log(tp.getMessage(), Project.MSG_VERBOSE);
}
}
@Override
public void trace(String msg, Throwable t) {
if (task != null) {
task.log(msg, t, Project.MSG_VERBOSE);
}
}
@Override
public boolean isDebugEnabled() {
return true;
}
@Override
public void debug(String msg) {
if (task != null) {
task.log(msg, Project.MSG_DEBUG);
}
}
@Override
public void debug(String format, Object arg) {
if (task != null) {
FormattingTuple tp = MessageFormatter.format(format, arg);
task.log(tp.getMessage(), Project.MSG_DEBUG);
}
}
@Override
public void debug(String format, Object arg1, Object arg2) {
if (task != null) {
FormattingTuple tp = MessageFormatter.format(format, arg1, arg2);
task.log(tp.getMessage(), Project.MSG_DEBUG);
}
}
@Override
public void debug(String format, Object... arguments) {
if (task != null) {
FormattingTuple tp = MessageFormatter.format(format, arguments);
task.log(tp.getMessage(), Project.MSG_DEBUG);
}
}
@Override
public void debug(String msg, Throwable t) {
if (task != null) {
task.log(msg, t, Project.MSG_DEBUG);
}
}
@Override
public boolean isInfoEnabled() {
return true;
}
@Override
public void info(String msg) {
if (task != null) {
task.log(msg, Project.MSG_INFO);
}
}
@Override
public void info(String format, Object arg) {
if (task != null) {
FormattingTuple tp = MessageFormatter.format(format, arg);
task.log(tp.getMessage(), Project.MSG_INFO);
}
}
@Override
public void info(String format, Object arg1, Object arg2) {
if (task != null) {
FormattingTuple tp = MessageFormatter.format(format, arg1, arg2);
task.log(tp.getMessage(), Project.MSG_INFO);
}
}
@Override
public void info(String format, Object... arguments) {
if (task != null) {
FormattingTuple tp = MessageFormatter.format(format, arguments);
task.log(tp.getMessage(), Project.MSG_INFO);
}
}
@Override
public void info(String msg, Throwable t) {
if (task != null) {
task.log(msg, t, Project.MSG_INFO);
}
}
@Override
public boolean isWarnEnabled() {
return true;
}
@Override
public void warn(String msg) {
if (task != null) {
task.log(msg, Project.MSG_WARN);
}
}
@Override
public void warn(String format, Object arg) {
if (task != null) {
FormattingTuple tp = MessageFormatter.format(format, arg);
task.log(tp.getMessage(), Project.MSG_WARN);
}
}
@Override
public void warn(String format, Object... arguments) {
if (task != null) {
FormattingTuple tp = MessageFormatter.format(format, arguments);
task.log(tp.getMessage(), Project.MSG_WARN);
}
}
@Override
public void warn(String format, Object arg1, Object arg2) {
if (task != null) {
FormattingTuple tp = MessageFormatter.format(format, arg1, arg2);
task.log(tp.getMessage(), Project.MSG_WARN);
}
}
@Override
public void warn(String msg, Throwable t) {
if (task != null) {
task.log(msg, t, Project.MSG_WARN);
}
}
@Override
public boolean isErrorEnabled() {
return true;
}
@Override
public void error(String msg) {
if (task != null) {
task.log(msg, Project.MSG_ERR);
}
}
@Override
public void error(String format, Object arg) {
if (task != null) {
FormattingTuple tp = MessageFormatter.format(format, arg);
task.log(tp.getMessage(), Project.MSG_ERR);
}
}
@Override
public void error(String format, Object arg1, Object arg2) {
if (task != null) {
FormattingTuple tp = MessageFormatter.format(format, arg1, arg2);
task.log(tp.getMessage(), Project.MSG_ERR);
}
}
@Override
public void error(String format, Object... arguments) {
if (task != null) {
FormattingTuple tp = MessageFormatter.format(format, arguments);
task.log(tp.getMessage(), Project.MSG_ERR);
}
}
@Override
public void error(String msg, Throwable t) {
if (task != null) {
task.log(msg, t, Project.MSG_ERR);
}
}
}

View File

@@ -0,0 +1,41 @@
/*
* This file is part of dependency-check-ant.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright (c) 2013 Jeremy Long. All Rights Reserved.
*/
package org.owasp.dependencycheck.ant.logging;
import org.apache.tools.ant.Task;
import org.slf4j.ILoggerFactory;
import org.slf4j.Logger;
/**
* An implementation of {@link org.slf4j.ILoggerFactory} which always returns
* {@link AntLoggerAdapter} instances.
*
* @author colezlaw
*/
public class AntLoggerFactory implements ILoggerFactory {
private AntLoggerAdapter antLoggerAdapter;
public AntLoggerFactory(Task task) {
super();
this.antLoggerAdapter = new AntLoggerAdapter(task);
}
public Logger getLogger(String name) {
return antLoggerAdapter;
}
}

View File

@@ -21,9 +21,8 @@ import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.util.List; import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.tools.ant.BuildException; import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.Task; import org.apache.tools.ant.Task;
import org.apache.tools.ant.types.EnumeratedAttribute; import org.apache.tools.ant.types.EnumeratedAttribute;
import org.apache.tools.ant.types.Reference; import org.apache.tools.ant.types.Reference;
@@ -40,8 +39,8 @@ import org.owasp.dependencycheck.dependency.Identifier;
import org.owasp.dependencycheck.dependency.Vulnerability; import org.owasp.dependencycheck.dependency.Vulnerability;
import org.owasp.dependencycheck.reporting.ReportGenerator; import org.owasp.dependencycheck.reporting.ReportGenerator;
import org.owasp.dependencycheck.reporting.ReportGenerator.Format; import org.owasp.dependencycheck.reporting.ReportGenerator.Format;
import org.owasp.dependencycheck.utils.LogUtils;
import org.owasp.dependencycheck.utils.Settings; import org.owasp.dependencycheck.utils.Settings;
import org.slf4j.impl.StaticLoggerBinder;
/** /**
* An Ant task definition to execute dependency-check during an Ant build. * An Ant task definition to execute dependency-check during an Ant build.
@@ -49,7 +48,6 @@ import org.owasp.dependencycheck.utils.Settings;
* @author Jeremy Long * @author Jeremy Long
*/ */
public class DependencyCheckTask extends Task { public class DependencyCheckTask extends Task {
/** /**
* The properties file location. * The properties file location.
*/ */
@@ -62,16 +60,15 @@ public class DependencyCheckTask extends Task {
* System specific new line character. * System specific new line character.
*/ */
private static final String NEW_LINE = System.getProperty("line.separator", "\n").intern(); private static final String NEW_LINE = System.getProperty("line.separator", "\n").intern();
/**
* The logger.
*/
private static final Logger LOGGER = Logger.getLogger(DependencyCheckTask.class.getName());
/** /**
* Construct a new DependencyCheckTask. * Construct a new DependencyCheckTask.
*/ */
public DependencyCheckTask() { public DependencyCheckTask() {
super(); super();
// Call this before Dependency Check Core starts logging anything - this way, all SLF4J messages from
// core end up coming through this tasks logger
StaticLoggerBinder.getSingleton().setTask(this);
} }
//The following code was copied Apache Ant PathConvert //The following code was copied Apache Ant PathConvert
//BEGIN COPY from org.apache.tools.ant.taskdefs.PathConvert //BEGIN COPY from org.apache.tools.ant.taskdefs.PathConvert
@@ -349,7 +346,7 @@ public class DependencyCheckTask extends Task {
*/ */
@Deprecated @Deprecated
public void setProxyUrl(String proxyUrl) { public void setProxyUrl(String proxyUrl) {
LOGGER.warning("A deprecated configuration option 'proxyUrl' was detected; use 'proxyServer' instead."); log("A deprecated configuration option 'proxyUrl' was detected; use 'proxyServer' instead.", Project.MSG_WARN);
this.proxyServer = proxyUrl; this.proxyServer = proxyUrl;
} }
/** /**
@@ -925,9 +922,6 @@ public class DependencyCheckTask extends Task {
@Override @Override
public void execute() throws BuildException { public void execute() throws BuildException {
final InputStream in = DependencyCheckTask.class.getClassLoader().getResourceAsStream(LOG_PROPERTIES_FILE);
LogUtils.prepareLogger(in, logFile);
dealWithReferences(); dealWithReferences();
validateConfiguration(); validateConfiguration();
populateSettings(); populateSettings();
@@ -958,7 +952,7 @@ public class DependencyCheckTask extends Task {
cve.open(); cve.open();
prop = cve.getDatabaseProperties(); prop = cve.getDatabaseProperties();
} catch (DatabaseException ex) { } catch (DatabaseException ex) {
LOGGER.log(Level.FINE, "Unable to retrieve DB Properties", ex); log("Unable to retrieve DB Properties", ex, Project.MSG_DEBUG);
} finally { } finally {
if (cve != null) { if (cve != null) {
cve.close(); cve.close();
@@ -974,16 +968,15 @@ public class DependencyCheckTask extends Task {
showSummary(engine.getDependencies()); showSummary(engine.getDependencies());
} }
} catch (IOException ex) { } catch (IOException ex) {
LOGGER.log(Level.FINE, "Unable to generate dependency-check report", ex); log("Unable to generate dependency-check report", ex, Project.MSG_DEBUG);
throw new BuildException("Unable to generate dependency-check report", ex); throw new BuildException("Unable to generate dependency-check report", ex);
} catch (Exception ex) { } catch (Exception ex) {
LOGGER.log(Level.FINE, "An exception occurred; unable to continue task", ex); log("An exception occurred; unable to continue task", ex, Project.MSG_DEBUG);
throw new BuildException("An exception occurred; unable to continue task", ex); throw new BuildException("An exception occurred; unable to continue task", ex);
} }
} }
} catch (DatabaseException ex) { } catch (DatabaseException ex) {
LOGGER.log(Level.SEVERE, "Unable to connect to the dependency-check database; analysis has stopped"); log("Unable to connect to the dependency-check database; analysis has stopped", ex, Project.MSG_ERR);
LOGGER.log(Level.FINE, "", ex);
} finally { } finally {
Settings.cleanup(true); Settings.cleanup(true);
if (engine != null) { if (engine != null) {
@@ -1017,14 +1010,13 @@ public class DependencyCheckTask extends Task {
taskProperties = this.getClass().getClassLoader().getResourceAsStream(PROPERTIES_FILE); taskProperties = this.getClass().getClassLoader().getResourceAsStream(PROPERTIES_FILE);
Settings.mergeProperties(taskProperties); Settings.mergeProperties(taskProperties);
} catch (IOException ex) { } catch (IOException ex) {
LOGGER.log(Level.WARNING, "Unable to load the dependency-check ant task.properties file."); log("Unable to load the dependency-check ant task.properties file.", ex, Project.MSG_WARN);
LOGGER.log(Level.FINE, null, ex);
} finally { } finally {
if (taskProperties != null) { if (taskProperties != null) {
try { try {
taskProperties.close(); taskProperties.close();
} catch (IOException ex) { } catch (IOException ex) {
LOGGER.log(Level.FINEST, null, ex); log("", ex, Project.MSG_DEBUG);
} }
} }
} }
@@ -1176,7 +1168,7 @@ public class DependencyCheckTask extends Task {
final String msg = String.format("%n%n" final String msg = String.format("%n%n"
+ "One or more dependencies were identified with known vulnerabilities:%n%n%s" + "One or more dependencies were identified with known vulnerabilities:%n%n%s"
+ "%n%nSee the dependency-check report for more details.%n%n", summary.toString()); + "%n%nSee the dependency-check report for more details.%n%n", summary.toString());
LOGGER.log(Level.WARNING, msg); log(msg, Project.MSG_WARN);
} }
} }

View File

@@ -0,0 +1,89 @@
/*
* This file is part of dependency-check-ant.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright (c) 2013 Jeremy Long. All Rights Reserved.
*/
package org.slf4j.impl;
import org.apache.tools.ant.Task;
import org.owasp.dependencycheck.ant.logging.AntLoggerFactory;
import org.slf4j.ILoggerFactory;
import org.slf4j.spi.LoggerFactoryBinder;
/**
* The binding of {@link LoggerFactory} class with an actual instance of
* {@link ILoggerFactory} is performed using information returned by this class.
*
* @author colezlaw
*/
public class StaticLoggerBinder implements LoggerFactoryBinder {
/**
* The unique instance of this class
*
*/
private static final StaticLoggerBinder SINGLETON = new StaticLoggerBinder();
/**
* Return the singleton of this class.
*
* @return the StaticLoggerBinder singleton
*/
public static final StaticLoggerBinder getSingleton() {
return SINGLETON;
}
/**
* Ant tasks have the log method we actually want to call. So we hang onto
* the task as a delegate
*/
private Task task;
/**
* Set the Task which will this is to log through.
*
* @param task the task through which to log
*/
public void setTask(Task task) {
this.task = task;
loggerFactory = new AntLoggerFactory(task);
}
/**
* Declare the version of the SLF4J API this implementation is compiled
* against. The value of this filed is usually modified with each release.
*/
// to avoid constant folding by the compiler, this field must *not* be final
public static String REQUESTED_API_VERSION = "1.7.12"; // final
private static final String loggerFactoryClassStr = AntLoggerFactory.class.getName();
/**
* The ILoggerFactory instance returned by the {@link #getLoggerFactory}
* method should always be the smae object
*/
private ILoggerFactory loggerFactory;
private StaticLoggerBinder() {
loggerFactory = new AntLoggerFactory(task);
}
public ILoggerFactory getLoggerFactory() {
return loggerFactory;
}
public String getLoggerFactoryClassStr() {
return loggerFactoryClassStr;
}
}

View File

@@ -321,5 +321,12 @@ Copyright (c) 2012 - Jeremy Long. All Rights Reserved.
<artifactId>dependency-check-utils</artifactId> <artifactId>dependency-check-utils</artifactId>
<version>${project.parent.version}</version> <version>${project.parent.version}</version>
</dependency> </dependency>
<!-- Logging implementation. We may change this in the future -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-jdk14</artifactId>
<version>${slf4j.version}</version>
<scope>compile</scope>
</dependency>
</dependencies> </dependencies>
</project> </project>

View File

@@ -26,8 +26,6 @@ import java.util.Arrays;
import java.util.HashSet; import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.cli.ParseException; import org.apache.commons.cli.ParseException;
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;
@@ -37,6 +35,8 @@ import org.owasp.dependencycheck.org.apache.tools.ant.DirectoryScanner;
import org.owasp.dependencycheck.reporting.ReportGenerator; import org.owasp.dependencycheck.reporting.ReportGenerator;
import org.owasp.dependencycheck.utils.LogUtils; import org.owasp.dependencycheck.utils.LogUtils;
import org.owasp.dependencycheck.utils.Settings; import org.owasp.dependencycheck.utils.Settings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* The command line interface for the DependencyCheck application. * The command line interface for the DependencyCheck application.
@@ -53,7 +53,7 @@ public class App {
/** /**
* The logger. * The logger.
*/ */
private static final Logger LOGGER = Logger.getLogger(App.class.getName()); private static final Logger LOGGER = LoggerFactory.getLogger(App.class);
/** /**
* The main method for the application. * The main method for the application.
@@ -103,7 +103,7 @@ public class App {
try { try {
runScan(cli.getReportDirectory(), cli.getReportFormat(), cli.getApplicationName(), cli.getScanFiles(), cli.getExcludeList()); runScan(cli.getReportDirectory(), cli.getReportFormat(), cli.getApplicationName(), cli.getScanFiles(), cli.getExcludeList());
} catch (InvalidScanPathException ex) { } catch (InvalidScanPathException ex) {
LOGGER.log(Level.SEVERE, "An invalid scan path was detected; unable to scan '//*' paths"); LOGGER.error("An invalid scan path was detected; unable to scan '//*' paths");
} }
} else { } else {
cli.printHelp(); cli.printHelp();
@@ -189,7 +189,7 @@ public class App {
cve.open(); cve.open();
prop = cve.getDatabaseProperties(); prop = cve.getDatabaseProperties();
} catch (DatabaseException ex) { } catch (DatabaseException ex) {
LOGGER.log(Level.FINE, "Unable to retrieve DB Properties", ex); LOGGER.debug("Unable to retrieve DB Properties", ex);
} finally { } finally {
if (cve != null) { if (cve != null) {
cve.close(); cve.close();
@@ -199,15 +199,15 @@ public class App {
try { try {
report.generateReports(reportDirectory, outputFormat); report.generateReports(reportDirectory, outputFormat);
} catch (IOException ex) { } catch (IOException ex) {
LOGGER.log(Level.SEVERE, "There was an IO error while attempting to generate the report."); LOGGER.error("There was an IO error while attempting to generate the report.");
LOGGER.log(Level.FINE, null, ex); LOGGER.debug("", ex);
} catch (Throwable ex) { } catch (Throwable ex) {
LOGGER.log(Level.SEVERE, "There was an error while attempting to generate the report."); LOGGER.error("There was an error while attempting to generate the report.");
LOGGER.log(Level.FINE, null, ex); LOGGER.debug("", ex);
} }
} catch (DatabaseException ex) { } catch (DatabaseException ex) {
LOGGER.log(Level.SEVERE, "Unable to connect to the dependency-check database; analysis has stopped"); LOGGER.error("Unable to connect to the dependency-check database; analysis has stopped");
LOGGER.log(Level.FINE, "", ex); LOGGER.debug("", ex);
} finally { } finally {
if (engine != null) { if (engine != null) {
engine.cleanup(); engine.cleanup();
@@ -224,8 +224,8 @@ public class App {
engine = new Engine(); engine = new Engine();
engine.doUpdates(); engine.doUpdates();
} catch (DatabaseException ex) { } catch (DatabaseException ex) {
LOGGER.log(Level.SEVERE, "Unable to connect to the dependency-check database; analysis has stopped"); LOGGER.error("Unable to connect to the dependency-check database; analysis has stopped");
LOGGER.log(Level.FINE, "", ex); LOGGER.debug("", ex);
} finally { } finally {
if (engine != null) { if (engine != null) {
engine.cleanup(); engine.cleanup();
@@ -271,13 +271,11 @@ public class App {
try { try {
Settings.mergeProperties(propertiesFile); Settings.mergeProperties(propertiesFile);
} catch (FileNotFoundException ex) { } catch (FileNotFoundException ex) {
final String msg = String.format("Unable to load properties file '%s'", propertiesFile.getPath()); LOGGER.error("Unable to load properties file '{}'", propertiesFile.getPath());
LOGGER.log(Level.SEVERE, msg); LOGGER.debug("", ex);
LOGGER.log(Level.FINE, null, ex);
} catch (IOException ex) { } catch (IOException ex) {
final String msg = String.format("Unable to find properties file '%s'", propertiesFile.getPath()); LOGGER.error("Unable to find properties file '{}'", propertiesFile.getPath());
LOGGER.log(Level.SEVERE, msg); LOGGER.debug("", ex);
LOGGER.log(Level.FINE, null, ex);
} }
} }
// We have to wait until we've merged the properties before attempting to set whether we use // We have to wait until we've merged the properties before attempting to set whether we use

View File

@@ -19,7 +19,6 @@ package org.owasp.dependencycheck;
import java.io.File; import java.io.File;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.util.logging.Logger;
import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.CommandLineParser;
@@ -33,6 +32,8 @@ import org.apache.commons.cli.PosixParser;
import org.owasp.dependencycheck.reporting.ReportGenerator.Format; import org.owasp.dependencycheck.reporting.ReportGenerator.Format;
import org.owasp.dependencycheck.utils.InvalidSettingException; import org.owasp.dependencycheck.utils.InvalidSettingException;
import org.owasp.dependencycheck.utils.Settings; import org.owasp.dependencycheck.utils.Settings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* A utility to parse command line arguments for the DependencyCheck. * A utility to parse command line arguments for the DependencyCheck.
@@ -44,7 +45,7 @@ public final class CliParser {
/** /**
* The logger. * The logger.
*/ */
private static final Logger LOGGER = Logger.getLogger(CliParser.class.getName()); private static final Logger LOGGER = LoggerFactory.getLogger(CliParser.class);
/** /**
* The command line. * The command line.
*/ */
@@ -633,7 +634,7 @@ public final class CliParser {
if (server == null) { if (server == null) {
server = line.getOptionValue(ARGUMENT.PROXY_URL); server = line.getOptionValue(ARGUMENT.PROXY_URL);
if (server != null) { if (server != null) {
LOGGER.warning("An old command line argument 'proxyurl' was detected; use proxyserver instead"); LOGGER.warn("An old command line argument 'proxyurl' was detected; use proxyserver instead");
} }
} }
return server; return server;

View File

@@ -361,6 +361,23 @@ Copyright (c) 2012 Jeremy Long. All Rights Reserved.
</reporting> </reporting>
<dependencies> <dependencies>
<!-- Note, to stay compatible with Jenkins installations only JARs compiled to 1.6 can be used --> <!-- Note, to stay compatible with Jenkins installations only JARs compiled to 1.6 can be used -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
<!-- Set this to test so that each project that uses this has to have its own implementation of SLF4J -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<scope>test</scope>
</dependency>
<!-- For the CAL10N support -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-ext</artifactId>
<version>${slf4j.version}</version>
<scope>compile</scope>
</dependency>
<dependency> <dependency>
<groupId>org.owasp</groupId> <groupId>org.owasp</groupId>
<artifactId>dependency-check-utils</artifactId> <artifactId>dependency-check-utils</artifactId>

View File

@@ -24,8 +24,6 @@ import java.util.HashSet;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.owasp.dependencycheck.analyzer.AnalysisPhase; import org.owasp.dependencycheck.analyzer.AnalysisPhase;
import org.owasp.dependencycheck.analyzer.Analyzer; import org.owasp.dependencycheck.analyzer.Analyzer;
import org.owasp.dependencycheck.analyzer.AnalyzerService; import org.owasp.dependencycheck.analyzer.AnalyzerService;
@@ -42,6 +40,8 @@ import org.owasp.dependencycheck.exception.NoDataException;
import org.owasp.dependencycheck.utils.FileUtils; import org.owasp.dependencycheck.utils.FileUtils;
import org.owasp.dependencycheck.utils.InvalidSettingException; import org.owasp.dependencycheck.utils.InvalidSettingException;
import org.owasp.dependencycheck.utils.Settings; import org.owasp.dependencycheck.utils.Settings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* Scans files, directories, etc. for Dependencies. Analyzers are loaded and used to process the files found by the scan, if a * Scans files, directories, etc. for Dependencies. Analyzers are loaded and used to process the files found by the scan, if a
@@ -72,7 +72,7 @@ public class Engine {
/** /**
* The Logger for use throughout the class. * The Logger for use throughout the class.
*/ */
private static final Logger LOGGER = Logger.getLogger(Engine.class.getName()); private static final Logger LOGGER = LoggerFactory.getLogger(Engine.class);
/** /**
* Creates a new Engine. * Creates a new Engine.
@@ -313,8 +313,7 @@ public class Engine {
*/ */
protected Dependency scanFile(File file) { protected Dependency scanFile(File file) {
if (!file.isFile()) { if (!file.isFile()) {
final String msg = String.format("Path passed to scanFile(File) is not a file: %s. Skipping the file.", file.toString()); LOGGER.debug("Path passed to scanFile(File) is not a file: {}. Skipping the file.", file);
LOGGER.log(Level.FINE, msg);
return null; return null;
} }
final String fileName = file.getName(); final String fileName = file.getName();
@@ -341,7 +340,7 @@ public class Engine {
try { try {
autoUpdate = Settings.getBoolean(Settings.KEYS.AUTO_UPDATE); autoUpdate = Settings.getBoolean(Settings.KEYS.AUTO_UPDATE);
} catch (InvalidSettingException ex) { } catch (InvalidSettingException ex) {
LOGGER.log(Level.FINE, "Invalid setting for auto-update; using true."); LOGGER.debug("Invalid setting for auto-update; using true.");
} }
if (autoUpdate) { if (autoUpdate) {
doUpdates(); doUpdates();
@@ -351,24 +350,18 @@ public class Engine {
try { try {
ensureDataExists(); ensureDataExists();
} catch (NoDataException ex) { } catch (NoDataException ex) {
final String msg = String.format("%s%n%nUnable to continue dependency-check analysis.", ex.getMessage()); LOGGER.error("{}\n\nUnable to continue dependency-check analysis.", ex.getMessage());
LOGGER.log(Level.SEVERE, msg); LOGGER.debug("", ex);
LOGGER.log(Level.FINE, null, ex);
return; return;
} catch (DatabaseException ex) { } catch (DatabaseException ex) {
final String msg = String.format("%s%n%nUnable to continue dependency-check analysis.", ex.getMessage()); LOGGER.error("{}\n\nUnable to continue dependency-check analysis.", ex.getMessage());
LOGGER.log(Level.SEVERE, msg); LOGGER.debug("", ex);
LOGGER.log(Level.FINE, null, ex);
return; return;
} }
final String logHeader = String.format("%n" LOGGER.debug("\n----------------------------------------------------\nBEGIN ANALYSIS\n----------------------------------------------------");
+ "----------------------------------------------------%n" LOGGER.info("Analysis Starting");
+ "BEGIN ANALYSIS%n"
+ "----------------------------------------------------");
LOGGER.log(Level.FINE, logHeader);
LOGGER.log(Level.INFO, "Analysis Starting");
// analysis phases // analysis phases
for (AnalysisPhase phase : AnalysisPhase.values()) { for (AnalysisPhase phase : AnalysisPhase.values()) {
@@ -381,8 +374,7 @@ public class Engine {
* analyzers may modify it. This prevents ConcurrentModificationExceptions. * analyzers may modify it. This prevents ConcurrentModificationExceptions.
* This is okay for adds/deletes because it happens per analyzer. * This is okay for adds/deletes because it happens per analyzer.
*/ */
final String msg = String.format("Begin Analyzer '%s'", a.getName()); LOGGER.debug("Begin Analyzer '{}'", a.getName());
LOGGER.log(Level.FINE, msg);
final Set<Dependency> dependencySet = new HashSet<Dependency>(); final Set<Dependency> dependencySet = new HashSet<Dependency>();
dependencySet.addAll(dependencies); dependencySet.addAll(dependencies);
for (Dependency d : dependencySet) { for (Dependency d : dependencySet) {
@@ -392,19 +384,16 @@ public class Engine {
shouldAnalyze = fAnalyzer.supportsExtension(d.getFileExtension()); shouldAnalyze = fAnalyzer.supportsExtension(d.getFileExtension());
} }
if (shouldAnalyze) { if (shouldAnalyze) {
final String msgFile = String.format("Begin Analysis of '%s'", d.getActualFilePath()); LOGGER.debug("Begin Analysis of '{}'", d.getActualFilePath());
LOGGER.log(Level.FINE, msgFile);
try { try {
a.analyze(d, this); a.analyze(d, this);
} catch (AnalysisException ex) { } catch (AnalysisException ex) {
final String exMsg = String.format("An error occurred while analyzing '%s'.", d.getActualFilePath()); LOGGER.warn("An error occurred while analyzing '{}'.", d.getActualFilePath());
LOGGER.log(Level.WARNING, exMsg); LOGGER.debug("", ex);
LOGGER.log(Level.FINE, "", ex);
} catch (Throwable ex) { } catch (Throwable ex) {
final String axMsg = String.format("An unexpected error occurred during analysis of '%s'", d.getActualFilePath());
//final AnalysisException ax = new AnalysisException(axMsg, ex); //final AnalysisException ax = new AnalysisException(axMsg, ex);
LOGGER.log(Level.WARNING, axMsg); LOGGER.warn("An unexpected error occurred during analysis of '{}'", d.getActualFilePath());
LOGGER.log(Level.FINE, "", ex); LOGGER.debug("", ex);
} }
} }
} }
@@ -418,12 +407,8 @@ public class Engine {
} }
} }
final String logFooter = String.format("%n" LOGGER.debug("\n----------------------------------------------------\nEND ANALYSIS\n----------------------------------------------------");
+ "----------------------------------------------------%n" LOGGER.info("Analysis Complete");
+ "END ANALYSIS%n"
+ "----------------------------------------------------");
LOGGER.log(Level.FINE, logFooter);
LOGGER.log(Level.INFO, "Analysis Complete");
} }
/** /**
@@ -434,17 +419,15 @@ public class Engine {
*/ */
protected Analyzer initializeAnalyzer(Analyzer analyzer) { protected Analyzer initializeAnalyzer(Analyzer analyzer) {
try { try {
final String msg = String.format("Initializing %s", analyzer.getName()); LOGGER.debug("Initializing {}", analyzer.getName());
LOGGER.log(Level.FINE, msg);
analyzer.initialize(); analyzer.initialize();
} catch (Throwable ex) { } catch (Throwable ex) {
final String msg = String.format("Exception occurred initializing %s.", analyzer.getName()); LOGGER.error("Exception occurred initializing {}.", analyzer.getName());
LOGGER.log(Level.SEVERE, msg); LOGGER.debug("", ex);
LOGGER.log(Level.FINE, null, ex);
try { try {
analyzer.close(); analyzer.close();
} catch (Throwable ex1) { } catch (Throwable ex1) {
LOGGER.log(Level.FINEST, null, ex1); LOGGER.trace("", ex1);
} }
} }
return analyzer; return analyzer;
@@ -456,12 +439,11 @@ public class Engine {
* @param analyzer the analyzer to close * @param analyzer the analyzer to close
*/ */
protected void closeAnalyzer(Analyzer analyzer) { protected void closeAnalyzer(Analyzer analyzer) {
final String msg = String.format("Closing Analyzer '%s'", analyzer.getName()); LOGGER.debug("Closing Analyzer '{}'", analyzer.getName());
LOGGER.log(Level.FINE, msg);
try { try {
analyzer.close(); analyzer.close();
} catch (Throwable ex) { } catch (Throwable ex) {
LOGGER.log(Level.FINEST, null, ex); LOGGER.trace("", ex);
} }
} }
@@ -477,9 +459,9 @@ public class Engine {
try { try {
source.update(); source.update();
} catch (UpdateException ex) { } catch (UpdateException ex) {
LOGGER.log(Level.WARNING, LOGGER.warn(
"Unable to update Cached Web DataSource, using local data instead. Results may not include recent vulnerabilities."); "Unable to update Cached Web DataSource, using local data instead. Results may not include recent vulnerabilities.");
LOGGER.log(Level.FINE, String.format("Unable to update details for %s", source.getClass().getName()), ex); LOGGER.debug("Unable to update details for {}", source.getClass().getName(), ex);
} }
} }
LOGGER.info("Check for updates complete"); LOGGER.info("Check for updates complete");

View File

@@ -20,8 +20,6 @@ package org.owasp.dependencycheck.agent;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.util.List; import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.owasp.dependencycheck.Engine; import org.owasp.dependencycheck.Engine;
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;
@@ -32,6 +30,8 @@ import org.owasp.dependencycheck.dependency.Vulnerability;
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;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* This class provides a way to easily conduct a scan solely based on existing evidence metadata rather than collecting evidence * This class provides a way to easily conduct a scan solely based on existing evidence metadata rather than collecting evidence
@@ -67,7 +67,7 @@ public class DependencyCheckScanAgent {
/** /**
* Logger for use throughout the class. * Logger for use throughout the class.
*/ */
private static final Logger LOGGER = Logger.getLogger(DependencyCheckScanAgent.class.getName()); private static final Logger LOGGER = LoggerFactory.getLogger(DependencyCheckScanAgent.class);
/** /**
* The application name for the report. * The application name for the report.
*/ */
@@ -861,7 +861,7 @@ public class DependencyCheckScanAgent {
cve.open(); cve.open();
prop = cve.getDatabaseProperties(); prop = cve.getDatabaseProperties();
} catch (DatabaseException ex) { } catch (DatabaseException ex) {
LOGGER.log(Level.FINE, "Unable to retrieve DB Properties", ex); LOGGER.debug("Unable to retrieve DB Properties", ex);
} finally { } finally {
if (cve != null) { if (cve != null) {
cve.close(); cve.close();
@@ -871,13 +871,13 @@ public class DependencyCheckScanAgent {
try { try {
r.generateReports(outDirectory.getCanonicalPath(), this.reportFormat.name()); r.generateReports(outDirectory.getCanonicalPath(), this.reportFormat.name());
} catch (IOException ex) { } catch (IOException ex) {
LOGGER.log(Level.SEVERE, LOGGER.error(
"Unexpected exception occurred during analysis; please see the verbose error log for more details."); "Unexpected exception occurred during analysis; please see the verbose error log for more details.");
LOGGER.log(Level.FINE, null, ex); LOGGER.debug("", ex);
} catch (Throwable ex) { } catch (Throwable ex) {
LOGGER.log(Level.SEVERE, LOGGER.error(
"Unexpected exception occurred during analysis; please see the verbose error log for more details."); "Unexpected exception occurred during analysis; please see the verbose error log for more details.");
LOGGER.log(Level.FINE, null, ex); LOGGER.debug("", ex);
} }
} }
@@ -981,9 +981,9 @@ public class DependencyCheckScanAgent {
checkForFailure(engine.getDependencies()); checkForFailure(engine.getDependencies());
} }
} catch (DatabaseException ex) { } catch (DatabaseException ex) {
LOGGER.log(Level.SEVERE, LOGGER.error(
"Unable to connect to the dependency-check database; analysis has stopped"); "Unable to connect to the dependency-check database; analysis has stopped");
LOGGER.log(Level.FINE, "", ex); LOGGER.debug("", ex);
} finally { } finally {
Settings.cleanup(true); Settings.cleanup(true);
if (engine != null) { if (engine != null) {
@@ -1058,10 +1058,8 @@ public class DependencyCheckScanAgent {
} }
} }
if (summary.length() > 0) { if (summary.length() > 0) {
final String msg = String.format("%n%n" LOGGER.warn("\n\nOne or more dependencies were identified with known vulnerabilities:\n\n{}\n\nSee the dependency-check report for more details.\n\n",
+ "One or more dependencies were identified with known vulnerabilities:%n%n%s" summary.toString());
+ "%n%nSee the dependency-check report for more details.%n%n", summary.toString());
LOGGER.log(Level.WARNING, msg);
} }
} }

View File

@@ -20,13 +20,13 @@ package org.owasp.dependencycheck.analyzer;
import java.util.Collections; import java.util.Collections;
import java.util.HashSet; import java.util.HashSet;
import java.util.Set; import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.owasp.dependencycheck.Engine; import org.owasp.dependencycheck.Engine;
import org.owasp.dependencycheck.analyzer.exception.AnalysisException; import org.owasp.dependencycheck.analyzer.exception.AnalysisException;
import org.owasp.dependencycheck.dependency.Dependency; import org.owasp.dependencycheck.dependency.Dependency;
import org.owasp.dependencycheck.utils.InvalidSettingException; import org.owasp.dependencycheck.utils.InvalidSettingException;
import org.owasp.dependencycheck.utils.Settings; import org.owasp.dependencycheck.utils.Settings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* The base FileTypeAnalyzer that all analyzers that have specific file types they analyze should extend. * The base FileTypeAnalyzer that all analyzers that have specific file types they analyze should extend.
@@ -49,7 +49,7 @@ public abstract class AbstractFileTypeAnalyzer extends AbstractAnalyzer implemen
/** /**
* The logger. * The logger.
*/ */
private static final Logger LOGGER = Logger.getLogger(AbstractFileTypeAnalyzer.class.getName()); private static final Logger LOGGER = LoggerFactory.getLogger(AbstractFileTypeAnalyzer.class);
/** /**
* Whether the file type analyzer detected any files it needs to analyze. * Whether the file type analyzer detected any files it needs to analyze.
*/ */
@@ -164,11 +164,9 @@ public abstract class AbstractFileTypeAnalyzer extends AbstractAnalyzer implemen
try { try {
enabled = Settings.getBoolean(key, true); enabled = Settings.getBoolean(key, true);
} catch (InvalidSettingException ex) { } catch (InvalidSettingException ex) {
String msg = String.format("Invalid setting for property '%s'", key); LOGGER.warn("Invalid setting for property '{}'", key);
LOGGER.log(Level.WARNING, msg); LOGGER.debug("", ex);
LOGGER.log(Level.FINE, "", ex); LOGGER.warn("{} has been disabled", getName());
msg = String.format("%s has been disabled", getName());
LOGGER.log(Level.WARNING, msg);
} }
} }
@@ -200,9 +198,8 @@ public abstract class AbstractFileTypeAnalyzer extends AbstractAnalyzer implemen
} }
final Set<String> ext = getSupportedExtensions(); final Set<String> ext = getSupportedExtensions();
if (ext == null) { if (ext == null) {
final String msg = String.format("The '%s' analyzer is misconfigured and does not have any file extensions;" LOGGER.error("The '{}' analyzer is misconfigured and does not have any file extensions;"
+ " it will be disabled", getName()); + " it will be disabled", getName());
LOGGER.log(Level.SEVERE, msg);
return false; return false;
} else { } else {
final boolean match = ext.contains(extension); final boolean match = ext.contains(extension);

View File

@@ -24,8 +24,6 @@ import java.net.MalformedURLException;
import java.net.URL; import java.net.URL;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import org.owasp.dependencycheck.suppression.SuppressionParseException; import org.owasp.dependencycheck.suppression.SuppressionParseException;
import org.owasp.dependencycheck.suppression.SuppressionParser; import org.owasp.dependencycheck.suppression.SuppressionParser;
@@ -34,6 +32,8 @@ import org.owasp.dependencycheck.utils.DownloadFailedException;
import org.owasp.dependencycheck.utils.Downloader; import org.owasp.dependencycheck.utils.Downloader;
import org.owasp.dependencycheck.utils.FileUtils; import org.owasp.dependencycheck.utils.FileUtils;
import org.owasp.dependencycheck.utils.Settings; import org.owasp.dependencycheck.utils.Settings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* Abstract base suppression analyzer that contains methods for parsing the suppression xml file. * Abstract base suppression analyzer that contains methods for parsing the suppression xml file.
@@ -45,7 +45,7 @@ public abstract class AbstractSuppressionAnalyzer extends AbstractAnalyzer {
/** /**
* The Logger for use throughout the class * The Logger for use throughout the class
*/ */
private static final Logger LOGGER = Logger.getLogger(AbstractSuppressionAnalyzer.class.getName()); private static final Logger LOGGER = LoggerFactory.getLogger(AbstractSuppressionAnalyzer.class);
//<editor-fold defaultstate="collapsed" desc="All standard implementation details of Analyzer"> //<editor-fold defaultstate="collapsed" desc="All standard implementation details of Analyzer">
/** /**
@@ -103,7 +103,7 @@ public abstract class AbstractSuppressionAnalyzer extends AbstractAnalyzer {
try { try {
rules = parser.parseSuppressionRules(this.getClass().getClassLoader().getResourceAsStream("dependencycheck-base-suppression.xml")); rules = parser.parseSuppressionRules(this.getClass().getClassLoader().getResourceAsStream("dependencycheck-base-suppression.xml"));
} catch (SuppressionParseException ex) { } catch (SuppressionParseException ex) {
LOGGER.log(Level.FINE, "Unable to parse the base suppression data file", ex); LOGGER.debug("Unable to parse the base suppression data file", ex);
} }
final String suppressionFilePath = Settings.getString(Settings.KEYS.SUPPRESSION_FILE); final String suppressionFilePath = Settings.getString(Settings.KEYS.SUPPRESSION_FILE);
if (suppressionFilePath == null) { if (suppressionFilePath == null) {
@@ -141,12 +141,11 @@ public abstract class AbstractSuppressionAnalyzer extends AbstractAnalyzer {
try { try {
//rules = parser.parseSuppressionRules(file); //rules = parser.parseSuppressionRules(file);
rules.addAll(parser.parseSuppressionRules(file)); rules.addAll(parser.parseSuppressionRules(file));
LOGGER.log(Level.FINE, rules.size() + " suppression rules were loaded."); LOGGER.debug("{} suppression rules were loaded.", rules.size());
} catch (SuppressionParseException ex) { } catch (SuppressionParseException ex) {
final String msg = String.format("Unable to parse suppression xml file '%s'", file.getPath()); LOGGER.warn("Unable to parse suppression xml file '{}'", file.getPath());
LOGGER.log(Level.WARNING, msg); LOGGER.warn(ex.getMessage());
LOGGER.log(Level.WARNING, ex.getMessage()); LOGGER.debug("", ex);
LOGGER.log(Level.FINE, "", ex);
throw ex; throw ex;
} }
} }
@@ -171,8 +170,8 @@ public abstract class AbstractSuppressionAnalyzer extends AbstractAnalyzer {
* @throws SuppressionParseException throws the generated SuppressionParseException * @throws SuppressionParseException throws the generated SuppressionParseException
*/ */
private void throwSuppressionParseException(String message, Exception exception) throws SuppressionParseException { private void throwSuppressionParseException(String message, Exception exception) throws SuppressionParseException {
LOGGER.log(Level.WARNING, message); LOGGER.warn(message);
LOGGER.log(Level.FINE, "", exception); LOGGER.debug("", exception);
throw new SuppressionParseException(message, exception); throw new SuppressionParseException(message, exception);
} }
} }

View File

@@ -31,8 +31,6 @@ import java.util.Enumeration;
import java.util.HashSet; import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.compress.archivers.ArchiveEntry; import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.archivers.ArchiveInputStream; import org.apache.commons.compress.archivers.ArchiveInputStream;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
@@ -48,6 +46,8 @@ import org.owasp.dependencycheck.analyzer.exception.ArchiveExtractionException;
import org.owasp.dependencycheck.dependency.Dependency; import org.owasp.dependencycheck.dependency.Dependency;
import org.owasp.dependencycheck.utils.FileUtils; import org.owasp.dependencycheck.utils.FileUtils;
import org.owasp.dependencycheck.utils.Settings; import org.owasp.dependencycheck.utils.Settings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* <p> * <p>
@@ -61,7 +61,7 @@ public class ArchiveAnalyzer extends AbstractFileTypeAnalyzer {
/** /**
* The logger. * The logger.
*/ */
private static final Logger LOGGER = Logger.getLogger(ArchiveAnalyzer.class.getName()); private static final Logger LOGGER = LoggerFactory.getLogger(ArchiveAnalyzer.class);
/** /**
* The buffer size to use when extracting files from the archive. * The buffer size to use when extracting files from the archive.
*/ */
@@ -184,10 +184,10 @@ public class ArchiveAnalyzer extends AbstractFileTypeAnalyzer {
@Override @Override
public void close() throws Exception { public void close() throws Exception {
if (tempFileLocation != null && tempFileLocation.exists()) { if (tempFileLocation != null && tempFileLocation.exists()) {
LOGGER.log(Level.FINE, "Attempting to delete temporary files"); LOGGER.debug("Attempting to delete temporary files");
final boolean success = FileUtils.delete(tempFileLocation); final boolean success = FileUtils.delete(tempFileLocation);
if (!success && tempFileLocation != null && tempFileLocation.exists() && tempFileLocation.list().length > 0) { if (!success && tempFileLocation != null && tempFileLocation.exists() && tempFileLocation.list().length > 0) {
LOGGER.log(Level.WARNING, "Failed to delete some temporary files, see the log for more details"); LOGGER.warn("Failed to delete some temporary files, see the log for more details");
} }
} }
} }
@@ -264,8 +264,7 @@ public class ArchiveAnalyzer extends AbstractFileTypeAnalyzer {
} }
} }
} catch (IOException ex) { } catch (IOException ex) {
final String msg = String.format("Unable to perform deep copy on '%s'", dependency.getActualFile().getPath()); LOGGER.debug("Unable to perform deep copy on '{}'", dependency.getActualFile().getPath(), ex);
LOGGER.log(Level.FINE, msg, ex);
} }
} }
engine.getDependencies().remove(dependency); engine.getDependencies().remove(dependency);
@@ -310,7 +309,7 @@ public class ArchiveAnalyzer extends AbstractFileTypeAnalyzer {
try { try {
fis = new FileInputStream(archive); fis = new FileInputStream(archive);
} catch (FileNotFoundException ex) { } catch (FileNotFoundException ex) {
LOGGER.log(Level.FINE, null, ex); LOGGER.debug("", ex);
throw new AnalysisException("Archive file was not found.", ex); throw new AnalysisException("Archive file was not found.", ex);
} }
final String archiveExt = FileUtils.getFileExtension(archive.getName()).toLowerCase(); final String archiveExt = FileUtils.getFileExtension(archive.getName()).toLowerCase();
@@ -327,18 +326,16 @@ public class ArchiveAnalyzer extends AbstractFileTypeAnalyzer {
} }
} }
} catch (ArchiveExtractionException ex) { } catch (ArchiveExtractionException ex) {
final String msg = String.format("Exception extracting archive '%s'.", archive.getName()); LOGGER.warn("Exception extracting archive '{}'.", archive.getName());
LOGGER.log(Level.WARNING, msg); LOGGER.debug("", ex);
LOGGER.log(Level.FINE, null, ex);
} catch (IOException ex) { } catch (IOException ex) {
final String msg = String.format("Exception reading archive '%s'.", archive.getName()); LOGGER.warn("Exception reading archive '{}'.", archive.getName());
LOGGER.log(Level.WARNING, msg); LOGGER.debug("", ex);
LOGGER.log(Level.FINE, null, ex);
} finally { } finally {
try { try {
fis.close(); fis.close();
} catch (IOException ex) { } catch (IOException ex) {
LOGGER.log(Level.FINE, null, ex); LOGGER.debug("", ex);
} }
} }
} }
@@ -367,8 +364,7 @@ public class ArchiveAnalyzer extends AbstractFileTypeAnalyzer {
final File file = new File(destination, entry.getName()); final File file = new File(destination, entry.getName());
final String ext = FileUtils.getFileExtension(file.getName()); final String ext = FileUtils.getFileExtension(file.getName());
if (engine.supportsExtension(ext)) { if (engine.supportsExtension(ext)) {
final String extracting = String.format("Extracting '%s'", file.getPath()); LOGGER.debug("Extracting '{}'", file.getPath());
LOGGER.fine(extracting);
BufferedOutputStream bos = null; BufferedOutputStream bos = null;
FileOutputStream fos = null; FileOutputStream fos = null;
try { try {
@@ -388,11 +384,11 @@ public class ArchiveAnalyzer extends AbstractFileTypeAnalyzer {
} }
bos.flush(); bos.flush();
} catch (FileNotFoundException ex) { } catch (FileNotFoundException ex) {
LOGGER.log(Level.FINE, null, ex); LOGGER.debug("", ex);
final String msg = String.format("Unable to find file '%s'.", file.getName()); final String msg = String.format("Unable to find file '%s'.", file.getName());
throw new AnalysisException(msg, ex); throw new AnalysisException(msg, ex);
} catch (IOException ex) { } catch (IOException ex) {
LOGGER.log(Level.FINE, null, ex); LOGGER.debug("", ex);
final String msg = String.format("IO Exception while parsing file '%s'.", file.getName()); final String msg = String.format("IO Exception while parsing file '%s'.", file.getName());
throw new AnalysisException(msg, ex); throw new AnalysisException(msg, ex);
} finally { } finally {
@@ -400,14 +396,14 @@ public class ArchiveAnalyzer extends AbstractFileTypeAnalyzer {
try { try {
bos.close(); bos.close();
} catch (IOException ex) { } catch (IOException ex) {
LOGGER.log(Level.FINEST, null, ex); LOGGER.trace("", ex);
} }
} }
if (fos != null) { if (fos != null) {
try { try {
fos.close(); fos.close();
} catch (IOException ex) { } catch (IOException ex) {
LOGGER.log(Level.FINEST, null, ex); LOGGER.trace("", ex);
} }
} }
} }
@@ -423,7 +419,7 @@ public class ArchiveAnalyzer extends AbstractFileTypeAnalyzer {
try { try {
input.close(); input.close();
} catch (IOException ex) { } catch (IOException ex) {
LOGGER.log(Level.FINEST, null, ex); LOGGER.trace("", ex);
} }
} }
} }
@@ -437,8 +433,7 @@ public class ArchiveAnalyzer extends AbstractFileTypeAnalyzer {
* @throws ArchiveExtractionException thrown if there is an exception decompressing the file * @throws ArchiveExtractionException thrown if there is an exception decompressing the file
*/ */
private void decompressFile(CompressorInputStream inputStream, File outputFile) throws ArchiveExtractionException { private void decompressFile(CompressorInputStream inputStream, File outputFile) throws ArchiveExtractionException {
final String msg = String.format("Decompressing '%s'", outputFile.getPath()); LOGGER.debug("Decompressing '{}'", outputFile.getPath());
LOGGER.fine(msg);
FileOutputStream out = null; FileOutputStream out = null;
try { try {
out = new FileOutputStream(outputFile); out = new FileOutputStream(outputFile);
@@ -448,17 +443,17 @@ public class ArchiveAnalyzer extends AbstractFileTypeAnalyzer {
out.write(buffer, 0, n); out.write(buffer, 0, n);
} }
} catch (FileNotFoundException ex) { } catch (FileNotFoundException ex) {
LOGGER.log(Level.FINE, null, ex); LOGGER.debug("", ex);
throw new ArchiveExtractionException(ex); throw new ArchiveExtractionException(ex);
} catch (IOException ex) { } catch (IOException ex) {
LOGGER.log(Level.FINE, null, ex); LOGGER.debug("", ex);
throw new ArchiveExtractionException(ex); throw new ArchiveExtractionException(ex);
} finally { } finally {
if (out != null) { if (out != null) {
try { try {
out.close(); out.close();
} catch (IOException ex) { } catch (IOException ex) {
LOGGER.log(Level.FINEST, null, ex); LOGGER.trace("", ex);
} }
} }
} }
@@ -490,7 +485,7 @@ public class ArchiveAnalyzer extends AbstractFileTypeAnalyzer {
} }
} }
} catch (IOException ex) { } catch (IOException ex) {
LOGGER.log(Level.FINE, String.format("Unable to unzip zip file '%s'", dependency.getFilePath()), ex); LOGGER.debug("Unable to unzip zip file '{}'", dependency.getFilePath(), ex);
} finally { } finally {
ZipFile.closeQuietly(zip); ZipFile.closeQuietly(zip);
} }

View File

@@ -25,20 +25,26 @@ import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Locale;
import java.util.Set; import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath; import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory; import javax.xml.xpath.XPathFactory;
import ch.qos.cal10n.IMessageConveyor;
import ch.qos.cal10n.MessageConveyor;
import org.owasp.dependencycheck.Engine; import org.owasp.dependencycheck.Engine;
import org.owasp.dependencycheck.analyzer.exception.AnalysisException; import org.owasp.dependencycheck.analyzer.exception.AnalysisException;
import org.owasp.dependencycheck.dependency.Confidence; import org.owasp.dependencycheck.dependency.Confidence;
import org.owasp.dependencycheck.dependency.Dependency; import org.owasp.dependencycheck.dependency.Dependency;
import org.owasp.dependencycheck.dependency.Evidence; import org.owasp.dependencycheck.dependency.Evidence;
import org.owasp.dependencycheck.utils.DCResources;
import org.owasp.dependencycheck.utils.Settings; import org.owasp.dependencycheck.utils.Settings;
import org.slf4j.Logger;
import org.slf4j.cal10n.LocLogger;
import org.slf4j.cal10n.LocLoggerFactory;
import org.w3c.dom.Document; import org.w3c.dom.Document;
import org.xml.sax.SAXException; import org.xml.sax.SAXException;
@@ -70,10 +76,18 @@ public class AssemblyAnalyzer extends AbstractFileTypeAnalyzer {
* The DocumentBuilder for parsing the XML * The DocumentBuilder for parsing the XML
*/ */
private DocumentBuilder builder; private DocumentBuilder builder;
/**
* Message Conveyer
*/
private IMessageConveyor messageConveyer = new MessageConveyor(Locale.getDefault());
/**
* LocLoggerFactory for localized logger
*/
private LocLoggerFactory llFactory = new LocLoggerFactory(messageConveyer);
/** /**
* Logger * Logger
*/ */
private static final Logger LOGGER = Logger.getLogger(AssemblyAnalyzer.class.getName(), "dependencycheck-resources"); private LocLogger LOGGER = llFactory.getLocLogger(AssemblyAnalyzer.class);
/** /**
* Builds the beginnings of a List for ProcessBuilder * Builds the beginnings of a List for ProcessBuilder
@@ -106,7 +120,7 @@ public class AssemblyAnalyzer extends AbstractFileTypeAnalyzer {
public void analyzeFileType(Dependency dependency, Engine engine) public void analyzeFileType(Dependency dependency, Engine engine)
throws AnalysisException { throws AnalysisException {
if (grokAssemblyExe == null) { if (grokAssemblyExe == null) {
LOGGER.warning("analyzer.AssemblyAnalyzer.notdeployed"); LOGGER.warn(DCResources.NOTDEPLOYED);
return; return;
} }
@@ -122,7 +136,7 @@ public class AssemblyAnalyzer extends AbstractFileTypeAnalyzer {
String line = null; String line = null;
// CHECKSTYLE:OFF // CHECKSTYLE:OFF
while (rdr.ready() && (line = rdr.readLine()) != null) { while (rdr.ready() && (line = rdr.readLine()) != null) {
LOGGER.log(Level.WARNING, "analyzer.AssemblyAnalyzer.grokassembly.stderr", line); LOGGER.warn(DCResources.GROKERROR, line);
} }
// CHECKSTYLE:ON // CHECKSTYLE:ON
int rc = 0; int rc = 0;
@@ -134,10 +148,10 @@ public class AssemblyAnalyzer extends AbstractFileTypeAnalyzer {
return; return;
} }
if (rc == 3) { if (rc == 3) {
LOGGER.log(Level.FINE, "analyzer.AssemblyAnalyzer.notassembly", dependency.getActualFilePath()); LOGGER.debug(DCResources.NOTASSEMBLY, dependency.getActualFilePath());
return; return;
} else if (rc != 0) { } else if (rc != 0) {
LOGGER.log(Level.WARNING, "analyzer.AssemblyAnalyzer.grokassembly.rc", rc); LOGGER.warn(DCResources.GROKRC, rc);
} }
final XPath xpath = XPathFactory.newInstance().newXPath(); final XPath xpath = XPathFactory.newInstance().newXPath();
@@ -178,7 +192,7 @@ public class AssemblyAnalyzer extends AbstractFileTypeAnalyzer {
try { try {
rdr.close(); rdr.close();
} catch (IOException ex) { } catch (IOException ex) {
LOGGER.log(Level.FINEST, "ignore", ex); LOGGER.debug("ignore", ex);
} }
} }
} }
@@ -205,24 +219,24 @@ public class AssemblyAnalyzer extends AbstractFileTypeAnalyzer {
grokAssemblyExe = tempFile; grokAssemblyExe = tempFile;
// Set the temp file to get deleted when we're done // Set the temp file to get deleted when we're done
grokAssemblyExe.deleteOnExit(); grokAssemblyExe.deleteOnExit();
LOGGER.log(Level.FINE, "analyzer.AssemblyAnalyzer.grokassembly.deployed", grokAssemblyExe.getPath()); LOGGER.debug(DCResources.GROKDEPLOYED, grokAssemblyExe.getPath());
} catch (IOException ioe) { } catch (IOException ioe) {
this.setEnabled(false); this.setEnabled(false);
LOGGER.log(Level.WARNING, "analyzer.AssemblyAnalyzer.grokassembly.notdeployed", ioe.getMessage()); LOGGER.warn(DCResources.GROKNOTDEPLOYED, ioe.getMessage());
throw new AnalysisException("Could not extract GrokAssembly.exe", ioe); throw new AnalysisException("Could not extract GrokAssembly.exe", ioe);
} finally { } finally {
if (fos != null) { if (fos != null) {
try { try {
fos.close(); fos.close();
} catch (Throwable e) { } catch (Throwable e) {
LOGGER.fine("Error closing output stream"); LOGGER.debug("Error closing output stream");
} }
} }
if (is != null) { if (is != null) {
try { try {
is.close(); is.close();
} catch (Throwable e) { } catch (Throwable e) {
LOGGER.fine("Error closing input stream"); LOGGER.debug("Error closing input stream");
} }
} }
} }
@@ -244,8 +258,8 @@ public class AssemblyAnalyzer extends AbstractFileTypeAnalyzer {
final XPath xpath = XPathFactory.newInstance().newXPath(); final XPath xpath = XPathFactory.newInstance().newXPath();
final String error = xpath.evaluate("/assembly/error", doc); final String error = xpath.evaluate("/assembly/error", doc);
if (p.waitFor() != 1 || error == null || "".equals(error)) { if (p.waitFor() != 1 || error == null || "".equals(error)) {
LOGGER.warning("An error occurred with the .NET AssemblyAnalyzer, please see the log for more details."); LOGGER.warn("An error occurred with the .NET AssemblyAnalyzer, please see the log for more details.");
LOGGER.fine("GrokAssembly.exe is not working properly"); LOGGER.debug("GrokAssembly.exe is not working properly");
grokAssemblyExe = null; grokAssemblyExe = null;
this.setEnabled(false); this.setEnabled(false);
throw new AnalysisException("Could not execute .NET AssemblyAnalyzer"); throw new AnalysisException("Could not execute .NET AssemblyAnalyzer");
@@ -254,8 +268,8 @@ public class AssemblyAnalyzer extends AbstractFileTypeAnalyzer {
if (e instanceof AnalysisException) { if (e instanceof AnalysisException) {
throw (AnalysisException) e; throw (AnalysisException) e;
} else { } else {
LOGGER.warning("analyzer.AssemblyAnalyzer.grokassembly.initialization.failed"); LOGGER.warn(DCResources.GROKINITFAIL);
LOGGER.log(Level.FINE, "analyzer.AssemblyAnalyzer.grokassembly.initialization.message", e.getMessage()); LOGGER.debug(DCResources.GROKINITMSG, e.getMessage());
this.setEnabled(false); this.setEnabled(false);
throw new AnalysisException("An error occured with the .NET AssemblyAnalyzer", e); throw new AnalysisException("An error occured with the .NET AssemblyAnalyzer", e);
} }
@@ -264,7 +278,7 @@ public class AssemblyAnalyzer extends AbstractFileTypeAnalyzer {
try { try {
rdr.close(); rdr.close();
} catch (IOException ex) { } catch (IOException ex) {
LOGGER.log(Level.FINEST, "ignore", ex); LOGGER.trace("ignore", ex);
} }
} }
} }
@@ -279,7 +293,7 @@ public class AssemblyAnalyzer extends AbstractFileTypeAnalyzer {
grokAssemblyExe.deleteOnExit(); grokAssemblyExe.deleteOnExit();
} }
} catch (SecurityException se) { } catch (SecurityException se) {
LOGGER.fine("analyzer.AssemblyAnalyzer.grokassembly.notdeleted"); LOGGER.debug(DCResources.GROKNOTDELETED);
} }
} }

View File

@@ -25,8 +25,6 @@ import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import java.util.StringTokenizer; import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.lucene.document.Document; import org.apache.lucene.document.Document;
import org.apache.lucene.index.CorruptIndexException; import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.queryparser.classic.ParseException; import org.apache.lucene.queryparser.classic.ParseException;
@@ -49,6 +47,8 @@ import org.owasp.dependencycheck.dependency.Identifier;
import org.owasp.dependencycheck.dependency.VulnerableSoftware; import org.owasp.dependencycheck.dependency.VulnerableSoftware;
import org.owasp.dependencycheck.utils.DependencyVersion; import org.owasp.dependencycheck.utils.DependencyVersion;
import org.owasp.dependencycheck.utils.DependencyVersionUtil; import org.owasp.dependencycheck.utils.DependencyVersionUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* CPEAnalyzer is a utility class that takes a project dependency and attempts to discern if there is an associated CPE. It uses * CPEAnalyzer is a utility class that takes a project dependency and attempts to discern if there is an associated CPE. It uses
@@ -61,7 +61,7 @@ public class CPEAnalyzer implements Analyzer {
/** /**
* The Logger. * The Logger.
*/ */
private static final Logger LOGGER = Logger.getLogger(CPEAnalyzer.class.getName()); private static final Logger LOGGER = LoggerFactory.getLogger(CPEAnalyzer.class);
/** /**
* The maximum number of query results to return. * The maximum number of query results to return.
*/ */
@@ -134,15 +134,15 @@ public class CPEAnalyzer implements Analyzer {
* process. * process.
*/ */
public void open() throws IOException, DatabaseException { public void open() throws IOException, DatabaseException {
LOGGER.log(Level.FINE, "Opening the CVE Database"); LOGGER.debug("Opening the CVE Database");
cve = new CveDB(); cve = new CveDB();
cve.open(); cve.open();
LOGGER.log(Level.FINE, "Creating the Lucene CPE Index"); LOGGER.debug("Creating the Lucene CPE Index");
cpe = CpeMemoryIndex.getInstance(); cpe = CpeMemoryIndex.getInstance();
try { try {
cpe.open(cve); cpe.open(cve);
} catch (IndexException ex) { } catch (IndexException ex) {
LOGGER.log(Level.FINE, "IndexException", ex); LOGGER.debug("IndexException", ex);
throw new DatabaseException(ex); throw new DatabaseException(ex);
} }
} }
@@ -180,11 +180,11 @@ public class CPEAnalyzer implements Analyzer {
for (Confidence confidence : Confidence.values()) { for (Confidence confidence : Confidence.values()) {
if (dependency.getVendorEvidence().contains(confidence)) { if (dependency.getVendorEvidence().contains(confidence)) {
vendors = addEvidenceWithoutDuplicateTerms(vendors, dependency.getVendorEvidence(), confidence); vendors = addEvidenceWithoutDuplicateTerms(vendors, dependency.getVendorEvidence(), confidence);
LOGGER.fine(String.format("vendor search: %s", vendors)); LOGGER.debug("vendor search: {}", vendors);
} }
if (dependency.getProductEvidence().contains(confidence)) { if (dependency.getProductEvidence().contains(confidence)) {
products = addEvidenceWithoutDuplicateTerms(products, dependency.getProductEvidence(), confidence); products = addEvidenceWithoutDuplicateTerms(products, dependency.getProductEvidence(), confidence);
LOGGER.fine(String.format("product search: %s", products)); LOGGER.debug("product search: {}", products);
} }
if (!vendors.isEmpty() && !products.isEmpty()) { if (!vendors.isEmpty() && !products.isEmpty()) {
final List<IndexEntry> entries = searchCPE(vendors, products, dependency.getProductEvidence().getWeighting(), final List<IndexEntry> entries = searchCPE(vendors, products, dependency.getProductEvidence().getWeighting(),
@@ -194,11 +194,11 @@ public class CPEAnalyzer implements Analyzer {
} }
boolean identifierAdded = false; boolean identifierAdded = false;
for (IndexEntry e : entries) { for (IndexEntry e : entries) {
LOGGER.fine(String.format("Verifying entry: %s", e.toString())); LOGGER.debug("Verifying entry: {}", e);
if (verifyEntry(e, dependency)) { if (verifyEntry(e, dependency)) {
final String vendor = e.getVendor(); final String vendor = e.getVendor();
final String product = e.getProduct(); final String product = e.getProduct();
LOGGER.fine(String.format("identified vendor/product: %s/%s", vendor, product)); LOGGER.debug("identified vendor/product: {}/{}", vendor, product);
identifierAdded |= determineIdentifiers(dependency, vendor, product, confidence); identifierAdded |= determineIdentifiers(dependency, vendor, product, confidence);
} }
} }
@@ -281,13 +281,11 @@ public class CPEAnalyzer implements Analyzer {
} }
return ret; return ret;
} catch (ParseException ex) { } catch (ParseException ex) {
final String msg = String.format("Unable to parse: %s", searchString); LOGGER.warn("An error occured querying the CPE data. See the log for more details.");
LOGGER.log(Level.WARNING, "An error occured querying the CPE data. See the log for more details."); LOGGER.info("Unable to parse: {}", searchString, ex);
LOGGER.log(Level.INFO, msg, ex);
} catch (IOException ex) { } catch (IOException ex) {
final String msg = String.format("IO Error with search string: %s", searchString); LOGGER.warn("An error occured reading CPE data. See the log for more details.");
LOGGER.log(Level.WARNING, "An error occured reading CPE data. See the log for more details."); LOGGER.info("IO Error with search string: {}", searchString, ex);
LOGGER.log(Level.INFO, msg, ex);
} }
return null; return null;
} }

View File

@@ -23,8 +23,6 @@ import java.io.IOException;
import java.net.URL; import java.net.URL;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.io.FileUtils; import org.apache.commons.io.FileUtils;
import org.owasp.dependencycheck.Engine; import org.owasp.dependencycheck.Engine;
import org.owasp.dependencycheck.analyzer.exception.AnalysisException; import org.owasp.dependencycheck.analyzer.exception.AnalysisException;
@@ -38,6 +36,8 @@ import org.owasp.dependencycheck.utils.DownloadFailedException;
import org.owasp.dependencycheck.utils.Downloader; import org.owasp.dependencycheck.utils.Downloader;
import org.owasp.dependencycheck.utils.InvalidSettingException; import org.owasp.dependencycheck.utils.InvalidSettingException;
import org.owasp.dependencycheck.utils.Settings; import org.owasp.dependencycheck.utils.Settings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* Analyzer which will attempt to locate a dependency, and the GAV information, by querying Central for the dependency's SHA-1 * Analyzer which will attempt to locate a dependency, and the GAV information, by querying Central for the dependency's SHA-1
@@ -50,7 +50,7 @@ public class CentralAnalyzer extends AbstractFileTypeAnalyzer {
/** /**
* The logger. * The logger.
*/ */
private static final Logger LOGGER = Logger.getLogger(CentralAnalyzer.class.getName()); private static final Logger LOGGER = LoggerFactory.getLogger(CentralAnalyzer.class);
/** /**
* The name of the analyzer. * The name of the analyzer.
@@ -103,7 +103,7 @@ public class CentralAnalyzer extends AbstractFileTypeAnalyzer {
if (Settings.getBoolean(Settings.KEYS.ANALYZER_CENTRAL_ENABLED)) { if (Settings.getBoolean(Settings.KEYS.ANALYZER_CENTRAL_ENABLED)) {
if (!Settings.getBoolean(Settings.KEYS.ANALYZER_NEXUS_ENABLED) if (!Settings.getBoolean(Settings.KEYS.ANALYZER_NEXUS_ENABLED)
|| NexusAnalyzer.DEFAULT_URL.equals(Settings.getString(Settings.KEYS.ANALYZER_NEXUS_URL))) { || NexusAnalyzer.DEFAULT_URL.equals(Settings.getString(Settings.KEYS.ANALYZER_NEXUS_URL))) {
LOGGER.fine("Enabling the Central analyzer"); LOGGER.debug("Enabling the Central analyzer");
retval = true; retval = true;
} else { } else {
LOGGER.info("Nexus analyzer is enabled, disabling the Central Analyzer"); LOGGER.info("Nexus analyzer is enabled, disabling the Central Analyzer");
@@ -112,7 +112,7 @@ public class CentralAnalyzer extends AbstractFileTypeAnalyzer {
LOGGER.info("Central analyzer disabled"); LOGGER.info("Central analyzer disabled");
} }
} catch (InvalidSettingException ise) { } catch (InvalidSettingException ise) {
LOGGER.warning("Invalid setting. Disabling the Central analyzer"); LOGGER.warn("Invalid setting. Disabling the Central analyzer");
} }
return retval; return retval;
} }
@@ -124,11 +124,11 @@ public class CentralAnalyzer extends AbstractFileTypeAnalyzer {
*/ */
@Override @Override
public void initializeFileTypeAnalyzer() throws Exception { public void initializeFileTypeAnalyzer() throws Exception {
LOGGER.fine("Initializing Central analyzer"); LOGGER.debug("Initializing Central analyzer");
LOGGER.fine(String.format("Central analyzer enabled: %s", isEnabled())); LOGGER.debug("Central analyzer enabled: {}", isEnabled());
if (isEnabled()) { if (isEnabled()) {
final String searchUrl = Settings.getString(Settings.KEYS.ANALYZER_CENTRAL_URL); final String searchUrl = Settings.getString(Settings.KEYS.ANALYZER_CENTRAL_URL);
LOGGER.fine(String.format("Central Analyzer URL: %s", searchUrl)); LOGGER.debug("Central Analyzer URL: {}", searchUrl);
searcher = new CentralSearch(new URL(searchUrl)); searcher = new CentralSearch(new URL(searchUrl));
} }
} }
@@ -190,7 +190,7 @@ public class CentralAnalyzer extends AbstractFileTypeAnalyzer {
final List<MavenArtifact> mas = searcher.searchSha1(dependency.getSha1sum()); final List<MavenArtifact> mas = searcher.searchSha1(dependency.getSha1sum());
final Confidence confidence = mas.size() > 1 ? Confidence.HIGH : Confidence.HIGHEST; final Confidence confidence = mas.size() > 1 ? Confidence.HIGH : Confidence.HIGHEST;
for (MavenArtifact ma : mas) { for (MavenArtifact ma : mas) {
LOGGER.fine(String.format("Central analyzer found artifact (%s) for dependency (%s)", ma.toString(), dependency.getFileName())); LOGGER.debug("Central analyzer found artifact ({}) for dependency ({})", ma.toString(), dependency.getFileName());
dependency.addAsEvidence("central", ma, confidence); dependency.addAsEvidence("central", ma, confidence);
boolean pomAnalyzed = false; boolean pomAnalyzed = false;
for (Evidence e : dependency.getVendorEvidence()) { for (Evidence e : dependency.getVendorEvidence()) {
@@ -205,19 +205,17 @@ public class CentralAnalyzer extends AbstractFileTypeAnalyzer {
final File baseDir = Settings.getTempDirectory(); final File baseDir = Settings.getTempDirectory();
pomFile = File.createTempFile("pom", ".xml", baseDir); pomFile = File.createTempFile("pom", ".xml", baseDir);
if (!pomFile.delete()) { if (!pomFile.delete()) {
final String msg = String.format("Unable to fetch pom.xml for %s from Central; " LOGGER.warn("Unable to fetch pom.xml for {} from Central; "
+ "this could result in undetected CPE/CVEs.", dependency.getFileName()); + "this could result in undetected CPE/CVEs.", dependency.getFileName());
LOGGER.warning(msg); LOGGER.debug("Unable to delete temp file");
LOGGER.fine("Unable to delete temp file");
} }
LOGGER.fine(String.format("Downloading %s", ma.getPomUrl())); LOGGER.debug("Downloading {}", ma.getPomUrl());
Downloader.fetchFile(new URL(ma.getPomUrl()), pomFile); Downloader.fetchFile(new URL(ma.getPomUrl()), pomFile);
PomUtils.analyzePOM(dependency, pomFile); PomUtils.analyzePOM(dependency, pomFile);
} catch (DownloadFailedException ex) { } catch (DownloadFailedException ex) {
final String msg = String.format("Unable to download pom.xml for %s from Central; " LOGGER.warn("Unable to download pom.xml for {} from Central; "
+ "this could result in undetected CPE/CVEs.", dependency.getFileName()); + "this could result in undetected CPE/CVEs.", dependency.getFileName());
LOGGER.warning(msg);
} finally { } finally {
if (pomFile != null && !FileUtils.deleteQuietly(pomFile)) { if (pomFile != null && !FileUtils.deleteQuietly(pomFile)) {
pomFile.deleteOnExit(); pomFile.deleteOnExit();
@@ -227,11 +225,11 @@ public class CentralAnalyzer extends AbstractFileTypeAnalyzer {
} }
} catch (IllegalArgumentException iae) { } catch (IllegalArgumentException iae) {
LOGGER.info(String.format("invalid sha1-hash on %s", dependency.getFileName())); LOGGER.info("invalid sha1-hash on {}", dependency.getFileName());
} catch (FileNotFoundException fnfe) { } catch (FileNotFoundException fnfe) {
LOGGER.fine(String.format("Artifact not found in repository: '%s", dependency.getFileName())); LOGGER.debug("Artifact not found in repository: '{}", dependency.getFileName());
} catch (IOException ioe) { } catch (IOException ioe) {
LOGGER.log(Level.FINE, "Could not connect to Central search", ioe); LOGGER.debug("Could not connect to Central search", ioe);
errorFlag = true; errorFlag = true;
} }
} }

View File

@@ -22,8 +22,6 @@ import java.util.HashSet;
import java.util.Iterator; import java.util.Iterator;
import java.util.ListIterator; import java.util.ListIterator;
import java.util.Set; import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import org.owasp.dependencycheck.Engine; import org.owasp.dependencycheck.Engine;
@@ -33,6 +31,8 @@ import org.owasp.dependencycheck.dependency.Identifier;
import org.owasp.dependencycheck.utils.DependencyVersion; import org.owasp.dependencycheck.utils.DependencyVersion;
import org.owasp.dependencycheck.utils.DependencyVersionUtil; import org.owasp.dependencycheck.utils.DependencyVersionUtil;
import org.owasp.dependencycheck.utils.LogUtils; import org.owasp.dependencycheck.utils.LogUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* <p> * <p>
@@ -49,7 +49,7 @@ public class DependencyBundlingAnalyzer extends AbstractAnalyzer implements Anal
/** /**
* The Logger. * The Logger.
*/ */
private static final Logger LOGGER = Logger.getLogger(DependencyBundlingAnalyzer.class.getName()); private static final Logger LOGGER = LoggerFactory.getLogger(DependencyBundlingAnalyzer.class);
//<editor-fold defaultstate="collapsed" desc="Constants and Member Variables"> //<editor-fold defaultstate="collapsed" desc="Constants and Member Variables">
/** /**
@@ -264,8 +264,7 @@ public class DependencyBundlingAnalyzer extends AbstractAnalyzer implements Anal
} }
} }
if (LogUtils.isVerboseLoggingEnabled()) { if (LogUtils.isVerboseLoggingEnabled()) {
final String msg = String.format("IdentifiersMatch=%s (%s, %s)", matches, dependency1.getFileName(), dependency2.getFileName()); LOGGER.debug("IdentifiersMatch={} ({}, {})", matches, dependency1.getFileName(), dependency2.getFileName());
LOGGER.log(Level.FINE, msg);
} }
return matches; return matches;
} }
@@ -345,8 +344,7 @@ public class DependencyBundlingAnalyzer extends AbstractAnalyzer implements Anal
returnVal = leftName.length() <= rightName.length(); returnVal = leftName.length() <= rightName.length();
} }
if (LogUtils.isVerboseLoggingEnabled()) { if (LogUtils.isVerboseLoggingEnabled()) {
final String msg = String.format("IsCore=%s (%s, %s)", returnVal, left.getFileName(), right.getFileName()); LOGGER.debug("IsCore={} ({}, {})", returnVal, left.getFileName(), right.getFileName());
LOGGER.log(Level.FINE, msg);
} }
return returnVal; return returnVal;
} }

View File

@@ -25,8 +25,6 @@ import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.ListIterator; import java.util.ListIterator;
import java.util.Set; import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import org.owasp.dependencycheck.Engine; import org.owasp.dependencycheck.Engine;
@@ -34,6 +32,8 @@ import org.owasp.dependencycheck.analyzer.exception.AnalysisException;
import org.owasp.dependencycheck.dependency.Dependency; import org.owasp.dependencycheck.dependency.Dependency;
import org.owasp.dependencycheck.dependency.Identifier; import org.owasp.dependencycheck.dependency.Identifier;
import org.owasp.dependencycheck.dependency.VulnerableSoftware; import org.owasp.dependencycheck.dependency.VulnerableSoftware;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* This analyzer attempts to remove some well known false positives - specifically regarding the java runtime. * This analyzer attempts to remove some well known false positives - specifically regarding the java runtime.
@@ -45,7 +45,7 @@ public class FalsePositiveAnalyzer extends AbstractAnalyzer {
/** /**
* The Logger. * The Logger.
*/ */
private static final Logger LOGGER = Logger.getLogger(FalsePositiveAnalyzer.class.getName()); private static final Logger LOGGER = LoggerFactory.getLogger(FalsePositiveAnalyzer.class);
//<editor-fold defaultstate="collapsed" desc="All standard implementation details of Analyzer"> //<editor-fold defaultstate="collapsed" desc="All standard implementation details of Analyzer">
/** /**
* The name of the analyzer. * The name of the analyzer.
@@ -171,7 +171,7 @@ public class FalsePositiveAnalyzer extends AbstractAnalyzer {
final String nextVersion = nextCpe.getVersion(); final String nextVersion = nextCpe.getVersion();
if (currentVersion == null && nextVersion == null) { if (currentVersion == null && nextVersion == null) {
//how did we get here? //how did we get here?
LOGGER.log(Level.FINE, "currentVersion and nextVersion are both null?"); LOGGER.debug("currentVersion and nextVersion are both null?");
} else if (currentVersion == null && nextVersion != null) { } else if (currentVersion == null && nextVersion != null) {
dependency.getIdentifiers().remove(currentId); dependency.getIdentifiers().remove(currentId);
} else if (nextVersion == null && currentVersion != null) { } else if (nextVersion == null && currentVersion != null) {
@@ -248,7 +248,7 @@ public class FalsePositiveAnalyzer extends AbstractAnalyzer {
try { try {
cpe.parseName(value); cpe.parseName(value);
} catch (UnsupportedEncodingException ex) { } catch (UnsupportedEncodingException ex) {
LOGGER.log(Level.FINEST, null, ex); LOGGER.trace("", ex);
return null; return null;
} }
return cpe; return cpe;
@@ -397,7 +397,7 @@ public class FalsePositiveAnalyzer extends AbstractAnalyzer {
newCpe4, newCpe4,
String.format(CPEAnalyzer.NVD_SEARCH_URL, URLEncoder.encode(newCpe4, "UTF-8"))); String.format(CPEAnalyzer.NVD_SEARCH_URL, URLEncoder.encode(newCpe4, "UTF-8")));
} catch (UnsupportedEncodingException ex) { } catch (UnsupportedEncodingException ex) {
LOGGER.log(Level.FINE, null, ex); LOGGER.debug("", ex);
} }
} }
} }

View File

@@ -39,8 +39,6 @@ import java.util.jar.Attributes;
import java.util.jar.JarEntry; import java.util.jar.JarEntry;
import java.util.jar.JarFile; import java.util.jar.JarFile;
import java.util.jar.Manifest; import java.util.jar.Manifest;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import java.util.zip.ZipEntry; import java.util.zip.ZipEntry;
import org.jsoup.Jsoup; import org.jsoup.Jsoup;
@@ -54,6 +52,8 @@ import org.owasp.dependencycheck.xml.pom.PomUtils;
import org.owasp.dependencycheck.xml.pom.Model; import org.owasp.dependencycheck.xml.pom.Model;
import org.owasp.dependencycheck.utils.FileUtils; import org.owasp.dependencycheck.utils.FileUtils;
import org.owasp.dependencycheck.utils.Settings; import org.owasp.dependencycheck.utils.Settings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* Used to load a JAR file and collect information that can be used to determine the associated CPE. * Used to load a JAR file and collect information that can be used to determine the associated CPE.
@@ -66,7 +66,7 @@ public class JarAnalyzer extends AbstractFileTypeAnalyzer {
/** /**
* The logger. * The logger.
*/ */
private static final Logger LOGGER = Logger.getLogger(JarAnalyzer.class.getName()); private static final Logger LOGGER = LoggerFactory.getLogger(JarAnalyzer.class);
/** /**
* The buffer size to use when extracting files from the archive. * The buffer size to use when extracting files from the archive.
*/ */
@@ -249,20 +249,16 @@ public class JarAnalyzer extends AbstractFileTypeAnalyzer {
try { try {
jar = new JarFile(dependency.getActualFilePath()); jar = new JarFile(dependency.getActualFilePath());
} catch (IOException ex) { } catch (IOException ex) {
final String msg = String.format("Unable to read JarFile '%s'.", dependency.getActualFilePath()); LOGGER.warn("Unable to read JarFile '{}'.", dependency.getActualFilePath());
//final AnalysisException ax = new AnalysisException(msg, ex); LOGGER.trace("", ex);
LOGGER.log(Level.WARNING, msg);
LOGGER.log(Level.FINE, "", ex);
return false; return false;
} }
List<String> pomEntries; List<String> pomEntries;
try { try {
pomEntries = retrievePomListing(jar); pomEntries = retrievePomListing(jar);
} catch (IOException ex) { } catch (IOException ex) {
final String msg = String.format("Unable to read Jar file entries in '%s'.", dependency.getActualFilePath()); LOGGER.warn("Unable to read Jar file entries in '{}'.", dependency.getActualFilePath());
//final AnalysisException ax = new AnalysisException(msg, ex); LOGGER.trace("", ex);
LOGGER.log(Level.WARNING, msg);
LOGGER.log(Level.FINE, msg, ex);
return false; return false;
} }
File externalPom = null; File externalPom = null;
@@ -277,14 +273,14 @@ public class JarAnalyzer extends AbstractFileTypeAnalyzer {
} }
} }
for (String path : pomEntries) { for (String path : pomEntries) {
LOGGER.fine(String.format("Reading pom entry: %s", path)); LOGGER.debug("Reading pom entry: {}", path);
Properties pomProperties = null; Properties pomProperties = null;
try { try {
if (externalPom == null) { if (externalPom == null) {
pomProperties = retrievePomProperties(path, jar); pomProperties = retrievePomProperties(path, jar);
} }
} catch (IOException ex) { } catch (IOException ex) {
LOGGER.log(Level.FINEST, "ignore this, failed reading a non-existent pom.properties", ex); LOGGER.trace("ignore this, failed reading a non-existent pom.properties", ex);
} }
Model pom = null; Model pom = null;
try { try {
@@ -318,9 +314,8 @@ public class JarAnalyzer extends AbstractFileTypeAnalyzer {
foundSomething |= setPomEvidence(dependency, pom, classes); foundSomething |= setPomEvidence(dependency, pom, classes);
} }
} catch (AnalysisException ex) { } catch (AnalysisException ex) {
final String msg = String.format("An error occured while analyzing '%s'.", dependency.getActualFilePath()); LOGGER.warn("An error occured while analyzing '{}'.", dependency.getActualFilePath());
LOGGER.log(Level.WARNING, msg); LOGGER.trace("", ex);
LOGGER.log(Level.FINE, "", ex);
} }
} }
return foundSomething; return foundSomething;
@@ -344,13 +339,13 @@ public class JarAnalyzer extends AbstractFileTypeAnalyzer {
reader = new InputStreamReader(jar.getInputStream(propEntry), "UTF-8"); reader = new InputStreamReader(jar.getInputStream(propEntry), "UTF-8");
pomProperties = new Properties(); pomProperties = new Properties();
pomProperties.load(reader); pomProperties.load(reader);
LOGGER.fine(String.format("Read pom.properties: %s", propPath)); LOGGER.debug("Read pom.properties: {}", propPath);
} finally { } finally {
if (reader != null) { if (reader != null) {
try { try {
reader.close(); reader.close();
} catch (IOException ex) { } catch (IOException ex) {
LOGGER.log(Level.FINEST, "close error", ex); LOGGER.trace("close error", ex);
} }
} }
} }
@@ -372,7 +367,7 @@ public class JarAnalyzer extends AbstractFileTypeAnalyzer {
final JarEntry entry = entries.nextElement(); final JarEntry entry = entries.nextElement();
final String entryName = (new File(entry.getName())).getName().toLowerCase(); final String entryName = (new File(entry.getName())).getName().toLowerCase();
if (!entry.isDirectory() && "pom.xml".equals(entryName)) { if (!entry.isDirectory() && "pom.xml".equals(entryName)) {
LOGGER.fine(String.format("POM Entry found: %s", entry.getName())); LOGGER.trace("POM Entry found: {}", entry.getName());
pomEntries.add(entry.getName()); pomEntries.add(entry.getName());
} }
} }
@@ -408,9 +403,8 @@ public class JarAnalyzer extends AbstractFileTypeAnalyzer {
bos.flush(); bos.flush();
dependency.setActualFilePath(file.getAbsolutePath()); dependency.setActualFilePath(file.getAbsolutePath());
} catch (IOException ex) { } catch (IOException ex) {
final String msg = String.format("An error occurred reading '%s' from '%s'.", path, dependency.getFilePath()); LOGGER.warn("An error occurred reading '{}' from '{}'.", path, dependency.getFilePath());
LOGGER.warning(msg); LOGGER.error("", ex);
LOGGER.log(Level.SEVERE, "", ex);
} finally { } finally {
closeStream(bos); closeStream(bos);
closeStream(fos); closeStream(fos);
@@ -429,7 +423,7 @@ public class JarAnalyzer extends AbstractFileTypeAnalyzer {
try { try {
stream.close(); stream.close();
} catch (IOException ex) { } catch (IOException ex) {
LOGGER.log(Level.FINEST, null, ex); LOGGER.trace("", ex);
} }
} }
} }
@@ -444,7 +438,7 @@ public class JarAnalyzer extends AbstractFileTypeAnalyzer {
try { try {
stream.close(); stream.close();
} catch (IOException ex) { } catch (IOException ex) {
LOGGER.log(Level.FINEST, null, ex); LOGGER.trace("", ex);
} }
} }
} }
@@ -644,9 +638,8 @@ public class JarAnalyzer extends AbstractFileTypeAnalyzer {
&& !dependency.getFileName().toLowerCase().endsWith("-javadoc.jar") && !dependency.getFileName().toLowerCase().endsWith("-javadoc.jar")
&& !dependency.getFileName().toLowerCase().endsWith("-src.jar") && !dependency.getFileName().toLowerCase().endsWith("-src.jar")
&& !dependency.getFileName().toLowerCase().endsWith("-doc.jar")) { && !dependency.getFileName().toLowerCase().endsWith("-doc.jar")) {
LOGGER.log(Level.FINE, LOGGER.debug("Jar file '{}' does not contain a manifest.",
String.format("Jar file '%s' does not contain a manifest.", dependency.getFileName());
dependency.getFileName()));
} }
return false; return false;
} }
@@ -892,11 +885,10 @@ public class JarAnalyzer extends AbstractFileTypeAnalyzer {
@Override @Override
public void close() { public void close() {
if (tempFileLocation != null && tempFileLocation.exists()) { if (tempFileLocation != null && tempFileLocation.exists()) {
LOGGER.log(Level.FINE, "Attempting to delete temporary files"); LOGGER.debug("Attempting to delete temporary files");
final boolean success = FileUtils.delete(tempFileLocation); final boolean success = FileUtils.delete(tempFileLocation);
if (!success) { if (!success) {
LOGGER.log(Level.WARNING, LOGGER.warn("Failed to delete some temporary files, see the log for more details");
"Failed to delete some temporary files, see the log for more details");
} }
} }
} }
@@ -937,15 +929,14 @@ public class JarAnalyzer extends AbstractFileTypeAnalyzer {
} }
} }
} catch (IOException ex) { } catch (IOException ex) {
final String msg = String.format("Unable to open jar file '%s'.", dependency.getFileName()); LOGGER.warn("Unable to open jar file '{}'.", dependency.getFileName());
LOGGER.log(Level.WARNING, msg); LOGGER.debug("", ex);
LOGGER.log(Level.FINE, null, ex);
} finally { } finally {
if (jar != null) { if (jar != null) {
try { try {
jar.close(); jar.close();
} catch (IOException ex) { } catch (IOException ex) {
LOGGER.log(Level.FINEST, null, ex); LOGGER.trace("", ex);
} }
} }
} }

View File

@@ -23,13 +23,13 @@ import java.io.FileNotFoundException;
import java.io.FileReader; import java.io.FileReader;
import java.io.IOException; import java.io.IOException;
import java.util.Set; import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import org.owasp.dependencycheck.Engine; import org.owasp.dependencycheck.Engine;
import org.owasp.dependencycheck.analyzer.exception.AnalysisException; import org.owasp.dependencycheck.analyzer.exception.AnalysisException;
import org.owasp.dependencycheck.dependency.Dependency; import org.owasp.dependencycheck.dependency.Dependency;
import org.owasp.dependencycheck.utils.Settings; import org.owasp.dependencycheck.utils.Settings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* *
@@ -42,7 +42,7 @@ public class JavaScriptAnalyzer extends AbstractFileTypeAnalyzer {
/** /**
* The logger. * The logger.
*/ */
private static final Logger LOGGER = Logger.getLogger(JavaScriptAnalyzer.class.getName()); private static final Logger LOGGER = LoggerFactory.getLogger(JavaScriptAnalyzer.class);
//<editor-fold defaultstate="collapsed" desc="All standard implementation details of Analyzer"> //<editor-fold defaultstate="collapsed" desc="All standard implementation details of Analyzer">
/** /**
@@ -122,13 +122,13 @@ public class JavaScriptAnalyzer extends AbstractFileTypeAnalyzer {
final String msg = String.format("Dependency file not found: '%s'", dependency.getActualFilePath()); final String msg = String.format("Dependency file not found: '%s'", dependency.getActualFilePath());
throw new AnalysisException(msg, ex); throw new AnalysisException(msg, ex);
} catch (IOException ex) { } catch (IOException ex) {
LOGGER.log(Level.SEVERE, null, ex); LOGGER.error("", ex);
} finally { } finally {
if (fin != null) { if (fin != null) {
try { try {
fin.close(); fin.close();
} catch (IOException ex) { } catch (IOException ex) {
LOGGER.log(Level.FINEST, null, ex); LOGGER.trace("", ex);
} }
} }
} }

View File

@@ -23,8 +23,6 @@ import java.io.IOException;
import java.net.MalformedURLException; import java.net.MalformedURLException;
import java.net.URL; import java.net.URL;
import java.util.Set; import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.io.FileUtils; import org.apache.commons.io.FileUtils;
import org.owasp.dependencycheck.Engine; import org.owasp.dependencycheck.Engine;
import org.owasp.dependencycheck.analyzer.exception.AnalysisException; import org.owasp.dependencycheck.analyzer.exception.AnalysisException;
@@ -38,6 +36,8 @@ import org.owasp.dependencycheck.utils.InvalidSettingException;
import org.owasp.dependencycheck.utils.DownloadFailedException; import org.owasp.dependencycheck.utils.DownloadFailedException;
import org.owasp.dependencycheck.utils.Downloader; import org.owasp.dependencycheck.utils.Downloader;
import org.owasp.dependencycheck.utils.Settings; import org.owasp.dependencycheck.utils.Settings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* Analyzer which will attempt to locate a dependency on a Nexus service by SHA-1 digest of the dependency. * Analyzer which will attempt to locate a dependency on a Nexus service by SHA-1 digest of the dependency.
@@ -63,7 +63,7 @@ public class NexusAnalyzer extends AbstractFileTypeAnalyzer {
/** /**
* The logger. * The logger.
*/ */
private static final Logger LOGGER = Logger.getLogger(NexusAnalyzer.class.getName()); private static final Logger LOGGER = LoggerFactory.getLogger(NexusAnalyzer.class);
/** /**
* The name of the analyzer. * The name of the analyzer.
@@ -107,10 +107,10 @@ public class NexusAnalyzer extends AbstractFileTypeAnalyzer {
LOGGER.info("Enabling Nexus analyzer"); LOGGER.info("Enabling Nexus analyzer");
retval = true; retval = true;
} else { } else {
LOGGER.fine("Nexus analyzer disabled, using Central instead"); LOGGER.debug("Nexus analyzer disabled, using Central instead");
} }
} catch (InvalidSettingException ise) { } catch (InvalidSettingException ise) {
LOGGER.warning("Invalid setting. Disabling Nexus analyzer"); LOGGER.warn("Invalid setting. Disabling Nexus analyzer");
} }
return retval; return retval;
@@ -133,21 +133,21 @@ public class NexusAnalyzer extends AbstractFileTypeAnalyzer {
*/ */
@Override @Override
public void initializeFileTypeAnalyzer() throws Exception { public void initializeFileTypeAnalyzer() throws Exception {
LOGGER.fine("Initializing Nexus Analyzer"); LOGGER.debug("Initializing Nexus Analyzer");
LOGGER.fine(String.format("Nexus Analyzer enabled: %s", isEnabled())); LOGGER.debug("Nexus Analyzer enabled: {}", isEnabled());
if (isEnabled()) { if (isEnabled()) {
final String searchUrl = Settings.getString(Settings.KEYS.ANALYZER_NEXUS_URL); final String searchUrl = Settings.getString(Settings.KEYS.ANALYZER_NEXUS_URL);
LOGGER.fine(String.format("Nexus Analyzer URL: %s", searchUrl)); LOGGER.debug("Nexus Analyzer URL: {}", searchUrl);
try { try {
searcher = new NexusSearch(new URL(searchUrl)); searcher = new NexusSearch(new URL(searchUrl));
if (!searcher.preflightRequest()) { if (!searcher.preflightRequest()) {
LOGGER.warning("There was an issue getting Nexus status. Disabling analyzer."); LOGGER.warn("There was an issue getting Nexus status. Disabling analyzer.");
setEnabled(false); setEnabled(false);
} }
} catch (MalformedURLException mue) { } catch (MalformedURLException mue) {
// I know that initialize can throw an exception, but we'll // I know that initialize can throw an exception, but we'll
// just disable the analyzer if the URL isn't valid // just disable the analyzer if the URL isn't valid
LOGGER.warning(String.format("Property %s not a valid URL. Nexus Analyzer disabled", searchUrl)); LOGGER.warn("Property {} not a valid URL. Nexus Analyzer disabled", searchUrl);
setEnabled(false); setEnabled(false);
} }
} }
@@ -209,7 +209,7 @@ public class NexusAnalyzer extends AbstractFileTypeAnalyzer {
final MavenArtifact ma = searcher.searchSha1(dependency.getSha1sum()); final MavenArtifact ma = searcher.searchSha1(dependency.getSha1sum());
dependency.addAsEvidence("nexus", ma, Confidence.HIGH); dependency.addAsEvidence("nexus", ma, Confidence.HIGH);
boolean pomAnalyzed = false; boolean pomAnalyzed = false;
LOGGER.fine("POM URL " + ma.getPomUrl()); LOGGER.debug("POM URL {}", ma.getPomUrl());
for (Evidence e : dependency.getVendorEvidence()) { for (Evidence e : dependency.getVendorEvidence()) {
if ("pom".equals(e.getSource())) { if ("pom".equals(e.getSource())) {
pomAnalyzed = true; pomAnalyzed = true;
@@ -222,18 +222,16 @@ public class NexusAnalyzer extends AbstractFileTypeAnalyzer {
final File baseDir = Settings.getTempDirectory(); final File baseDir = Settings.getTempDirectory();
pomFile = File.createTempFile("pom", ".xml", baseDir); pomFile = File.createTempFile("pom", ".xml", baseDir);
if (!pomFile.delete()) { if (!pomFile.delete()) {
final String msg = String.format("Unable to fetch pom.xml for %s from Nexus repository; " LOGGER.warn("Unable to fetch pom.xml for {} from Nexus repository; "
+ "this could result in undetected CPE/CVEs.", dependency.getFileName()); + "this could result in undetected CPE/CVEs.", dependency.getFileName());
LOGGER.warning(msg); LOGGER.debug("Unable to delete temp file");
LOGGER.fine("Unable to delete temp file");
} }
LOGGER.fine(String.format("Downloading %s", ma.getPomUrl())); LOGGER.debug("Downloading {}", ma.getPomUrl());
Downloader.fetchFile(new URL(ma.getPomUrl()), pomFile); Downloader.fetchFile(new URL(ma.getPomUrl()), pomFile);
PomUtils.analyzePOM(dependency, pomFile); PomUtils.analyzePOM(dependency, pomFile);
} catch (DownloadFailedException ex) { } catch (DownloadFailedException ex) {
final String msg = String.format("Unable to download pom.xml for %s from Nexus repository; " LOGGER.warn("Unable to download pom.xml for {} from Nexus repository; "
+ "this could result in undetected CPE/CVEs.", dependency.getFileName()); + "this could result in undetected CPE/CVEs.", dependency.getFileName());
LOGGER.warning(msg);
} finally { } finally {
if (pomFile != null && !FileUtils.deleteQuietly(pomFile)) { if (pomFile != null && !FileUtils.deleteQuietly(pomFile)) {
pomFile.deleteOnExit(); pomFile.deleteOnExit();
@@ -245,11 +243,11 @@ public class NexusAnalyzer extends AbstractFileTypeAnalyzer {
LOGGER.info(String.format("invalid sha-1 hash on %s", dependency.getFileName())); LOGGER.info(String.format("invalid sha-1 hash on %s", dependency.getFileName()));
} catch (FileNotFoundException fnfe) { } catch (FileNotFoundException fnfe) {
//dependency.addAnalysisException(new AnalysisException("Artifact not found on repository")); //dependency.addAnalysisException(new AnalysisException("Artifact not found on repository"));
LOGGER.fine(String.format("Artifact not found in repository '%s'", dependency.getFileName())); LOGGER.debug("Artifact not found in repository '{}'", dependency.getFileName());
LOGGER.log(Level.FINE, fnfe.getMessage(), fnfe); LOGGER.debug(fnfe.getMessage(), fnfe);
} catch (IOException ioe) { } catch (IOException ioe) {
//dependency.addAnalysisException(new AnalysisException("Could not connect to repository", ioe)); //dependency.addAnalysisException(new AnalysisException("Could not connect to repository", ioe));
LOGGER.log(Level.FINE, "Could not connect to nexus repository", ioe); LOGGER.debug("Could not connect to nexus repository", ioe);
} }
} }
} }

View File

@@ -21,8 +21,6 @@ import java.io.FileInputStream;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.IOException; import java.io.IOException;
import java.util.Set; import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.owasp.dependencycheck.Engine; import org.owasp.dependencycheck.Engine;
import org.owasp.dependencycheck.analyzer.exception.AnalysisException; import org.owasp.dependencycheck.analyzer.exception.AnalysisException;
import org.owasp.dependencycheck.data.nuget.NugetPackage; import org.owasp.dependencycheck.data.nuget.NugetPackage;
@@ -32,6 +30,8 @@ import org.owasp.dependencycheck.data.nuget.XPathNuspecParser;
import org.owasp.dependencycheck.dependency.Confidence; import org.owasp.dependencycheck.dependency.Confidence;
import org.owasp.dependencycheck.dependency.Dependency; import org.owasp.dependencycheck.dependency.Dependency;
import org.owasp.dependencycheck.utils.Settings; import org.owasp.dependencycheck.utils.Settings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* Analyzer which will parse a Nuspec file to gather module information. * Analyzer which will parse a Nuspec file to gather module information.
@@ -43,7 +43,7 @@ public class NuspecAnalyzer extends AbstractFileTypeAnalyzer {
/** /**
* The logger. * The logger.
*/ */
private static final Logger LOGGER = Logger.getLogger(NuspecAnalyzer.class.getName()); private static final Logger LOGGER = LoggerFactory.getLogger(NuspecAnalyzer.class);
/** /**
* The name of the analyzer. * The name of the analyzer.
@@ -118,7 +118,7 @@ public class NuspecAnalyzer extends AbstractFileTypeAnalyzer {
*/ */
@Override @Override
public void analyzeFileType(Dependency dependency, Engine engine) throws AnalysisException { public void analyzeFileType(Dependency dependency, Engine engine) throws AnalysisException {
LOGGER.log(Level.FINE, "Checking Nuspec file {0}", dependency.toString()); LOGGER.debug("Checking Nuspec file {}", dependency.toString());
try { try {
final NuspecParser parser = new XPathNuspecParser(); final NuspecParser parser = new XPathNuspecParser();
NugetPackage np = null; NugetPackage np = null;
@@ -135,7 +135,7 @@ public class NuspecAnalyzer extends AbstractFileTypeAnalyzer {
try { try {
fis.close(); fis.close();
} catch (IOException e) { } catch (IOException e) {
LOGGER.fine("Error closing input stream"); LOGGER.debug("Error closing input stream");
} }
} }
} }

View File

@@ -23,8 +23,6 @@ import java.io.FileInputStream;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.FilenameFilter; import java.io.FilenameFilter;
import java.util.Set; import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import javax.mail.MessagingException; import javax.mail.MessagingException;
@@ -44,6 +42,8 @@ import org.owasp.dependencycheck.utils.ExtractionUtil;
import org.owasp.dependencycheck.utils.FileUtils; import org.owasp.dependencycheck.utils.FileUtils;
import org.owasp.dependencycheck.utils.Settings; import org.owasp.dependencycheck.utils.Settings;
import org.owasp.dependencycheck.utils.UrlStringUtils; import org.owasp.dependencycheck.utils.UrlStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* Used to analyze a Wheel or egg distribution files, or their contents in unzipped form, and collect information that can be used * Used to analyze a Wheel or egg distribution files, or their contents in unzipped form, and collect information that can be used
@@ -66,8 +66,8 @@ public class PythonDistributionAnalyzer extends AbstractFileTypeAnalyzer {
/** /**
* The logger. * The logger.
*/ */
private static final Logger LOGGER = Logger private static final Logger LOGGER = LoggerFactory
.getLogger(PythonDistributionAnalyzer.class.getName()); .getLogger(PythonDistributionAnalyzer.class);
/** /**
* The count of directories created during analysis. This is used for creating temporary directories. * The count of directories created during analysis. This is used for creating temporary directories.
@@ -203,7 +203,7 @@ public class PythonDistributionAnalyzer extends AbstractFileTypeAnalyzer {
FilenameFilter folderFilter, FilenameFilter metadataFilter) FilenameFilter folderFilter, FilenameFilter metadataFilter)
throws AnalysisException { throws AnalysisException {
final File temp = getNextTempDirectory(); final File temp = getNextTempDirectory();
LOGGER.fine(String.format("%s exists? %b", temp, temp.exists())); LOGGER.debug("{} exists? {}", temp, temp.exists());
try { try {
ExtractionUtil.extractFilesUsingFilter( ExtractionUtil.extractFilesUsingFilter(
new File(dependency.getActualFilePath()), temp, new File(dependency.getActualFilePath()), temp,
@@ -247,10 +247,10 @@ public class PythonDistributionAnalyzer extends AbstractFileTypeAnalyzer {
@Override @Override
public void close() { public void close() {
if (tempFileLocation != null && tempFileLocation.exists()) { if (tempFileLocation != null && tempFileLocation.exists()) {
LOGGER.log(Level.FINE, "Attempting to delete temporary files"); LOGGER.debug("Attempting to delete temporary files");
final boolean success = FileUtils.delete(tempFileLocation); final boolean success = FileUtils.delete(tempFileLocation);
if (!success) { if (!success) {
LOGGER.log(Level.WARNING, LOGGER.warn(
"Failed to delete some temporary files, see the log for more details"); "Failed to delete some temporary files, see the log for more details");
} }
} }
@@ -298,7 +298,7 @@ public class PythonDistributionAnalyzer extends AbstractFileTypeAnalyzer {
private static void addPropertyToEvidence(InternetHeaders headers, private static void addPropertyToEvidence(InternetHeaders headers,
EvidenceCollection evidence, String property, Confidence confidence) { EvidenceCollection evidence, String property, Confidence confidence) {
final String value = headers.getHeader(property, null); final String value = headers.getHeader(property, null);
LOGGER.fine(String.format("Property: %s, Value: %s", property, value)); LOGGER.debug("Property: {}, Value: {}", property, value);
if (StringUtils.isNotBlank(value)) { if (StringUtils.isNotBlank(value)) {
evidence.addEvidence(METADATA, property, value, confidence); evidence.addEvidence(METADATA, property, value, confidence);
} }
@@ -329,15 +329,15 @@ public class PythonDistributionAnalyzer extends AbstractFileTypeAnalyzer {
private static InternetHeaders getManifestProperties(File manifest) { private static InternetHeaders getManifestProperties(File manifest) {
final InternetHeaders result = new InternetHeaders(); final InternetHeaders result = new InternetHeaders();
if (null == manifest) { if (null == manifest) {
LOGGER.fine("Manifest file not found."); LOGGER.debug("Manifest file not found.");
} else { } else {
try { try {
result.load(new AutoCloseInputStream(new BufferedInputStream( result.load(new AutoCloseInputStream(new BufferedInputStream(
new FileInputStream(manifest)))); new FileInputStream(manifest))));
} catch (MessagingException e) { } catch (MessagingException e) {
LOGGER.log(Level.WARNING, e.getMessage(), e); LOGGER.warn(e.getMessage(), e);
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
LOGGER.log(Level.WARNING, e.getMessage(), e); LOGGER.warn(e.getMessage(), e);
} }
} }
return result; return result;

View File

@@ -25,7 +25,6 @@ import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import java.util.logging.Logger;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
@@ -39,6 +38,8 @@ import org.owasp.dependencycheck.dependency.Dependency;
import org.owasp.dependencycheck.dependency.EvidenceCollection; import org.owasp.dependencycheck.dependency.EvidenceCollection;
import org.owasp.dependencycheck.utils.Settings; import org.owasp.dependencycheck.utils.Settings;
import org.owasp.dependencycheck.utils.UrlStringUtils; import org.owasp.dependencycheck.utils.UrlStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* Used to analyze a Python package, and collect information that can be used to determine the associated CPE. * Used to analyze a Python package, and collect information that can be used to determine the associated CPE.
@@ -56,8 +57,8 @@ public class PythonPackageAnalyzer extends AbstractFileTypeAnalyzer {
/** /**
* The logger. * The logger.
*/ */
private static final Logger LOGGER = Logger private static final Logger LOGGER = LoggerFactory
.getLogger(PythonPackageAnalyzer.class.getName()); .getLogger(PythonPackageAnalyzer.class);
/** /**
* Filename extensions for files to be analyzed. * Filename extensions for files to be analyzed.
@@ -240,7 +241,7 @@ public class PythonPackageAnalyzer extends AbstractFileTypeAnalyzer {
found |= gatherHomePageEvidence(HOMEPAGE_PATTERN, found |= gatherHomePageEvidence(HOMEPAGE_PATTERN,
vendorEvidence, source, "HomePage", contents); vendorEvidence, source, "HomePage", contents);
} catch (MalformedURLException e) { } catch (MalformedURLException e) {
LOGGER.warning(e.getMessage()); LOGGER.warn(e.getMessage());
} }
} }
return found; return found;

View File

@@ -23,7 +23,6 @@ import java.net.HttpURLConnection;
import java.net.URL; import java.net.URL;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath; import javax.xml.xpath.XPath;
@@ -32,6 +31,8 @@ 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;
import org.owasp.dependencycheck.utils.URLConnectionFactory; import org.owasp.dependencycheck.utils.URLConnectionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document; import org.w3c.dom.Document;
import org.w3c.dom.NodeList; import org.w3c.dom.NodeList;
@@ -55,7 +56,7 @@ public class CentralSearch {
/** /**
* Used for logging. * Used for logging.
*/ */
private static final Logger LOGGER = Logger.getLogger(CentralSearch.class.getName()); private static final Logger LOGGER = LoggerFactory.getLogger(CentralSearch.class);
/** /**
* Creates a NexusSearch for the given repository URL. * Creates a NexusSearch for the given repository URL.
@@ -67,10 +68,10 @@ public class CentralSearch {
this.rootURL = rootURL; this.rootURL = rootURL;
if (null != Settings.getString(Settings.KEYS.PROXY_SERVER)) { if (null != Settings.getString(Settings.KEYS.PROXY_SERVER)) {
useProxy = true; useProxy = true;
LOGGER.fine("Using proxy"); LOGGER.debug("Using proxy");
} else { } else {
useProxy = false; useProxy = false;
LOGGER.fine("Not using proxy"); LOGGER.debug("Not using proxy");
} }
} }
@@ -89,7 +90,7 @@ public class CentralSearch {
final URL url = new URL(rootURL + String.format("?q=1:\"%s\"&wt=xml", sha1)); final URL url = new URL(rootURL + String.format("?q=1:\"%s\"&wt=xml", sha1));
LOGGER.fine(String.format("Searching Central url %s", url.toString())); LOGGER.debug("Searching Central url {}", url.toString());
// Determine if we need to use a proxy. The rules: // Determine if we need to use a proxy. The rules:
// 1) If the proxy is set, AND the setting is set to true, use the proxy // 1) If the proxy is set, AND the setting is set to true, use the proxy
@@ -119,9 +120,9 @@ public class CentralSearch {
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));
LOGGER.finest(String.format("GroupId: %s", g)); LOGGER.trace("GroupId: {}", g);
final String a = xpath.evaluate("./str[@name='a']", docs.item(i)); final String a = xpath.evaluate("./str[@name='a']", docs.item(i));
LOGGER.finest(String.format("ArtifactId: %s", a)); LOGGER.trace("ArtifactId: {}", a);
final String v = xpath.evaluate("./str[@name='v']", docs.item(i)); final String v = xpath.evaluate("./str[@name='v']", docs.item(i));
NodeList atts = (NodeList) xpath.evaluate("./arr[@name='ec']/str", docs.item(i), XPathConstants.NODESET); NodeList atts = (NodeList) xpath.evaluate("./arr[@name='ec']/str", docs.item(i), XPathConstants.NODESET);
boolean pomAvailable = false; boolean pomAvailable = false;
@@ -144,7 +145,7 @@ public class CentralSearch {
} }
} }
LOGGER.finest(String.format("Version: %s", v)); LOGGER.trace("Version: {}", v);
result.add(new MavenArtifact(g, a, v, jarAvailable, pomAvailable, useHTTPS)); result.add(new MavenArtifact(g, a, v, jarAvailable, pomAvailable, useHTTPS));
} }
@@ -160,10 +161,9 @@ public class CentralSearch {
throw new FileNotFoundException("Artifact not found in Central"); throw new FileNotFoundException("Artifact not found in Central");
} }
} else { } else {
final String msg = String.format("Could not connect to Central received response code: %d %s", LOGGER.debug("Could not connect to Central received response code: {} {}",
conn.getResponseCode(), conn.getResponseMessage()); conn.getResponseCode(), conn.getResponseMessage());
LOGGER.fine(msg); throw new IOException("Could not connect to Central");
throw new IOException(msg);
} }
return null; return null;

View File

@@ -21,8 +21,6 @@ import java.io.IOException;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.core.KeywordAnalyzer; import org.apache.lucene.analysis.core.KeywordAnalyzer;
import org.apache.lucene.analysis.miscellaneous.PerFieldAnalyzerWrapper; import org.apache.lucene.analysis.miscellaneous.PerFieldAnalyzerWrapper;
@@ -46,6 +44,8 @@ import org.owasp.dependencycheck.data.lucene.SearchFieldAnalyzer;
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.utils.Pair; import org.owasp.dependencycheck.utils.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* An in memory lucene index that contains the vendor/product combinations from the CPE (application) identifiers within the NVD * An in memory lucene index that contains the vendor/product combinations from the CPE (application) identifiers within the NVD
@@ -58,7 +58,7 @@ public final class CpeMemoryIndex {
/** /**
* The logger. * The logger.
*/ */
private static final Logger LOGGER = Logger.getLogger(CpeMemoryIndex.class.getName()); private static final Logger LOGGER = LoggerFactory.getLogger(CpeMemoryIndex.class);
/** /**
* singleton instance. * singleton instance.
*/ */
@@ -203,7 +203,7 @@ public final class CpeMemoryIndex {
try { try {
indexReader.close(); indexReader.close();
} catch (IOException ex) { } catch (IOException ex) {
LOGGER.log(Level.FINEST, null, ex); LOGGER.trace("", ex);
} }
indexReader = null; indexReader = null;
} }
@@ -235,7 +235,7 @@ public final class CpeMemoryIndex {
saveEntry(pair.getLeft(), pair.getRight(), indexWriter); saveEntry(pair.getLeft(), pair.getRight(), indexWriter);
} }
} catch (DatabaseException ex) { } catch (DatabaseException ex) {
LOGGER.log(Level.FINE, null, ex); LOGGER.debug("", ex);
throw new IndexException("Error reading CPE data", ex); throw new IndexException("Error reading CPE data", ex);
} }
} catch (CorruptIndexException ex) { } catch (CorruptIndexException ex) {

View File

@@ -17,12 +17,13 @@
*/ */
package org.owasp.dependencycheck.data.cwe; package org.owasp.dependencycheck.data.cwe;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.ObjectInputStream; import java.io.ObjectInputStream;
import java.util.HashMap; import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
/** /**
* *
@@ -33,7 +34,7 @@ public final class CweDB {
/** /**
* The Logger. * The Logger.
*/ */
private static final Logger LOGGER = Logger.getLogger(CweDB.class.getName()); private static final Logger LOGGER = LoggerFactory.getLogger(CweDB.class);
/** /**
* Empty private constructor as this is a utility class. * Empty private constructor as this is a utility class.
@@ -61,17 +62,17 @@ public final class CweDB {
final HashMap<String, String> ret = (HashMap<String, String>) oin.readObject(); final HashMap<String, String> ret = (HashMap<String, String>) oin.readObject();
return ret; return ret;
} catch (ClassNotFoundException ex) { } catch (ClassNotFoundException ex) {
LOGGER.log(Level.WARNING, "Unable to load CWE data. This should not be an issue."); LOGGER.warn("Unable to load CWE data. This should not be an issue.");
LOGGER.log(Level.FINE, null, ex); LOGGER.debug("", ex);
} catch (IOException ex) { } catch (IOException ex) {
LOGGER.log(Level.WARNING, "Unable to load CWE data due to an IO Error. This should not be an issue."); LOGGER.warn("Unable to load CWE data due to an IO Error. This should not be an issue.");
LOGGER.log(Level.FINE, null, ex); LOGGER.debug("", ex);
} finally { } finally {
if (oin != null) { if (oin != null) {
try { try {
oin.close(); oin.close();
} catch (IOException ex) { } catch (IOException ex) {
LOGGER.log(Level.FINEST, null, ex); LOGGER.trace("", ex);
} }
} }
} }

View File

@@ -21,11 +21,11 @@ import java.io.IOException;
import java.net.MalformedURLException; import java.net.MalformedURLException;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.lucene.analysis.TokenStream; import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute; import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.owasp.dependencycheck.utils.UrlStringUtils; import org.owasp.dependencycheck.utils.UrlStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* <p> * <p>
@@ -39,7 +39,7 @@ public final class UrlTokenizingFilter extends AbstractTokenizingFilter {
/** /**
* The logger. * The logger.
*/ */
private static final Logger LOGGER = Logger.getLogger(UrlTokenizingFilter.class.getName()); private static final Logger LOGGER = LoggerFactory.getLogger(UrlTokenizingFilter.class);
/** /**
* Constructs a new VersionTokenizingFilter. * Constructs a new VersionTokenizingFilter.
* *
@@ -70,7 +70,7 @@ public final class UrlTokenizingFilter extends AbstractTokenizingFilter {
final List<String> data = UrlStringUtils.extractImportantUrlData(part); final List<String> data = UrlStringUtils.extractImportantUrlData(part);
tokens.addAll(data); tokens.addAll(data);
} catch (MalformedURLException ex) { } catch (MalformedURLException ex) {
LOGGER.log(Level.FINE, "error parsing " + part, ex); LOGGER.debug("error parsing {}", part, ex);
tokens.add(part); tokens.add(part);
} }
} else { } else {

View File

@@ -21,8 +21,6 @@ import java.io.FileNotFoundException;
import java.io.IOException; import java.io.IOException;
import java.net.HttpURLConnection; import java.net.HttpURLConnection;
import java.net.URL; import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath; import javax.xml.xpath.XPath;
@@ -30,6 +28,8 @@ import javax.xml.xpath.XPathFactory;
import org.owasp.dependencycheck.utils.InvalidSettingException; import org.owasp.dependencycheck.utils.InvalidSettingException;
import org.owasp.dependencycheck.utils.Settings; import org.owasp.dependencycheck.utils.Settings;
import org.owasp.dependencycheck.utils.URLConnectionFactory; import org.owasp.dependencycheck.utils.URLConnectionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document; import org.w3c.dom.Document;
/** /**
@@ -59,7 +59,7 @@ public class NexusSearch {
/** /**
* Used for logging. * Used for logging.
*/ */
private static final Logger LOGGER = Logger.getLogger(NexusSearch.class.getName()); private static final Logger LOGGER = LoggerFactory.getLogger(NexusSearch.class);
/** /**
* Creates a NexusSearch for the given repository URL. * Creates a NexusSearch for the given repository URL.
@@ -73,10 +73,10 @@ public class NexusSearch {
if (null != Settings.getString(Settings.KEYS.PROXY_SERVER) if (null != Settings.getString(Settings.KEYS.PROXY_SERVER)
&& Settings.getBoolean(Settings.KEYS.ANALYZER_NEXUS_PROXY)) { && Settings.getBoolean(Settings.KEYS.ANALYZER_NEXUS_PROXY)) {
useProxy = true; useProxy = true;
LOGGER.fine("Using proxy"); LOGGER.debug("Using proxy");
} else { } else {
useProxy = false; useProxy = false;
LOGGER.fine("Not using proxy"); LOGGER.debug("Not using proxy");
} }
} catch (InvalidSettingException ise) { } catch (InvalidSettingException ise) {
useProxy = false; useProxy = false;
@@ -99,7 +99,7 @@ public class NexusSearch {
final URL url = new URL(rootURL, String.format("identify/sha1/%s", final URL url = new URL(rootURL, String.format("identify/sha1/%s",
sha1.toLowerCase())); sha1.toLowerCase()));
LOGGER.fine(String.format("Searching Nexus url %s", url.toString())); LOGGER.debug("Searching Nexus url {}", url);
// Determine if we need to use a proxy. The rules: // Determine if we need to use a proxy. The rules:
// 1) If the proxy is set, AND the setting is set to true, use the proxy // 1) If the proxy is set, AND the setting is set to true, use the proxy
@@ -155,10 +155,9 @@ public class NexusSearch {
} else if (conn.getResponseCode() == 404) { } else if (conn.getResponseCode() == 404) {
throw new FileNotFoundException("Artifact not found in Nexus"); throw new FileNotFoundException("Artifact not found in Nexus");
} else { } else {
final String msg = String.format("Could not connect to Nexus received response code: %d %s", LOGGER.debug("Could not connect to Nexus received response code: {} {}",
conn.getResponseCode(), conn.getResponseMessage()); conn.getResponseCode(), conn.getResponseMessage());
LOGGER.fine(msg); throw new IOException("Could not connect to Nexus");
throw new IOException(msg);
} }
} }
@@ -175,13 +174,13 @@ public class NexusSearch {
conn.addRequestProperty("Accept", "application/xml"); conn.addRequestProperty("Accept", "application/xml");
conn.connect(); conn.connect();
if (conn.getResponseCode() != 200) { if (conn.getResponseCode() != 200) {
LOGGER.log(Level.WARNING, "Expected 200 result from Nexus, got {0}", conn.getResponseCode()); LOGGER.warn("Expected 200 result from Nexus, got {}", conn.getResponseCode());
return false; return false;
} }
final DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); final DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
final Document doc = builder.parse(conn.getInputStream()); final Document doc = builder.parse(conn.getInputStream());
if (!"status".equals(doc.getDocumentElement().getNodeName())) { if (!"status".equals(doc.getDocumentElement().getNodeName())) {
LOGGER.log(Level.WARNING, "Expected root node name of status, got {0}", doc.getDocumentElement().getNodeName()); LOGGER.warn("Expected root node name of status, got {}", doc.getDocumentElement().getNodeName());
return false; return false;
} }
} catch (Throwable e) { } catch (Throwable e) {

View File

@@ -29,10 +29,10 @@ import java.sql.DriverManager;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.sql.Statement; import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.owasp.dependencycheck.utils.DBUtils; import org.owasp.dependencycheck.utils.DBUtils;
import org.owasp.dependencycheck.utils.Settings; import org.owasp.dependencycheck.utils.Settings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* Loads the configured database driver and returns the database connection. If the embedded H2 database is used * Loads the configured database driver and returns the database connection. If the embedded H2 database is used
@@ -46,7 +46,7 @@ public final class ConnectionFactory {
/** /**
* The Logger. * The Logger.
*/ */
private static final Logger LOGGER = Logger.getLogger(ConnectionFactory.class.getName()); private static final Logger LOGGER = LoggerFactory.getLogger(ConnectionFactory.class);
/** /**
* The version of the current DB Schema. * The version of the current DB Schema.
*/ */
@@ -94,17 +94,17 @@ public final class ConnectionFactory {
//load the driver if necessary //load the driver if necessary
final String driverName = Settings.getString(Settings.KEYS.DB_DRIVER_NAME, ""); final String driverName = Settings.getString(Settings.KEYS.DB_DRIVER_NAME, "");
if (!driverName.isEmpty()) { //likely need to load the correct driver if (!driverName.isEmpty()) { //likely need to load the correct driver
LOGGER.log(Level.FINE, "Loading driver: {0}", driverName); LOGGER.debug("Loading driver: {}", driverName);
final String driverPath = Settings.getString(Settings.KEYS.DB_DRIVER_PATH, ""); final String driverPath = Settings.getString(Settings.KEYS.DB_DRIVER_PATH, "");
try { try {
if (!driverPath.isEmpty()) { if (!driverPath.isEmpty()) {
LOGGER.log(Level.FINE, "Loading driver from: {0}", driverPath); LOGGER.debug("Loading driver from: {}", driverPath);
driver = DriverLoader.load(driverName, driverPath); driver = DriverLoader.load(driverName, driverPath);
} else { } else {
driver = DriverLoader.load(driverName); driver = DriverLoader.load(driverName);
} }
} catch (DriverLoadException ex) { } catch (DriverLoadException ex) {
LOGGER.log(Level.FINE, "Unable to load database driver", ex); LOGGER.debug("Unable to load database driver", ex);
throw new DatabaseException("Unable to load database driver"); throw new DatabaseException("Unable to load database driver");
} }
} }
@@ -117,7 +117,7 @@ public final class ConnectionFactory {
Settings.KEYS.DB_FILE_NAME, Settings.KEYS.DB_FILE_NAME,
Settings.KEYS.DB_VERSION); Settings.KEYS.DB_VERSION);
} catch (IOException ex) { } catch (IOException ex) {
LOGGER.log(Level.FINE, LOGGER.debug(
"Unable to retrieve the database connection string", ex); "Unable to retrieve the database connection string", ex);
throw new DatabaseException("Unable to retrieve the database connection string"); throw new DatabaseException("Unable to retrieve the database connection string");
} }
@@ -125,15 +125,15 @@ public final class ConnectionFactory {
try { try {
if (connectionString.startsWith("jdbc:h2:file:")) { //H2 if (connectionString.startsWith("jdbc:h2:file:")) { //H2
shouldCreateSchema = !h2DataFileExists(); shouldCreateSchema = !h2DataFileExists();
LOGGER.log(Level.FINE, "Need to create DB Structure: {0}", shouldCreateSchema); LOGGER.debug("Need to create DB Structure: {}", shouldCreateSchema);
} }
} catch (IOException ioex) { } catch (IOException ioex) {
LOGGER.log(Level.FINE, "Unable to verify database exists", ioex); LOGGER.debug("Unable to verify database exists", ioex);
throw new DatabaseException("Unable to verify database exists"); throw new DatabaseException("Unable to verify database exists");
} }
LOGGER.log(Level.FINE, "Loading database connection"); LOGGER.debug("Loading database connection");
LOGGER.log(Level.FINE, "Connection String: {0}", connectionString); LOGGER.debug("Connection String: {}", connectionString);
LOGGER.log(Level.FINE, "Database User: {0}", userName); LOGGER.debug("Database User: {}", userName);
try { try {
conn = DriverManager.getConnection(connectionString, userName, password); conn = DriverManager.getConnection(connectionString, userName, password);
@@ -143,14 +143,14 @@ public final class ConnectionFactory {
try { try {
conn = DriverManager.getConnection(connectionString, userName, password); conn = DriverManager.getConnection(connectionString, userName, password);
Settings.setString(Settings.KEYS.DB_CONNECTION_STRING, connectionString); Settings.setString(Settings.KEYS.DB_CONNECTION_STRING, connectionString);
LOGGER.log(Level.FINE, LOGGER.debug(
"Unable to start the database in server mode; reverting to single user mode"); "Unable to start the database in server mode; reverting to single user mode");
} catch (SQLException sqlex) { } catch (SQLException sqlex) {
LOGGER.log(Level.FINE, "Unable to connect to the database", ex); LOGGER.debug("Unable to connect to the database", ex);
throw new DatabaseException("Unable to connect to the database"); throw new DatabaseException("Unable to connect to the database");
} }
} else { } else {
LOGGER.log(Level.FINE, "Unable to connect to the database", ex); LOGGER.debug("Unable to connect to the database", ex);
throw new DatabaseException("Unable to connect to the database"); throw new DatabaseException("Unable to connect to the database");
} }
} }
@@ -159,14 +159,14 @@ public final class ConnectionFactory {
try { try {
createTables(conn); createTables(conn);
} catch (DatabaseException dex) { } catch (DatabaseException dex) {
LOGGER.log(Level.FINE, null, dex); LOGGER.debug("", dex);
throw new DatabaseException("Unable to create the database structure"); throw new DatabaseException("Unable to create the database structure");
} }
} else { } else {
try { try {
ensureSchemaVersion(conn); ensureSchemaVersion(conn);
} catch (DatabaseException dex) { } catch (DatabaseException dex) {
LOGGER.log(Level.FINE, null, dex); LOGGER.debug("", dex);
throw new DatabaseException("Database schema does not match this version of dependency-check"); throw new DatabaseException("Database schema does not match this version of dependency-check");
} }
} }
@@ -175,7 +175,7 @@ public final class ConnectionFactory {
try { try {
conn.close(); conn.close();
} catch (SQLException ex) { } catch (SQLException ex) {
LOGGER.log(Level.FINE, "An error occurred closing the connection", ex); LOGGER.debug("An error occurred closing the connection", ex);
} }
} }
} }
@@ -191,9 +191,9 @@ public final class ConnectionFactory {
try { try {
DriverManager.deregisterDriver(driver); DriverManager.deregisterDriver(driver);
} catch (SQLException ex) { } catch (SQLException ex) {
LOGGER.log(Level.FINE, "An error occurred unloading the database driver", ex); LOGGER.debug("An error occurred unloading the database driver", ex);
} catch (Throwable unexpected) { } catch (Throwable unexpected) {
LOGGER.log(Level.FINE, LOGGER.debug(
"An unexpected throwable occurred unloading the database driver", unexpected); "An unexpected throwable occurred unloading the database driver", unexpected);
} }
driver = null; driver = null;
@@ -215,7 +215,7 @@ public final class ConnectionFactory {
try { try {
conn = DriverManager.getConnection(connectionString, userName, password); conn = DriverManager.getConnection(connectionString, userName, password);
} catch (SQLException ex) { } catch (SQLException ex) {
LOGGER.log(Level.FINE, null, ex); LOGGER.debug("", ex);
throw new DatabaseException("Unable to connect to the database"); throw new DatabaseException("Unable to connect to the database");
} }
return conn; return conn;
@@ -242,7 +242,7 @@ public final class ConnectionFactory {
* @throws DatabaseException thrown if there is a Database Exception * @throws DatabaseException thrown if there is a Database Exception
*/ */
private static void createTables(Connection conn) throws DatabaseException { private static void createTables(Connection conn) throws DatabaseException {
LOGGER.log(Level.FINE, "Creating database structure"); LOGGER.debug("Creating database structure");
InputStream is; InputStream is;
InputStreamReader reader; InputStreamReader reader;
BufferedReader in = null; BufferedReader in = null;
@@ -260,7 +260,7 @@ public final class ConnectionFactory {
statement = conn.createStatement(); statement = conn.createStatement();
statement.execute(sb.toString()); statement.execute(sb.toString());
} catch (SQLException ex) { } catch (SQLException ex) {
LOGGER.log(Level.FINE, null, ex); LOGGER.debug("", ex);
throw new DatabaseException("Unable to create database statement", ex); throw new DatabaseException("Unable to create database statement", ex);
} finally { } finally {
DBUtils.closeStatement(statement); DBUtils.closeStatement(statement);
@@ -272,7 +272,7 @@ public final class ConnectionFactory {
try { try {
in.close(); in.close();
} catch (IOException ex) { } catch (IOException ex) {
LOGGER.log(Level.FINEST, null, ex); LOGGER.trace("", ex);
} }
} }
} }
@@ -299,7 +299,7 @@ public final class ConnectionFactory {
throw new DatabaseException("Database schema is missing"); throw new DatabaseException("Database schema is missing");
} }
} catch (SQLException ex) { } catch (SQLException ex) {
LOGGER.log(Level.FINE, null, ex); LOGGER.debug("", ex);
throw new DatabaseException("Unable to check the database schema version"); throw new DatabaseException("Unable to check the database schema version");
} finally { } finally {
DBUtils.closeResultSet(rs); DBUtils.closeResultSet(rs);

View File

@@ -33,8 +33,6 @@ import java.util.Map.Entry;
import java.util.Properties; import java.util.Properties;
import java.util.ResourceBundle; import java.util.ResourceBundle;
import java.util.Set; import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.owasp.dependencycheck.data.cwe.CweDB; import org.owasp.dependencycheck.data.cwe.CweDB;
import org.owasp.dependencycheck.dependency.Reference; import org.owasp.dependencycheck.dependency.Reference;
import org.owasp.dependencycheck.dependency.Vulnerability; import org.owasp.dependencycheck.dependency.Vulnerability;
@@ -44,6 +42,8 @@ import org.owasp.dependencycheck.utils.DependencyVersion;
import org.owasp.dependencycheck.utils.DependencyVersionUtil; import org.owasp.dependencycheck.utils.DependencyVersionUtil;
import org.owasp.dependencycheck.utils.Pair; import org.owasp.dependencycheck.utils.Pair;
import org.owasp.dependencycheck.utils.Settings; import org.owasp.dependencycheck.utils.Settings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* The database holding information about the NVD CVE data. * The database holding information about the NVD CVE data.
@@ -55,7 +55,7 @@ public class CveDB {
/** /**
* The logger. * The logger.
*/ */
private static final Logger LOGGER = Logger.getLogger(CveDB.class.getName()); private static final Logger LOGGER = LoggerFactory.getLogger(CveDB.class);
/** /**
* Database connection * Database connection
*/ */
@@ -110,13 +110,11 @@ public class CveDB {
try { try {
conn.close(); conn.close();
} catch (SQLException ex) { } catch (SQLException ex) {
final String msg = "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.log(Level.SEVERE, msg); LOGGER.debug("", ex);
LOGGER.log(Level.FINE, null, ex);
} catch (Throwable ex) { } catch (Throwable ex) {
final String msg = "There was an exception attempting to close the CveDB, see the log for more details."; LOGGER.error("There was an exception attempting to close the CveDB, see the log for more details.");
LOGGER.log(Level.SEVERE, msg); LOGGER.debug("", ex);
LOGGER.log(Level.FINE, null, ex);
} }
conn = null; conn = null;
} }
@@ -151,7 +149,7 @@ public class CveDB {
@Override @Override
@SuppressWarnings("FinalizeDeclaration") @SuppressWarnings("FinalizeDeclaration")
protected void finalize() throws Throwable { protected void finalize() throws Throwable {
LOGGER.log(Level.FINE, "Entering finalize"); LOGGER.debug("Entering finalize");
close(); close();
super.finalize(); super.finalize();
} }
@@ -193,9 +191,8 @@ public class CveDB {
cpe.add(vs); cpe.add(vs);
} }
} catch (SQLException ex) { } catch (SQLException ex) {
final String msg = "An unexpected SQL Exception occurred; please see the verbose log for more details."; LOGGER.error("An unexpected SQL Exception occurred; please see the verbose log for more details.");
LOGGER.log(Level.SEVERE, msg); LOGGER.debug("", ex);
LOGGER.log(Level.FINE, null, ex);
} finally { } finally {
DBUtils.closeResultSet(rs); DBUtils.closeResultSet(rs);
DBUtils.closeStatement(ps); DBUtils.closeStatement(ps);
@@ -245,9 +242,8 @@ public class CveDB {
prop.setProperty(rs.getString(1), rs.getString(2)); prop.setProperty(rs.getString(1), rs.getString(2));
} }
} catch (SQLException ex) { } catch (SQLException ex) {
final String msg = "An unexpected SQL Exception occurred; please see the verbose log for more details."; LOGGER.error("An unexpected SQL Exception occurred; please see the verbose log for more details.");
LOGGER.log(Level.SEVERE, msg); LOGGER.debug("", ex);
LOGGER.log(Level.FINE, null, ex);
} finally { } finally {
DBUtils.closeStatement(ps); DBUtils.closeStatement(ps);
DBUtils.closeResultSet(rs); DBUtils.closeResultSet(rs);
@@ -268,8 +264,8 @@ public class CveDB {
updateProperty = getConnection().prepareStatement(statementBundle.getString("UPDATE_PROPERTY")); updateProperty = getConnection().prepareStatement(statementBundle.getString("UPDATE_PROPERTY"));
insertProperty = getConnection().prepareStatement(statementBundle.getString("INSERT_PROPERTY")); insertProperty = getConnection().prepareStatement(statementBundle.getString("INSERT_PROPERTY"));
} catch (SQLException ex) { } catch (SQLException ex) {
LOGGER.log(Level.WARNING, "Unable to save properties to the database"); LOGGER.warn("Unable to save properties to the database");
LOGGER.log(Level.FINE, "Unable to save properties to the database", ex); LOGGER.debug("Unable to save properties to the database", ex);
return; return;
} }
for (Entry<Object, Object> entry : props.entrySet()) { for (Entry<Object, Object> entry : props.entrySet()) {
@@ -283,9 +279,8 @@ public class CveDB {
insertProperty.setString(2, value); insertProperty.setString(2, value);
} }
} catch (SQLException ex) { } catch (SQLException ex) {
final String msg = String.format("Unable to save property '%s' with a value of '%s' to the database", key, value); LOGGER.warn("Unable to save property '{}' with a value of '{}' to the database", key, value);
LOGGER.log(Level.WARNING, msg); LOGGER.debug("", ex);
LOGGER.log(Level.FINE, null, ex);
} }
} }
} finally { } finally {
@@ -307,8 +302,8 @@ public class CveDB {
try { try {
updateProperty = getConnection().prepareStatement(statementBundle.getString("UPDATE_PROPERTY")); updateProperty = getConnection().prepareStatement(statementBundle.getString("UPDATE_PROPERTY"));
} catch (SQLException ex) { } catch (SQLException ex) {
LOGGER.log(Level.WARNING, "Unable to save properties to the database"); LOGGER.warn("Unable to save properties to the database");
LOGGER.log(Level.FINE, "Unable to save properties to the database", ex); LOGGER.debug("Unable to save properties to the database", ex);
return; return;
} }
try { try {
@@ -318,8 +313,8 @@ public class CveDB {
try { try {
insertProperty = getConnection().prepareStatement(statementBundle.getString("INSERT_PROPERTY")); insertProperty = getConnection().prepareStatement(statementBundle.getString("INSERT_PROPERTY"));
} catch (SQLException ex) { } catch (SQLException ex) {
LOGGER.log(Level.WARNING, "Unable to save properties to the database"); LOGGER.warn("Unable to save properties to the database");
LOGGER.log(Level.FINE, "Unable to save properties to the database", ex); LOGGER.debug("Unable to save properties to the database", ex);
return; return;
} }
insertProperty.setString(1, key); insertProperty.setString(1, key);
@@ -327,9 +322,8 @@ public class CveDB {
insertProperty.execute(); insertProperty.execute();
} }
} catch (SQLException ex) { } catch (SQLException ex) {
final String msg = String.format("Unable to save property '%s' with a value of '%s' to the database", key, value); LOGGER.warn("Unable to save property '{}' with a value of '{}' to the database", key, value);
LOGGER.log(Level.WARNING, msg); LOGGER.debug("", ex);
LOGGER.log(Level.FINE, null, ex);
} }
} finally { } finally {
DBUtils.closeStatement(updateProperty); DBUtils.closeStatement(updateProperty);
@@ -350,7 +344,7 @@ public class CveDB {
try { try {
cpe.parseName(cpeStr); cpe.parseName(cpeStr);
} catch (UnsupportedEncodingException ex) { } catch (UnsupportedEncodingException ex) {
LOGGER.log(Level.FINEST, null, ex); LOGGER.trace("", ex);
} }
final DependencyVersion detectedVersion = parseDependencyVersion(cpe); final DependencyVersion detectedVersion = parseDependencyVersion(cpe);
final List<Vulnerability> vulnerabilities = new ArrayList<Vulnerability>(); final List<Vulnerability> vulnerabilities = new ArrayList<Vulnerability>();
@@ -601,7 +595,7 @@ public class CveDB {
} 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());
LOGGER.log(Level.FINE, null, ex); LOGGER.debug("", ex);
throw new DatabaseException(msg, ex); throw new DatabaseException(msg, ex);
} finally { } finally {
DBUtils.closeStatement(selectVulnerabilityId); DBUtils.closeStatement(selectVulnerabilityId);
@@ -640,13 +634,12 @@ public class CveDB {
} catch (IOException ex1) { } catch (IOException ex1) {
dd = Settings.getString(Settings.KEYS.DATA_DIRECTORY); dd = Settings.getString(Settings.KEYS.DATA_DIRECTORY);
} }
final String msg = String.format("Unable to access the local database.%n%nEnsure that '%s' is a writable directory. " LOGGER.error("Unable to access the local database.\n\nEnsure that '{}' is a writable directory. "
+ "If the problem persist try deleting the files in '%s' and running %s again. If the problem continues, please " + "If the problem persist try deleting the files in '{}' and running {} again. If the problem continues, please "
+ "create a log file (see documentation at http://jeremylong.github.io/DependencyCheck/) and open a ticket at " + "create a log file (see documentation at http://jeremylong.github.io/DependencyCheck/) and open a ticket at "
+ "https://github.com/jeremylong/DependencyCheck/issues and include the log file.%n%n", + "https://github.com/jeremylong/DependencyCheck/issues and include the log file.\n\n",
dd, dd, Settings.getString(Settings.KEYS.APPLICATION_VAME)); dd, dd, Settings.getString(Settings.KEYS.APPLICATION_VAME));
LOGGER.log(Level.SEVERE, msg); LOGGER.debug("", ex);
LOGGER.log(Level.FINE, "", ex);
} finally { } finally {
DBUtils.closeResultSet(rs); DBUtils.closeResultSet(rs);
DBUtils.closeStatement(cs); DBUtils.closeStatement(cs);
@@ -666,9 +659,8 @@ public class CveDB {
ps.executeUpdate(); ps.executeUpdate();
} }
} catch (SQLException ex) { } catch (SQLException ex) {
final String msg = "An unexpected SQL Exception occurred; please see the verbose log for more details."; LOGGER.error("An unexpected SQL Exception occurred; please see the verbose log for more details.");
LOGGER.log(Level.SEVERE, msg); LOGGER.debug("", ex);
LOGGER.log(Level.FINE, null, ex);
} finally { } finally {
DBUtils.closeStatement(ps); DBUtils.closeStatement(ps);
} }
@@ -759,7 +751,7 @@ public class CveDB {
cpe.parseName(cpeStr); cpe.parseName(cpeStr);
} catch (UnsupportedEncodingException ex) { } catch (UnsupportedEncodingException ex) {
//never going to happen. //never going to happen.
LOGGER.log(Level.FINEST, null, ex); LOGGER.trace("", ex);
} }
return parseDependencyVersion(cpe); return parseDependencyVersion(cpe);
} }

View File

@@ -24,10 +24,10 @@ import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.Properties; import java.util.Properties;
import java.util.TreeMap; import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.owasp.dependencycheck.data.update.NvdCveInfo; import org.owasp.dependencycheck.data.update.NvdCveInfo;
import org.owasp.dependencycheck.data.update.exception.UpdateException; import org.owasp.dependencycheck.data.update.exception.UpdateException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* This is a wrapper around a set of properties that are stored in the database. * This is a wrapper around a set of properties that are stored in the database.
@@ -39,7 +39,7 @@ public class DatabaseProperties {
/** /**
* The Logger. * The Logger.
*/ */
private static final Logger LOGGER = Logger.getLogger(DatabaseProperties.class.getName()); private static final Logger LOGGER = LoggerFactory.getLogger(DatabaseProperties.class);
/** /**
* Modified key word, used as a key to store information about the modified file (i.e. the containing the last 8 * Modified key word, used as a key to store information about the modified file (i.e. the containing the last 8
* days of updates).. * days of updates)..
@@ -166,7 +166,7 @@ public class DatabaseProperties {
final String formatted = format.format(date); final String formatted = format.format(date);
map.put(key, formatted); map.put(key, formatted);
} catch (Throwable ex) { //deliberately being broad in this catch clause } catch (Throwable ex) { //deliberately being broad in this catch clause
LOGGER.log(Level.FINE, "Unable to parse timestamp from DB", ex); LOGGER.debug("Unable to parse timestamp from DB", ex);
map.put(key, (String) entry.getValue()); map.put(key, (String) entry.getValue());
} }
} else { } else {

View File

@@ -17,6 +17,9 @@
*/ */
package org.owasp.dependencycheck.data.nvdcve; package org.owasp.dependencycheck.data.nvdcve;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File; import java.io.File;
import java.net.MalformedURLException; import java.net.MalformedURLException;
import java.net.URL; import java.net.URL;
@@ -28,8 +31,6 @@ import java.sql.DriverManager;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/** /**
* DriverLoader is a utility class that is used to load database drivers. * DriverLoader is a utility class that is used to load database drivers.
@@ -41,7 +42,7 @@ public final class DriverLoader {
/** /**
* The logger. * The logger.
*/ */
private static final Logger LOGGER = Logger.getLogger(DriverLoader.class.getName()); private static final Logger LOGGER = LoggerFactory.getLogger(DriverLoader.class);
/** /**
* Private constructor for a utility class. * Private constructor for a utility class.
@@ -87,20 +88,18 @@ public final class DriverLoader {
try { try {
urls.add(f.toURI().toURL()); urls.add(f.toURI().toURL());
} catch (MalformedURLException ex) { } catch (MalformedURLException ex) {
final String msg = String.format("Unable to load database driver '%s'; invalid path provided '%s'", LOGGER.debug("Unable to load database driver '{}'; invalid path provided '{}'",
className, f.getAbsoluteFile()); className, f.getAbsoluteFile(), ex);
LOGGER.log(Level.FINE, msg, ex); throw new DriverLoadException("Unable to load database driver. Invalid path provided", ex);
throw new DriverLoadException(msg, ex);
} }
} }
} else if (file.exists()) { } else if (file.exists()) {
try { try {
urls.add(file.toURI().toURL()); urls.add(file.toURI().toURL());
} catch (MalformedURLException ex) { } catch (MalformedURLException ex) {
final String msg = String.format("Unable to load database driver '%s'; invalid path provided '%s'", LOGGER.debug("Unable to load database driver '{}'; invalid path provided '{}'",
className, file.getAbsoluteFile()); className, file.getAbsoluteFile(), ex);
LOGGER.log(Level.FINE, msg, ex); throw new DriverLoadException("Unable to load database driver. Invalid path provided", ex);
throw new DriverLoadException(msg, ex);
} }
} }
} }
@@ -133,19 +132,19 @@ public final class DriverLoader {
return shim; return shim;
} catch (ClassNotFoundException ex) { } catch (ClassNotFoundException 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.log(Level.FINE, msg, ex); LOGGER.debug(msg, ex);
throw new DriverLoadException(msg, ex); throw new DriverLoadException(msg, ex);
} catch (InstantiationException ex) { } catch (InstantiationException 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.log(Level.FINE, msg, ex); LOGGER.debug(msg, ex);
throw new DriverLoadException(msg, ex); throw new DriverLoadException(msg, ex);
} catch (IllegalAccessException ex) { } catch (IllegalAccessException 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.log(Level.FINE, msg, ex); LOGGER.debug(msg, ex);
throw new DriverLoadException(msg, ex); throw new DriverLoadException(msg, ex);
} catch (SQLException 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.log(Level.FINE, msg, ex); LOGGER.debug(msg, ex);
throw new DriverLoadException(msg, ex); throw new DriverLoadException(msg, ex);
} }
} }

View File

@@ -17,6 +17,9 @@
*/ */
package org.owasp.dependencycheck.data.nvdcve; package org.owasp.dependencycheck.data.nvdcve;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.sql.Connection; import java.sql.Connection;
@@ -25,8 +28,6 @@ import java.sql.DriverPropertyInfo;
import java.sql.SQLException; import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException; import java.sql.SQLFeatureNotSupportedException;
import java.util.Properties; import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
/** /**
* <p> * <p>
@@ -42,7 +43,7 @@ class DriverShim implements Driver {
/** /**
* The logger. * The logger.
*/ */
private static final Logger LOGGER = Logger.getLogger(DriverShim.class.getName()); private static final Logger LOGGER = LoggerFactory.getLogger(DriverShim.class);
/** /**
* The database driver being wrapped. * The database driver being wrapped.
*/ */
@@ -115,7 +116,7 @@ class DriverShim implements Driver {
* @see java.sql.Driver#getParentLogger() * @see java.sql.Driver#getParentLogger()
*/ */
//@Override //@Override
public Logger getParentLogger() throws SQLFeatureNotSupportedException { public java.util.logging.Logger getParentLogger() throws SQLFeatureNotSupportedException {
//return driver.getParentLogger(); //return driver.getParentLogger();
Method m = null; Method m = null;
try { try {
@@ -125,13 +126,13 @@ class DriverShim implements Driver {
} }
if (m != null) { if (m != null) {
try { try {
return (Logger) m.invoke(m); return (java.util.logging.Logger) m.invoke(m);
} catch (IllegalAccessException ex) { } catch (IllegalAccessException ex) {
LOGGER.log(Level.FINER, null, ex); LOGGER.trace("", ex);
} catch (IllegalArgumentException ex) { } catch (IllegalArgumentException ex) {
LOGGER.log(Level.FINER, null, ex); LOGGER.trace("", ex);
} catch (InvocationTargetException ex) { } catch (InvocationTargetException ex) {
LOGGER.log(Level.FINER, null, ex); LOGGER.trace("", ex);
} }
} }
throw new SQLFeatureNotSupportedException(); throw new SQLFeatureNotSupportedException();

View File

@@ -22,8 +22,6 @@ import java.net.HttpURLConnection;
import java.net.MalformedURLException; import java.net.MalformedURLException;
import java.net.URL; import java.net.URL;
import java.util.Date; import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;
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;
@@ -34,6 +32,8 @@ import org.owasp.dependencycheck.utils.DependencyVersion;
import org.owasp.dependencycheck.utils.Settings; import org.owasp.dependencycheck.utils.Settings;
import org.owasp.dependencycheck.utils.URLConnectionFactory; import org.owasp.dependencycheck.utils.URLConnectionFactory;
import org.owasp.dependencycheck.utils.URLConnectionFailureException; import org.owasp.dependencycheck.utils.URLConnectionFailureException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* *
@@ -44,7 +44,7 @@ public class EngineVersionCheck implements CachedWebDataSource {
/** /**
* Static logger. * Static logger.
*/ */
private static final Logger LOGGER = Logger.getLogger(EngineVersionCheck.class.getName()); private static final Logger LOGGER = LoggerFactory.getLogger(EngineVersionCheck.class);
/** /**
* The property key indicating when the last version check occurred. * The property key indicating when the last version check occurred.
*/ */
@@ -85,23 +85,22 @@ public class EngineVersionCheck implements CachedWebDataSource {
public void update() throws UpdateException { public void update() throws UpdateException {
try { try {
openDatabase(); openDatabase();
LOGGER.fine("Begin Engine Version Check"); LOGGER.debug("Begin Engine Version Check");
final DatabaseProperties properties = cveDB.getDatabaseProperties(); final DatabaseProperties properties = cveDB.getDatabaseProperties();
final long lastChecked = Long.parseLong(properties.getProperty(ENGINE_VERSION_CHECKED_ON, "0")); final long lastChecked = Long.parseLong(properties.getProperty(ENGINE_VERSION_CHECKED_ON, "0"));
final long now = (new Date()).getTime(); final long now = (new Date()).getTime();
updateToVersion = properties.getProperty(CURRENT_ENGINE_RELEASE, ""); updateToVersion = properties.getProperty(CURRENT_ENGINE_RELEASE, "");
final String currentVersion = Settings.getString(Settings.KEYS.APPLICATION_VERSION, "0.0.0"); final String currentVersion = Settings.getString(Settings.KEYS.APPLICATION_VERSION, "0.0.0");
LOGGER.fine("Last checked: " + lastChecked); LOGGER.debug("Last checked: {}", lastChecked);
LOGGER.fine("Now: " + now); LOGGER.debug("Now: {}", now);
LOGGER.fine("Current version: " + currentVersion); LOGGER.debug("Current version: {}", currentVersion);
final boolean updateNeeded = shouldUpdate(lastChecked, now, properties, currentVersion); final boolean updateNeeded = shouldUpdate(lastChecked, now, properties, currentVersion);
if (updateNeeded) { if (updateNeeded) {
final String msg = String.format("A new version of dependency-check is available. Consider updating to version %s.", LOGGER.warn("A new version of dependency-check is available. Consider updating to version {}.",
updateToVersion); updateToVersion);
LOGGER.warning(msg);
} }
} catch (DatabaseException ex) { } catch (DatabaseException ex) {
LOGGER.log(Level.FINE, "Database Exception opening databases to retrieve properties", ex); LOGGER.debug("Database Exception opening databases to retrieve properties", ex);
throw new UpdateException("Error occured updating database properties."); throw new UpdateException("Error occured updating database properties.");
} finally { } finally {
closeDatabase(); closeDatabase();
@@ -127,7 +126,7 @@ public class EngineVersionCheck implements CachedWebDataSource {
checkRange = 7; checkRange = 7;
} }
if (!DateUtil.withinDateRange(lastChecked, now, checkRange)) { if (!DateUtil.withinDateRange(lastChecked, now, checkRange)) {
LOGGER.fine("Checking web for new version."); LOGGER.debug("Checking web for new version.");
final String currentRelease = getCurrentReleaseVersion(); final String currentRelease = getCurrentReleaseVersion();
if (currentRelease != null) { if (currentRelease != null) {
final DependencyVersion v = new DependencyVersion(currentRelease); final DependencyVersion v = new DependencyVersion(currentRelease);
@@ -141,15 +140,15 @@ public class EngineVersionCheck implements CachedWebDataSource {
properties.save(ENGINE_VERSION_CHECKED_ON, Long.toString(now)); properties.save(ENGINE_VERSION_CHECKED_ON, Long.toString(now));
} }
} }
LOGGER.log(Level.FINE, "Current Release: {0}", updateToVersion); LOGGER.debug("Current Release: {}", updateToVersion);
} }
final DependencyVersion running = new DependencyVersion(currentVersion); final DependencyVersion running = new DependencyVersion(currentVersion);
final DependencyVersion released = new DependencyVersion(updateToVersion); final DependencyVersion released = new DependencyVersion(updateToVersion);
if (running.compareTo(released) < 0) { if (running.compareTo(released) < 0) {
LOGGER.fine("Upgrade recommended"); LOGGER.debug("Upgrade recommended");
return true; return true;
} }
LOGGER.fine("Upgrade not needed"); LOGGER.debug("Upgrade not needed");
return false; return false;
} }
@@ -174,7 +173,7 @@ public class EngineVersionCheck implements CachedWebDataSource {
try { try {
cveDB.close(); cveDB.close();
} catch (Throwable ignore) { } catch (Throwable ignore) {
LOGGER.log(Level.FINEST, "Error closing the cveDB", ignore); LOGGER.trace("Error closing the cveDB", ignore);
} }
} }
} }
@@ -199,11 +198,11 @@ public class EngineVersionCheck implements CachedWebDataSource {
return releaseVersion.trim(); return releaseVersion.trim();
} }
} catch (MalformedURLException ex) { } catch (MalformedURLException ex) {
LOGGER.log(Level.FINE, "unable to retrieve current release version of dependency-check", ex); LOGGER.debug("unable to retrieve current release version of dependency-check", ex);
} catch (URLConnectionFailureException ex) { } catch (URLConnectionFailureException ex) {
LOGGER.log(Level.FINE, "unable to retrieve current release version of dependency-check", ex); LOGGER.debug("unable to retrieve current release version of dependency-check", ex);
} catch (IOException ex) { } catch (IOException ex) {
LOGGER.log(Level.FINE, "unable to retrieve current release version of dependency-check", ex); LOGGER.debug("unable to retrieve current release version of dependency-check", ex);
} finally { } finally {
if (conn != null) { if (conn != null) {
conn.disconnect(); conn.disconnect();

View File

@@ -18,11 +18,11 @@
package org.owasp.dependencycheck.data.update; package org.owasp.dependencycheck.data.update;
import java.net.MalformedURLException; import java.net.MalformedURLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.owasp.dependencycheck.data.update.exception.UpdateException; import org.owasp.dependencycheck.data.update.exception.UpdateException;
import org.owasp.dependencycheck.utils.DownloadFailedException; import org.owasp.dependencycheck.utils.DownloadFailedException;
import org.owasp.dependencycheck.utils.Settings; import org.owasp.dependencycheck.utils.Settings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* Class responsible for updating the NVD CVE and CPE data stores. * Class responsible for updating the NVD CVE and CPE data stores.
@@ -34,7 +34,7 @@ public class NvdCveUpdater implements CachedWebDataSource {
/** /**
* The logger * The logger
*/ */
private static final Logger LOGGER = Logger.getLogger(NvdCveUpdater.class.getName()); private static final Logger LOGGER = LoggerFactory.getLogger(NvdCveUpdater.class);
/** /**
* <p> * <p>
@@ -50,17 +50,17 @@ public class NvdCveUpdater implements CachedWebDataSource {
task.update(); task.update();
} }
} catch (MalformedURLException ex) { } catch (MalformedURLException ex) {
LOGGER.log(Level.WARNING, LOGGER.warn(
"NVD CVE properties files contain an invalid URL, unable to update the data to use the most current data."); "NVD CVE properties files contain an invalid URL, unable to update the data to use the most current data.");
LOGGER.log(Level.FINE, null, ex); LOGGER.debug("", ex);
} catch (DownloadFailedException ex) { } catch (DownloadFailedException ex) {
LOGGER.log(Level.WARNING, LOGGER.warn(
"Unable to download the NVD CVE data; the results may not include the most recent CPE/CVEs from the NVD."); "Unable to download the NVD CVE data; the results may not include the most recent CPE/CVEs from the NVD.");
if (Settings.getString(Settings.KEYS.PROXY_SERVER) == null) { if (Settings.getString(Settings.KEYS.PROXY_SERVER) == null) {
LOGGER.log(Level.INFO, LOGGER.info(
"If you are behind a proxy you may need to configure dependency-check to use the proxy."); "If you are behind a proxy you may need to configure dependency-check to use the proxy.");
} }
LOGGER.log(Level.FINE, null, ex); LOGGER.debug("", ex);
} }
} }
} }

View File

@@ -26,8 +26,6 @@ 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.logging.Level;
import java.util.logging.Logger;
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;
@@ -40,6 +38,8 @@ import org.owasp.dependencycheck.utils.DateUtil;
import org.owasp.dependencycheck.utils.DownloadFailedException; import org.owasp.dependencycheck.utils.DownloadFailedException;
import org.owasp.dependencycheck.utils.InvalidSettingException; import org.owasp.dependencycheck.utils.InvalidSettingException;
import org.owasp.dependencycheck.utils.Settings; import org.owasp.dependencycheck.utils.Settings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* Class responsible for updating the NVDCVE data store. * Class responsible for updating the NVDCVE data store.
@@ -51,7 +51,7 @@ public class StandardUpdate {
/** /**
* Static logger. * Static logger.
*/ */
private static final Logger LOGGER = Logger.getLogger(StandardUpdate.class.getName()); private static final Logger LOGGER = LoggerFactory.getLogger(StandardUpdate.class);
/** /**
* The max thread pool size to use when downloading files. * The max thread pool size to use when downloading files.
*/ */
@@ -109,7 +109,7 @@ public class StandardUpdate {
return; return;
} }
if (maxUpdates > 3) { if (maxUpdates > 3) {
LOGGER.log(Level.INFO, LOGGER.info(
"NVD CVE requires several updates; this could take a couple of minutes."); "NVD CVE requires several updates; this could take a couple of minutes.");
} }
if (maxUpdates > 0) { if (maxUpdates > 0) {
@@ -139,19 +139,19 @@ public class StandardUpdate {
downloadExecutors.shutdownNow(); downloadExecutors.shutdownNow();
processExecutor.shutdownNow(); processExecutor.shutdownNow();
LOGGER.log(Level.FINE, "Thread was interrupted during download", ex); LOGGER.debug("Thread was interrupted during download", ex);
throw new UpdateException("The download was interrupted", ex); throw new UpdateException("The download was interrupted", ex);
} catch (ExecutionException ex) { } catch (ExecutionException ex) {
downloadExecutors.shutdownNow(); downloadExecutors.shutdownNow();
processExecutor.shutdownNow(); processExecutor.shutdownNow();
LOGGER.log(Level.FINE, "Thread was interrupted during download execution", ex); LOGGER.debug("Thread was interrupted during download execution", ex);
throw new UpdateException("The execution of the download was interrupted", ex); throw new UpdateException("The execution of the download was interrupted", ex);
} }
if (task == null) { if (task == null) {
downloadExecutors.shutdownNow(); downloadExecutors.shutdownNow();
processExecutor.shutdownNow(); processExecutor.shutdownNow();
LOGGER.log(Level.FINE, "Thread was interrupted during download"); LOGGER.debug("Thread was interrupted during download");
throw new UpdateException("The download was interrupted; unable to complete the update"); throw new UpdateException("The download was interrupted; unable to complete the update");
} else { } else {
processFutures.add(task); processFutures.add(task);
@@ -166,11 +166,11 @@ public class StandardUpdate {
} }
} catch (InterruptedException ex) { } catch (InterruptedException ex) {
processExecutor.shutdownNow(); processExecutor.shutdownNow();
LOGGER.log(Level.FINE, "Thread was interrupted during processing", ex); LOGGER.debug("Thread was interrupted during processing", ex);
throw new UpdateException(ex); throw new UpdateException(ex);
} catch (ExecutionException ex) { } catch (ExecutionException ex) {
processExecutor.shutdownNow(); processExecutor.shutdownNow();
LOGGER.log(Level.FINE, "Execution Exception during process", ex); LOGGER.debug("Execution Exception during process", ex);
throw new UpdateException(ex); throw new UpdateException(ex);
} finally { } finally {
processExecutor.shutdown(); processExecutor.shutdown();
@@ -179,9 +179,9 @@ public class StandardUpdate {
if (maxUpdates >= 1) { //ensure the modified file date gets written (we may not have actually updated it) if (maxUpdates >= 1) { //ensure the modified file date gets written (we may not have actually updated it)
properties.save(updateable.get(MODIFIED)); properties.save(updateable.get(MODIFIED));
LOGGER.log(Level.INFO, "Begin database maintenance."); LOGGER.info("Begin database maintenance.");
cveDB.cleanupDatabase(); cveDB.cleanupDatabase();
LOGGER.log(Level.INFO, "End database maintenance."); LOGGER.info("End database maintenance.");
} }
} finally { } finally {
closeDataStores(); closeDataStores();
@@ -204,10 +204,10 @@ public class StandardUpdate {
updates = retrieveCurrentTimestampsFromWeb(); updates = retrieveCurrentTimestampsFromWeb();
} catch (InvalidDataException ex) { } catch (InvalidDataException ex) {
final String msg = "Unable to retrieve valid timestamp from nvd cve downloads page"; final String msg = "Unable to retrieve valid timestamp from nvd cve downloads page";
LOGGER.log(Level.FINE, msg, ex); LOGGER.debug(msg, ex);
throw new DownloadFailedException(msg, ex); throw new DownloadFailedException(msg, ex);
} catch (InvalidSettingException ex) { } catch (InvalidSettingException ex) {
LOGGER.log(Level.FINE, "Invalid setting found when retrieving timestamps", ex); LOGGER.debug("Invalid setting found when retrieving timestamps", ex);
throw new DownloadFailedException("Invalid settings", ex); throw new DownloadFailedException("Invalid settings", ex);
} }
@@ -238,9 +238,8 @@ public class StandardUpdate {
try { try {
currentTimestamp = Long.parseLong(properties.getProperty(DatabaseProperties.LAST_UPDATED_BASE + entry.getId(), "0")); currentTimestamp = Long.parseLong(properties.getProperty(DatabaseProperties.LAST_UPDATED_BASE + entry.getId(), "0"));
} catch (NumberFormatException ex) { } catch (NumberFormatException ex) {
final String msg = String.format("Error parsing '%s' '%s' from nvdcve.lastupdated", LOGGER.debug("Error parsing '{}' '{}' from nvdcve.lastupdated",
DatabaseProperties.LAST_UPDATED_BASE, entry.getId()); DatabaseProperties.LAST_UPDATED_BASE, entry.getId(), ex);
LOGGER.log(Level.FINE, msg, ex);
} }
if (currentTimestamp == entry.getTimestamp()) { if (currentTimestamp == entry.getTimestamp()) {
entry.setNeedsUpdate(false); entry.setNeedsUpdate(false);
@@ -249,9 +248,8 @@ public class StandardUpdate {
} }
} }
} catch (NumberFormatException ex) { } catch (NumberFormatException ex) {
final String msg = "An invalid schema version or timestamp exists in the data.properties file."; LOGGER.warn("An invalid schema version or timestamp exists in the data.properties file.");
LOGGER.log(Level.WARNING, msg); LOGGER.debug( "", ex);
LOGGER.log(Level.FINE, "", ex);
} }
} }
return updates; return updates;
@@ -295,7 +293,7 @@ public class StandardUpdate {
try { try {
cveDB.close(); cveDB.close();
} catch (Throwable ignore) { } catch (Throwable ignore) {
LOGGER.log(Level.FINEST, "Error closing the cveDB", ignore); LOGGER.trace("Error closing the cveDB", ignore);
} }
} }
} }
@@ -314,7 +312,7 @@ public class StandardUpdate {
cveDB.open(); cveDB.open();
} catch (DatabaseException ex) { } catch (DatabaseException ex) {
closeDataStores(); closeDataStores();
LOGGER.log(Level.FINE, "Database Exception opening databases", ex); LOGGER.debug("Database Exception opening databases", ex);
throw new UpdateException("Error updating the CPE/CVE data, please see the log file for more details."); throw new UpdateException("Error updating the CPE/CVE data, please see the log file for more details.");
} }
} }

View File

@@ -26,8 +26,6 @@ import java.net.URL;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future; import java.util.concurrent.Future;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.GZIPInputStream; import java.util.zip.GZIPInputStream;
import org.apache.commons.io.FileUtils; import org.apache.commons.io.FileUtils;
import org.owasp.dependencycheck.data.nvdcve.CveDB; import org.owasp.dependencycheck.data.nvdcve.CveDB;
@@ -36,6 +34,8 @@ import org.owasp.dependencycheck.data.update.exception.UpdateException;
import org.owasp.dependencycheck.utils.DownloadFailedException; import org.owasp.dependencycheck.utils.DownloadFailedException;
import org.owasp.dependencycheck.utils.Downloader; import org.owasp.dependencycheck.utils.Downloader;
import org.owasp.dependencycheck.utils.Settings; import org.owasp.dependencycheck.utils.Settings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* A callable object to download two files. * A callable object to download two files.
@@ -47,7 +47,7 @@ public class DownloadTask implements Callable<Future<ProcessTask>> {
/** /**
* The Logger. * The Logger.
*/ */
private static final Logger LOGGER = Logger.getLogger(DownloadTask.class.getName()); private static final Logger LOGGER = LoggerFactory.getLogger(DownloadTask.class);
/** /**
* Simple constructor for the callable download task. * Simple constructor for the callable download task.
@@ -185,19 +185,17 @@ public class DownloadTask implements Callable<Future<ProcessTask>> {
Settings.setInstance(settings); Settings.setInstance(settings);
final URL url1 = new URL(nvdCveInfo.getUrl()); final URL url1 = new URL(nvdCveInfo.getUrl());
final URL url2 = new URL(nvdCveInfo.getOldSchemaVersionUrl()); final URL url2 = new URL(nvdCveInfo.getOldSchemaVersionUrl());
String msg = String.format("Download Started for NVD CVE - %s", nvdCveInfo.getId()); LOGGER.info("Download Started for NVD CVE - {}", nvdCveInfo.getId());
LOGGER.log(Level.INFO, msg);
try { try {
Downloader.fetchFile(url1, first); Downloader.fetchFile(url1, first);
Downloader.fetchFile(url2, second); Downloader.fetchFile(url2, second);
} catch (DownloadFailedException ex) { } catch (DownloadFailedException ex) {
msg = String.format("Download Failed for NVD CVE - %s%nSome CVEs may not be reported.", nvdCveInfo.getId()); LOGGER.warn("Download Failed for NVD CVE - {}\nSome CVEs may not be reported.", nvdCveInfo.getId());
LOGGER.log(Level.WARNING, msg);
if (Settings.getString(Settings.KEYS.PROXY_SERVER) == null) { if (Settings.getString(Settings.KEYS.PROXY_SERVER) == null) {
LOGGER.log(Level.INFO, LOGGER.info(
"If you are behind a proxy you may need to configure dependency-check to use the proxy."); "If you are behind a proxy you may need to configure dependency-check to use the proxy.");
} }
LOGGER.log(Level.FINE, null, ex); LOGGER.debug("", ex);
return null; return null;
} }
if (url1.toExternalForm().endsWith(".xml.gz")) { if (url1.toExternalForm().endsWith(".xml.gz")) {
@@ -207,8 +205,7 @@ public class DownloadTask implements Callable<Future<ProcessTask>> {
extractGzip(second); extractGzip(second);
} }
msg = String.format("Download Complete for NVD CVE - %s", nvdCveInfo.getId()); LOGGER.info("Download Complete for NVD CVE - {}", nvdCveInfo.getId());
LOGGER.log(Level.INFO, msg);
if (this.processorService == null) { if (this.processorService == null) {
return null; return null;
} }
@@ -216,9 +213,8 @@ public class DownloadTask implements Callable<Future<ProcessTask>> {
return this.processorService.submit(task); return this.processorService.submit(task);
} catch (Throwable ex) { } catch (Throwable ex) {
final String msg = String.format("An exception occurred downloading NVD CVE - %s%nSome CVEs may not be reported.", nvdCveInfo.getId()); LOGGER.warn("An exception occurred downloading NVD CVE - {}\nSome CVEs may not be reported.", nvdCveInfo.getId());
LOGGER.log(Level.WARNING, msg); LOGGER.debug("Download Task Failed", ex);
LOGGER.log(Level.FINE, "Download Task Failed", ex);
} finally { } finally {
Settings.cleanup(false); Settings.cleanup(false);
} }
@@ -287,14 +283,14 @@ public class DownloadTask implements Callable<Future<ProcessTask>> {
try { try {
cin.close(); cin.close();
} catch (IOException ex) { } catch (IOException ex) {
LOGGER.log(Level.FINEST, "ignore", ex); LOGGER.trace("ignore", ex);
} }
} }
if (out != null) { if (out != null) {
try { try {
out.close(); out.close();
} catch (IOException ex) { } catch (IOException ex) {
LOGGER.log(Level.FINEST, "ignore", ex); LOGGER.trace("ignore", ex);
} }
} }
if (gzip.isFile()) { if (gzip.isFile()) {

View File

@@ -24,8 +24,6 @@ import java.sql.SQLException;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.ParserConfigurationException; 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;
@@ -37,6 +35,8 @@ import org.owasp.dependencycheck.data.update.xml.NvdCve12Handler;
import org.owasp.dependencycheck.data.update.xml.NvdCve20Handler; import org.owasp.dependencycheck.data.update.xml.NvdCve20Handler;
import org.owasp.dependencycheck.dependency.VulnerableSoftware; import org.owasp.dependencycheck.dependency.VulnerableSoftware;
import org.owasp.dependencycheck.utils.Settings; import org.owasp.dependencycheck.utils.Settings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.SAXException; import org.xml.sax.SAXException;
/** /**
@@ -49,7 +49,7 @@ public class ProcessTask implements Callable<ProcessTask> {
/** /**
* The logger. * The logger.
*/ */
private static final Logger LOGGER = Logger.getLogger(ProcessTask.class.getName()); private static final Logger LOGGER = LoggerFactory.getLogger(ProcessTask.class);
/** /**
* A field to store any update exceptions that occur during the "call". * A field to store any update exceptions that occur during the "call".
*/ */
@@ -158,8 +158,7 @@ public class ProcessTask implements Callable<ProcessTask> {
* @throws UpdateException thrown if there is an error loading the data into the database * @throws UpdateException thrown if there is an error loading the data into the database
*/ */
private void processFiles() throws UpdateException { private void processFiles() throws UpdateException {
String msg = String.format("Processing Started for NVD CVE - %s", filePair.getNvdCveInfo().getId()); LOGGER.info("Processing Started for NVD CVE - {}", filePair.getNvdCveInfo().getId());
LOGGER.log(Level.INFO, msg);
try { try {
importXML(filePair.getFirst(), filePair.getSecond()); importXML(filePair.getFirst(), filePair.getSecond());
cveDB.commit(); cveDB.commit();
@@ -181,7 +180,6 @@ public class ProcessTask implements Callable<ProcessTask> {
} finally { } finally {
filePair.cleanup(); filePair.cleanup();
} }
msg = String.format("Processing Complete for NVD CVE - %s", filePair.getNvdCveInfo().getId()); LOGGER.info("Processing Complete for NVD CVE - {}", filePair.getNvdCveInfo().getId());
LOGGER.log(Level.INFO, msg);
} }
} }

View File

@@ -20,14 +20,14 @@ package org.owasp.dependencycheck.data.update.xml;
import java.io.IOException; import java.io.IOException;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.lucene.index.CorruptIndexException; import org.apache.lucene.index.CorruptIndexException;
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.dependency.Reference; import org.owasp.dependencycheck.dependency.Reference;
import org.owasp.dependencycheck.dependency.Vulnerability; import org.owasp.dependencycheck.dependency.Vulnerability;
import org.owasp.dependencycheck.dependency.VulnerableSoftware; import org.owasp.dependencycheck.dependency.VulnerableSoftware;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.Attributes; import org.xml.sax.Attributes;
import org.xml.sax.SAXException; import org.xml.sax.SAXException;
import org.xml.sax.SAXNotSupportedException; import org.xml.sax.SAXNotSupportedException;
@@ -43,7 +43,7 @@ public class NvdCve20Handler extends DefaultHandler {
/** /**
* The logger. * The logger.
*/ */
private static final Logger LOGGER = Logger.getLogger(NvdCve20Handler.class.getName()); private static final Logger LOGGER = LoggerFactory.getLogger(NvdCve20Handler.class);
/** /**
* the current supported schema version. * the current supported schema version.
*/ */
@@ -172,8 +172,8 @@ public class NvdCve20Handler extends DefaultHandler {
final float score = Float.parseFloat(nodeText.toString()); final float score = Float.parseFloat(nodeText.toString());
vulnerability.setCvssScore(score); vulnerability.setCvssScore(score);
} catch (NumberFormatException ex) { } catch (NumberFormatException ex) {
LOGGER.log(Level.SEVERE, "Error parsing CVSS Score."); LOGGER.error("Error parsing CVSS Score.");
LOGGER.log(Level.FINE, null, ex); LOGGER.debug("", ex);
} }
nodeText = null; nodeText = null;
} else if (current.isCVSSAccessVectorNode()) { } else if (current.isCVSSAccessVectorNode()) {

View File

@@ -27,11 +27,11 @@ import java.util.List;
import java.util.Set; import java.util.Set;
import java.util.SortedSet; import java.util.SortedSet;
import java.util.TreeSet; import java.util.TreeSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.owasp.dependencycheck.data.nexus.MavenArtifact; import org.owasp.dependencycheck.data.nexus.MavenArtifact;
import org.owasp.dependencycheck.utils.Checksum; import org.owasp.dependencycheck.utils.Checksum;
import org.owasp.dependencycheck.utils.FileUtils; import org.owasp.dependencycheck.utils.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* A program dependency. This object is one of the core components within DependencyCheck. It is used to collect information about * A program dependency. This object is one of the core components within DependencyCheck. It is used to collect information about
@@ -45,7 +45,7 @@ public class Dependency implements Serializable, Comparable<Dependency> {
/** /**
* The logger. * The logger.
*/ */
private static final Logger LOGGER = Logger.getLogger(Dependency.class.getName()); private static final Logger LOGGER = LoggerFactory.getLogger(Dependency.class);
/** /**
* The actual file path of the dependency on disk. * The actual file path of the dependency on disk.
*/ */
@@ -345,12 +345,12 @@ public class Dependency implements Serializable, Comparable<Dependency> {
final String url = "http://search.maven.org/#search|ga|1|1%3A%22" + this.getSha1sum() + "%22"; final String url = "http://search.maven.org/#search|ga|1|1%3A%22" + this.getSha1sum() + "%22";
i.setUrl(url); i.setUrl(url);
//i.setUrl(mavenArtifact.getArtifactUrl()); //i.setUrl(mavenArtifact.getArtifactUrl());
LOGGER.fine(String.format("Already found identifier %s. Confidence set to highest", i.getValue())); LOGGER.debug("Already found identifier {}. Confidence set to highest", i.getValue());
break; break;
} }
} }
if (!found) { if (!found) {
LOGGER.fine(String.format("Adding new maven identifier %s", mavenArtifact.toString())); LOGGER.debug("Adding new maven identifier {}", mavenArtifact.toString());
this.addIdentifier("maven", mavenArtifact.toString(), mavenArtifact.getArtifactUrl(), Confidence.HIGHEST); this.addIdentifier("maven", mavenArtifact.toString(), mavenArtifact.getArtifactUrl(), Confidence.HIGHEST);
} }
} }
@@ -564,13 +564,11 @@ public class Dependency implements Serializable, Comparable<Dependency> {
md5 = Checksum.getMD5Checksum(file); md5 = Checksum.getMD5Checksum(file);
sha1 = Checksum.getSHA1Checksum(file); sha1 = Checksum.getSHA1Checksum(file);
} catch (IOException ex) { } catch (IOException ex) {
final String msg = String.format("Unable to read '%s' to determine hashes.", file.getName()); LOGGER.warn("Unable to read '{}' to determine hashes.", file.getName());
LOGGER.log(Level.WARNING, msg); LOGGER.debug("", ex);
LOGGER.log(Level.FINE, null, ex);
} catch (NoSuchAlgorithmException ex) { } catch (NoSuchAlgorithmException ex) {
final String msg = "Unable to use MD5 of SHA1 checksums."; LOGGER.warn("Unable to use MD5 of SHA1 checksums.");
LOGGER.log(Level.WARNING, msg); LOGGER.debug("", ex);
LOGGER.log(Level.FINE, null, ex);
} }
this.setMd5sum(md5); this.setMd5sum(md5);
this.setSha1sum(sha1); this.setSha1sum(sha1);
@@ -656,10 +654,10 @@ public class Dependency implements Serializable, Comparable<Dependency> {
*/ */
public void addRelatedDependency(Dependency dependency) { public void addRelatedDependency(Dependency dependency) {
if (this == dependency) { if (this == dependency) {
LOGGER.warning("Attempted to add a circular reference - please post the log file to issue #172 here " LOGGER.warn("Attempted to add a circular reference - please post the log file to issue #172 here "
+ "https://github.com/jeremylong/DependencyCheck/issues/172 "); + "https://github.com/jeremylong/DependencyCheck/issues/172 ");
LOGGER.log(Level.FINE, "this: {0}", this.toString()); LOGGER.debug("this: {}", this);
LOGGER.log(Level.FINE, "dependency: {0}", dependency.toString()); LOGGER.debug("dependency: {}", dependency);
} else { } else {
relatedDependencies.add(dependency); relatedDependencies.add(dependency);
} }

View File

@@ -24,13 +24,13 @@ import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import java.util.TreeSet; import java.util.TreeSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.owasp.dependencycheck.utils.DependencyVersion; import org.owasp.dependencycheck.utils.DependencyVersion;
import org.owasp.dependencycheck.utils.DependencyVersionUtil; import org.owasp.dependencycheck.utils.DependencyVersionUtil;
import org.owasp.dependencycheck.utils.Filter; import org.owasp.dependencycheck.utils.Filter;
import org.owasp.dependencycheck.utils.UrlStringUtils; import org.owasp.dependencycheck.utils.UrlStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* Used to maintain a collection of Evidence. * Used to maintain a collection of Evidence.
@@ -42,7 +42,7 @@ public class EvidenceCollection implements Serializable, Iterable<Evidence> {
/** /**
* The logger. * The logger.
*/ */
private static final Logger LOGGER = Logger.getLogger(EvidenceCollection.class.getName()); private static final Logger LOGGER = LoggerFactory.getLogger(EvidenceCollection.class);
/** /**
* Used to iterate over highest confidence evidence contained in the collection. * Used to iterate over highest confidence evidence contained in the collection.
*/ */
@@ -385,7 +385,7 @@ public class EvidenceCollection implements Serializable, Iterable<Evidence> {
final List<String> data = UrlStringUtils.extractImportantUrlData(part); final List<String> data = UrlStringUtils.extractImportantUrlData(part);
sb.append(' ').append(StringUtils.join(data, ' ')); sb.append(' ').append(StringUtils.join(data, ' '));
} catch (MalformedURLException ex) { } catch (MalformedURLException ex) {
LOGGER.log(Level.FINE, "error parsing " + part, ex); LOGGER.debug("error parsing {}", part, ex);
sb.append(' ').append(part); sb.append(' ').append(part);
} }
} else { } else {

View File

@@ -20,9 +20,9 @@ package org.owasp.dependencycheck.dependency;
import java.io.Serializable; import java.io.Serializable;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.net.URLDecoder; import java.net.URLDecoder;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.owasp.dependencycheck.data.cpe.IndexEntry; import org.owasp.dependencycheck.data.cpe.IndexEntry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* A record containing information about vulnerable software. This is referenced from a vulnerability. * A record containing information about vulnerable software. This is referenced from a vulnerability.
@@ -34,7 +34,7 @@ public class VulnerableSoftware extends IndexEntry implements Serializable, Comp
/** /**
* The logger. * The logger.
*/ */
private static final Logger LOGGER = Logger.getLogger(VulnerableSoftware.class.getName()); private static final Logger LOGGER = LoggerFactory.getLogger(VulnerableSoftware.class);
/** /**
* The serial version UID. * The serial version UID.
*/ */
@@ -49,9 +49,8 @@ public class VulnerableSoftware extends IndexEntry implements Serializable, Comp
try { try {
parseName(cpe); parseName(cpe);
} catch (UnsupportedEncodingException ex) { } catch (UnsupportedEncodingException ex) {
final String msg = String.format("Character encoding is unsupported for CPE '%s'.", cpe); LOGGER.warn("Character encoding is unsupported for CPE '{}'.", cpe);
LOGGER.log(Level.WARNING, msg); LOGGER.debug("", ex);
LOGGER.log(Level.FINE, null, ex);
setName(cpe); setName(cpe);
} }
} }

View File

@@ -19,9 +19,9 @@ package org.owasp.dependencycheck.reporting;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.net.URLEncoder; import java.net.URLEncoder;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.lang.StringEscapeUtils; import org.apache.commons.lang.StringEscapeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* An extremely simple wrapper around various escape utils to perform URL and HTML encoding within the reports. This * An extremely simple wrapper around various escape utils to perform URL and HTML encoding within the reports. This
@@ -34,7 +34,7 @@ public class EscapeTool {
/** /**
* The logger. * The logger.
*/ */
private static final Logger LOGGER = Logger.getLogger(EscapeTool.class.getName()); private static final Logger LOGGER = LoggerFactory.getLogger(EscapeTool.class);
/** /**
* URL Encodes the provided text. * URL Encodes the provided text.
@@ -46,8 +46,8 @@ public class EscapeTool {
try { try {
return URLEncoder.encode(text, "UTF-8"); return URLEncoder.encode(text, "UTF-8");
} catch (UnsupportedEncodingException ex) { } catch (UnsupportedEncodingException ex) {
LOGGER.log(Level.WARNING, "UTF-8 is not supported?"); LOGGER.warn("UTF-8 is not supported?");
LOGGER.log(Level.INFO, null, ex); LOGGER.info("", ex);
} }
return ""; return "";
} }

View File

@@ -30,8 +30,6 @@ import java.text.DateFormat;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.velocity.VelocityContext; import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine; import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.context.Context; import org.apache.velocity.context.Context;
@@ -40,6 +38,8 @@ import org.owasp.dependencycheck.analyzer.Analyzer;
import org.owasp.dependencycheck.data.nvdcve.DatabaseProperties; import org.owasp.dependencycheck.data.nvdcve.DatabaseProperties;
import org.owasp.dependencycheck.dependency.Dependency; import org.owasp.dependencycheck.dependency.Dependency;
import org.owasp.dependencycheck.utils.Settings; import org.owasp.dependencycheck.utils.Settings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* The ReportGenerator is used to, as the name implies, generate reports. Internally the generator uses the Velocity * The ReportGenerator is used to, as the name implies, generate reports. Internally the generator uses the Velocity
@@ -52,7 +52,7 @@ public class ReportGenerator {
/** /**
* The logger. * The logger.
*/ */
private static final Logger LOGGER = Logger.getLogger(ReportGenerator.class.getName()); private static final Logger LOGGER = LoggerFactory.getLogger(ReportGenerator.class);
/** /**
* An enumeration of the report formats. * An enumeration of the report formats.
@@ -235,9 +235,8 @@ public class ReportGenerator {
templatePath = templateName; templatePath = templateName;
input = new FileInputStream(f); input = new FileInputStream(f);
} catch (FileNotFoundException ex) { } catch (FileNotFoundException ex) {
final String msg = "Unable to generate the report, the report template file could not be found."; LOGGER.error("Unable to generate the report, the report template file could not be found.");
LOGGER.log(Level.SEVERE, msg); LOGGER.debug("", ex);
LOGGER.log(Level.FINE, null, ex);
} }
} else { } else {
templatePath = "templates/" + templateName + ".vsl"; templatePath = "templates/" + templateName + ".vsl";
@@ -262,20 +261,20 @@ public class ReportGenerator {
try { try {
writer.close(); writer.close();
} catch (IOException ex) { } catch (IOException ex) {
LOGGER.log(Level.FINEST, null, ex); LOGGER.trace("", ex);
} }
} }
if (outputStream != null) { if (outputStream != null) {
try { try {
outputStream.close(); outputStream.close();
} catch (IOException ex) { } catch (IOException ex) {
LOGGER.log(Level.FINEST, null, ex); LOGGER.trace("", ex);
} }
} }
try { try {
reader.close(); reader.close();
} catch (IOException ex) { } catch (IOException ex) {
LOGGER.log(Level.FINEST, null, ex); LOGGER.trace("", ex);
} }
} }
} }
@@ -311,7 +310,7 @@ public class ReportGenerator {
try { try {
outputSteam.close(); outputSteam.close();
} catch (IOException ex) { } catch (IOException ex) {
LOGGER.log(Level.FINEST, "ignore", ex); LOGGER.trace("ignore", ex);
} }
} }
} }

View File

@@ -17,14 +17,14 @@
*/ */
package org.owasp.dependencycheck.reporting; package org.owasp.dependencycheck.reporting;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.velocity.runtime.RuntimeServices; import org.apache.velocity.runtime.RuntimeServices;
import org.apache.velocity.runtime.log.LogChute; import org.apache.velocity.runtime.log.LogChute;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* <p> * <p>
* DependencyCheck uses {@link java.util.logging.Logger} as a logging framework, and Apache Velocity uses a custom * DependencyCheck uses {@link org.slf4j.Logger} as a logging framework, and Apache Velocity uses a custom
* logging implementation that outputs to a file named velocity.log by default. This class is an implementation of a * logging implementation that outputs to a file named velocity.log by default. This class is an implementation of a
* custom Velocity logger that redirects all velocity logging to the Java Logger class. * custom Velocity logger that redirects all velocity logging to the Java Logger class.
* </p><p> * </p><p>
@@ -39,7 +39,7 @@ public class VelocityLoggerRedirect implements LogChute {
/** /**
* The Logger. * The Logger.
*/ */
private static final Logger LOGGER = Logger.getLogger(VelocityLoggerRedirect.class.getName()); private static final Logger LOGGER = LoggerFactory.getLogger(VelocityLoggerRedirect.class);
/** /**
* This will be invoked once by the LogManager. * This will be invoked once by the LogManager.
@@ -58,7 +58,25 @@ public class VelocityLoggerRedirect implements LogChute {
* @param message the message to be logged * @param message the message to be logged
*/ */
public void log(int level, String message) { public void log(int level, String message) {
LOGGER.log(getLevel(level), message); switch (level) {
case TRACE_ID:
LOGGER.trace(message);
break;
case DEBUG_ID:
LOGGER.debug(message);
break;
case INFO_ID:
LOGGER.info(message);
break;
case WARN_ID:
LOGGER.warn(message);
break;
case ERROR_ID:
LOGGER.error(message);
break;
default:
LOGGER.info(message);
}
} }
/** /**
@@ -70,7 +88,25 @@ public class VelocityLoggerRedirect implements LogChute {
* @param t a throwable to log * @param t a throwable to log
*/ */
public void log(int level, String message, Throwable t) { public void log(int level, String message, Throwable t) {
LOGGER.log(getLevel(level), message, t); switch (level) {
case TRACE_ID:
LOGGER.trace(message, t);
break;
case DEBUG_ID:
LOGGER.debug(message, t);
break;
case INFO_ID:
LOGGER.info(message, t);
break;
case WARN_ID:
LOGGER.warn(message, t);
break;
case ERROR_ID:
LOGGER.error(message, t);
break;
default:
LOGGER.info(message, t);
}
} }
/** /**
@@ -82,27 +118,4 @@ public class VelocityLoggerRedirect implements LogChute {
public boolean isLevelEnabled(int level) { public boolean isLevelEnabled(int level) {
return true; return true;
} }
/**
* Maps Velocity log levels to {@link Logger} values.
*
* @param velocityLevel the logging level
* @return the logging level
*/
private Level getLevel(int velocityLevel) {
switch (velocityLevel) {
case TRACE_ID:
return Level.ALL;
case DEBUG_ID:
return Level.FINE;
case INFO_ID:
return Level.INFO;
case WARN_ID:
return Level.WARNING;
case ERROR_ID:
return Level.SEVERE;
default:
return Level.INFO;
}
}
} }

View File

@@ -17,8 +17,8 @@
*/ */
package org.owasp.dependencycheck.suppression; package org.owasp.dependencycheck.suppression;
import java.util.logging.Level; import org.slf4j.Logger;
import java.util.logging.Logger; import org.slf4j.LoggerFactory;
import org.xml.sax.ErrorHandler; import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException; import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException; import org.xml.sax.SAXParseException;
@@ -33,7 +33,7 @@ public class SuppressionErrorHandler implements ErrorHandler {
/** /**
* The logger. * The logger.
*/ */
private static final Logger LOGGER = Logger.getLogger(SuppressionErrorHandler.class.getName()); private static final Logger LOGGER = LoggerFactory.getLogger(SuppressionErrorHandler.class);
/** /**
* Builds a prettier exception message. * Builds a prettier exception message.
@@ -70,7 +70,7 @@ public class SuppressionErrorHandler implements ErrorHandler {
*/ */
@Override @Override
public void warning(SAXParseException ex) throws SAXException { public void warning(SAXParseException ex) throws SAXException {
LOGGER.log(Level.FINE, null, ex); LOGGER.debug("", ex);
} }
/** /**

View File

@@ -25,11 +25,12 @@ import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.io.Reader; import java.io.Reader;
import java.util.List; import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.ParserConfigurationException; 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;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.InputSource; import org.xml.sax.InputSource;
import org.xml.sax.SAXException; import org.xml.sax.SAXException;
import org.xml.sax.XMLReader; import org.xml.sax.XMLReader;
@@ -44,7 +45,7 @@ public class SuppressionParser {
/** /**
* The logger. * The logger.
*/ */
private static final Logger LOGGER = Logger.getLogger(SuppressionParser.class.getName()); private static final Logger LOGGER = LoggerFactory.getLogger(SuppressionParser.class);
/** /**
* JAXP Schema Language. Source: http://docs.oracle.com/javase/tutorial/jaxp/sax/validation.html * JAXP Schema Language. Source: http://docs.oracle.com/javase/tutorial/jaxp/sax/validation.html
*/ */
@@ -71,14 +72,14 @@ public class SuppressionParser {
fis = new FileInputStream(file); fis = new FileInputStream(file);
return parseSuppressionRules(fis); return parseSuppressionRules(fis);
} catch (IOException ex) { } catch (IOException ex) {
LOGGER.log(Level.FINE, null, ex); LOGGER.debug("", ex);
throw new SuppressionParseException(ex); throw new SuppressionParseException(ex);
} finally { } finally {
if (fis != null) { if (fis != null) {
try { try {
fis.close(); fis.close();
} catch (IOException ex) { } catch (IOException ex) {
LOGGER.log(Level.FINE, "Unable to close stream", ex); LOGGER.debug("Unable to close stream", ex);
} }
} }
} }
@@ -113,16 +114,16 @@ public class SuppressionParser {
return handler.getSuppressionRules(); return handler.getSuppressionRules();
} catch (ParserConfigurationException ex) { } catch (ParserConfigurationException ex) {
LOGGER.log(Level.FINE, null, ex); LOGGER.debug("", ex);
throw new SuppressionParseException(ex); throw new SuppressionParseException(ex);
} catch (SAXException ex) { } catch (SAXException ex) {
LOGGER.log(Level.FINE, null, ex); LOGGER.debug("", ex);
throw new SuppressionParseException(ex); throw new SuppressionParseException(ex);
} catch (FileNotFoundException ex) { } catch (FileNotFoundException ex) {
LOGGER.log(Level.FINE, null, ex); LOGGER.debug("", ex);
throw new SuppressionParseException(ex); throw new SuppressionParseException(ex);
} catch (IOException ex) { } catch (IOException ex) {
LOGGER.log(Level.FINE, null, ex); LOGGER.debug("", ex);
throw new SuppressionParseException(ex); throw new SuppressionParseException(ex);
} }
} }

View File

@@ -21,9 +21,9 @@ import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.sql.Statement; import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.owasp.dependencycheck.data.nvdcve.DatabaseException; import org.owasp.dependencycheck.data.nvdcve.DatabaseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* *
@@ -34,7 +34,7 @@ public final class DBUtils {
/** /**
* The logger. * The logger.
*/ */
private static final Logger LOGGER = Logger.getLogger(DBUtils.class.getName()); private static final Logger LOGGER = LoggerFactory.getLogger(DBUtils.class);
/** /**
* Private constructor for a utility class. * Private constructor for a utility class.
@@ -76,7 +76,7 @@ public final class DBUtils {
try { try {
statement.close(); statement.close();
} catch (SQLException ex) { } catch (SQLException ex) {
LOGGER.log(Level.FINEST, statement.toString(), ex); LOGGER.trace(statement.toString(), ex);
} }
} }
} }
@@ -91,7 +91,7 @@ public final class DBUtils {
try { try {
rs.close(); rs.close();
} catch (SQLException ex) { } catch (SQLException ex) {
LOGGER.log(Level.FINEST, rs.toString(), ex); LOGGER.trace(rs.toString(), ex);
} }
} }
} }

View File

@@ -0,0 +1,26 @@
package org.owasp.dependencycheck.utils;
import ch.qos.cal10n.BaseName;
import ch.qos.cal10n.Locale;
import ch.qos.cal10n.LocaleData;
/**
* Created by colezlaw on 6/13/15.
*/
@BaseName("dependencycheck-resources")
@LocaleData(defaultCharset = "UTF-8",
value = {
@Locale("en")
}
)
public enum DCResources {
NOTDEPLOYED,
GROKERROR,
NOTASSEMBLY,
GROKRC,
GROKDEPLOYED,
GROKNOTDEPLOYED,
GROKINITFAIL,
GROKINITMSG,
GROKNOTDELETED
}

View File

@@ -29,8 +29,6 @@ import java.io.FileOutputStream;
import java.io.FilenameFilter; import java.io.FilenameFilter;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.ZipEntry; import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream; import java.util.zip.ZipInputStream;
@@ -40,6 +38,8 @@ import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream;
import org.owasp.dependencycheck.Engine; import org.owasp.dependencycheck.Engine;
import org.owasp.dependencycheck.analyzer.exception.AnalysisException; import org.owasp.dependencycheck.analyzer.exception.AnalysisException;
import org.owasp.dependencycheck.analyzer.exception.ArchiveExtractionException; import org.owasp.dependencycheck.analyzer.exception.ArchiveExtractionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* Set of utilities to extract files from archives. * Set of utilities to extract files from archives.
@@ -51,7 +51,7 @@ public final class ExtractionUtil {
/** /**
* The logger. * The logger.
*/ */
private static final Logger LOGGER = Logger.getLogger(ExtractionUtil.class.getName()); private static final Logger LOGGER = LoggerFactory.getLogger(ExtractionUtil.class);
/** /**
* The buffer size to use when extracting files from the archive. * The buffer size to use when extracting files from the archive.
*/ */
@@ -94,7 +94,7 @@ public final class ExtractionUtil {
try { try {
fis = new FileInputStream(archive); fis = new FileInputStream(archive);
} catch (FileNotFoundException ex) { } catch (FileNotFoundException ex) {
LOGGER.log(Level.FINE, null, ex); LOGGER.debug("", ex);
throw new ExtractionException("Archive file was not found.", ex); throw new ExtractionException("Archive file was not found.", ex);
} }
zis = new ZipInputStream(new BufferedInputStream(fis)); zis = new ZipInputStream(new BufferedInputStream(fis));
@@ -118,11 +118,11 @@ public final class ExtractionUtil {
bos = new BufferedOutputStream(fos, BUFFER_SIZE); bos = new BufferedOutputStream(fos, BUFFER_SIZE);
transferUsingBuffer(zis, bos); transferUsingBuffer(zis, bos);
} catch (FileNotFoundException ex) { } catch (FileNotFoundException ex) {
LOGGER.log(Level.FINE, null, ex); LOGGER.debug("", ex);
final String msg = String.format("Unable to find file '%s'.", file.getName()); final String msg = String.format("Unable to find file '%s'.", file.getName());
throw new ExtractionException(msg, ex); throw new ExtractionException(msg, ex);
} catch (IOException ex) { } catch (IOException ex) {
LOGGER.log(Level.FINE, null, ex); LOGGER.debug("", ex);
final String msg = String.format("IO Exception while parsing file '%s'.", file.getName()); final String msg = String.format("IO Exception while parsing file '%s'.", file.getName());
throw new ExtractionException(msg, ex); throw new ExtractionException(msg, ex);
} finally { } finally {
@@ -133,7 +133,7 @@ public final class ExtractionUtil {
} }
} catch (IOException ex) { } catch (IOException ex) {
final String msg = String.format("Exception reading archive '%s'.", archive.getName()); final String msg = String.format("Exception reading archive '%s'.", archive.getName());
LOGGER.log(Level.FINE, msg, ex); LOGGER.debug("", ex);
throw new ExtractionException(msg, ex); throw new ExtractionException(msg, ex);
} finally { } finally {
closeStream(zis); closeStream(zis);
@@ -158,22 +158,20 @@ public final class ExtractionUtil {
try { try {
fis = new FileInputStream(archive); fis = new FileInputStream(archive);
} catch (FileNotFoundException ex) { } catch (FileNotFoundException ex) {
LOGGER.log(Level.FINE, null, ex); LOGGER.debug("", ex);
throw new ExtractionException("Archive file was not found.", ex); throw new ExtractionException("Archive file was not found.", ex);
} }
try { try {
extractArchive(new ZipArchiveInputStream(new BufferedInputStream( extractArchive(new ZipArchiveInputStream(new BufferedInputStream(
fis)), destination, filter); fis)), destination, filter);
} catch (ArchiveExtractionException ex) { } catch (ArchiveExtractionException ex) {
final String msg = String.format( LOGGER.warn("Exception extracting archive '{}'.", archive.getName());
"Exception extracting archive '%s'.", archive.getName()); LOGGER.debug("", ex);
LOGGER.log(Level.WARNING, msg);
LOGGER.log(Level.FINE, null, ex);
} finally { } finally {
try { try {
fis.close(); fis.close();
} catch (IOException ex) { } catch (IOException ex) {
LOGGER.log(Level.FINE, null, ex); LOGGER.debug("", ex);
} }
} }
} }
@@ -228,9 +226,8 @@ public final class ExtractionUtil {
FilenameFilter filter, ArchiveEntry entry) throws ExtractionException { FilenameFilter filter, ArchiveEntry entry) throws ExtractionException {
final File file = new File(destination, entry.getName()); final File file = new File(destination, entry.getName());
if (filter.accept(file.getParentFile(), file.getName())) { if (filter.accept(file.getParentFile(), file.getName())) {
final String extracting = String.format("Extracting '%s'", LOGGER.debug("Extracting '{}'",
file.getPath()); file.getPath());
LOGGER.fine(extracting);
BufferedOutputStream bos = null; BufferedOutputStream bos = null;
FileOutputStream fos = null; FileOutputStream fos = null;
try { try {
@@ -239,12 +236,12 @@ public final class ExtractionUtil {
bos = new BufferedOutputStream(fos, BUFFER_SIZE); bos = new BufferedOutputStream(fos, BUFFER_SIZE);
transferUsingBuffer(input, bos); transferUsingBuffer(input, bos);
} catch (FileNotFoundException ex) { } catch (FileNotFoundException ex) {
LOGGER.log(Level.FINE, null, ex); LOGGER.debug("", ex);
final String msg = String.format("Unable to find file '%s'.", final String msg = String.format("Unable to find file '%s'.",
file.getName()); file.getName());
throw new ExtractionException(msg, ex); throw new ExtractionException(msg, ex);
} catch (IOException ex) { } catch (IOException ex) {
LOGGER.log(Level.FINE, null, ex); LOGGER.debug("", ex);
final String msg = String final String msg = String
.format("IO Exception while parsing file '%s'.", .format("IO Exception while parsing file '%s'.",
file.getName()); file.getName());
@@ -283,7 +280,7 @@ public final class ExtractionUtil {
try { try {
stream.close(); stream.close();
} catch (IOException ex) { } catch (IOException ex) {
LOGGER.log(Level.FINEST, null, ex); LOGGER.trace("", ex);
} }
} }
} }

View File

@@ -24,11 +24,12 @@ import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.io.Reader; import java.io.Reader;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.ParserConfigurationException; 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;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.InputSource; import org.xml.sax.InputSource;
import org.xml.sax.SAXException; import org.xml.sax.SAXException;
import org.xml.sax.XMLReader; import org.xml.sax.XMLReader;
@@ -43,7 +44,7 @@ public class PomParser {
/** /**
* The logger. * The logger.
*/ */
private static final Logger LOGGER = Logger.getLogger(PomParser.class.getName()); private static final Logger LOGGER = LoggerFactory.getLogger(PomParser.class);
/** /**
* Parses the given xml file and returns a Model object containing only the fields dependency-check requires. * Parses the given xml file and returns a Model object containing only the fields dependency-check requires.
@@ -58,14 +59,14 @@ public class PomParser {
fis = new FileInputStream(file); fis = new FileInputStream(file);
return parse(fis); return parse(fis);
} catch (IOException ex) { } catch (IOException ex) {
LOGGER.log(Level.FINE, null, ex); LOGGER.debug("", ex);
throw new PomParseException(ex); throw new PomParseException(ex);
} finally { } finally {
if (fis != null) { if (fis != null) {
try { try {
fis.close(); fis.close();
} catch (IOException ex) { } catch (IOException ex) {
LOGGER.log(Level.FINE, "Unable to close stream", ex); LOGGER.debug("Unable to close stream", ex);
} }
} }
} }
@@ -96,16 +97,16 @@ public class PomParser {
return handler.getModel(); return handler.getModel();
} catch (ParserConfigurationException ex) { } catch (ParserConfigurationException ex) {
LOGGER.log(Level.FINE, null, ex); LOGGER.debug("", ex);
throw new PomParseException(ex); throw new PomParseException(ex);
} catch (SAXException ex) { } catch (SAXException ex) {
LOGGER.log(Level.FINE, null, ex); LOGGER.debug("", ex);
throw new PomParseException(ex); throw new PomParseException(ex);
} catch (FileNotFoundException ex) { } catch (FileNotFoundException ex) {
LOGGER.log(Level.FINE, null, ex); LOGGER.debug("", ex);
throw new PomParseException(ex); throw new PomParseException(ex);
} catch (IOException ex) { } catch (IOException ex) {
LOGGER.log(Level.FINE, null, ex); LOGGER.debug("", ex);
throw new PomParseException(ex); throw new PomParseException(ex);
} }
} }

View File

@@ -20,12 +20,12 @@ package org.owasp.dependencycheck.xml.pom;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.util.jar.JarFile; import java.util.jar.JarFile;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.ZipEntry; import java.util.zip.ZipEntry;
import org.owasp.dependencycheck.analyzer.JarAnalyzer; import org.owasp.dependencycheck.analyzer.JarAnalyzer;
import org.owasp.dependencycheck.analyzer.exception.AnalysisException; import org.owasp.dependencycheck.analyzer.exception.AnalysisException;
import org.owasp.dependencycheck.dependency.Dependency; import org.owasp.dependencycheck.dependency.Dependency;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* *
@@ -41,7 +41,7 @@ public final class PomUtils {
/** /**
* The logger. * The logger.
*/ */
private static final Logger LOGGER = Logger.getLogger(PomUtils.class.getName()); private static final Logger LOGGER = LoggerFactory.getLogger(PomUtils.class);
/** /**
* Reads in the specified POM and converts it to a Model. * Reads in the specified POM and converts it to a Model.
@@ -57,19 +57,16 @@ public final class PomUtils {
final PomParser parser = new PomParser(); final PomParser parser = new PomParser();
model = parser.parse(file); model = parser.parse(file);
} catch (PomParseException ex) { } catch (PomParseException ex) {
final String msg = String.format("Unable to parse pom '%s'", file.getPath()); LOGGER.warn("Unable to parse pom '{}'", file.getPath());
LOGGER.log(Level.WARNING, msg); LOGGER.debug("", ex);
LOGGER.log(Level.FINE, "", ex);
throw new AnalysisException(ex); throw new AnalysisException(ex);
} catch (IOException ex) { } catch (IOException ex) {
final String msg = String.format("Unable to parse pom '%s'(IO Exception)", file.getPath()); LOGGER.warn("Unable to parse pom '{}'(IO Exception)", file.getPath());
LOGGER.log(Level.WARNING, msg); LOGGER.debug("", ex);
LOGGER.log(Level.FINE, "", ex);
throw new AnalysisException(ex); throw new AnalysisException(ex);
} catch (Throwable ex) { } catch (Throwable ex) {
final String msg = String.format("Unexpected error during parsing of the pom '%s'", file.getPath()); LOGGER.warn("Unexpected error during parsing of the pom '{}'", file.getPath());
LOGGER.log(Level.WARNING, msg); LOGGER.debug("", ex);
LOGGER.log(Level.FINE, "", ex);
throw new AnalysisException(ex); throw new AnalysisException(ex);
} }
return model; return model;
@@ -91,21 +88,18 @@ public final class PomUtils {
try { try {
final PomParser parser = new PomParser(); final PomParser parser = new PomParser();
model = parser.parse(jar.getInputStream(entry)); model = parser.parse(jar.getInputStream(entry));
LOGGER.fine(String.format("Read POM %s", path)); LOGGER.debug("Read POM {}", path);
} catch (SecurityException ex) { } catch (SecurityException ex) {
final String msg = String.format("Unable to parse pom '%s' in jar '%s'; invalid signature", path, jar.getName()); LOGGER.warn("Unable to parse pom '{}' in jar '{}'; invalid signature", path, jar.getName());
LOGGER.log(Level.WARNING, msg); LOGGER.debug("", ex);
LOGGER.log(Level.FINE, null, ex);
throw new AnalysisException(ex); throw new AnalysisException(ex);
} catch (IOException ex) { } catch (IOException ex) {
final String msg = String.format("Unable to parse pom '%s' in jar '%s' (IO Exception)", path, jar.getName()); LOGGER.warn("Unable to parse pom '{}' in jar '{}' (IO Exception)", path, jar.getName());
LOGGER.log(Level.WARNING, msg); LOGGER.debug("", ex);
LOGGER.log(Level.FINE, "", ex);
throw new AnalysisException(ex); throw new AnalysisException(ex);
} catch (Throwable ex) { } catch (Throwable ex) {
final String msg = String.format("Unexpected error during parsing of the pom '%s' in jar '%s'", path, jar.getName()); LOGGER.warn("Unexpected error during parsing of the pom '{}' in jar '{}'", path, jar.getName());
LOGGER.log(Level.WARNING, msg); LOGGER.debug("", ex);
LOGGER.log(Level.FINE, "", ex);
throw new AnalysisException(ex); throw new AnalysisException(ex);
} }
} }

View File

@@ -1,10 +1,10 @@
analyzer.AssemblyAnalyzer.notdeployed=GrokAssembly didn't get deployed NOTDEPLOYED=GrokAssembly didn't get deployed
analyzer.AssemblyAnalyzer.grokassembly.stderr=Error from GrokAssembly: {0} GROKERROR=Error from GrokAssembly: {0}
analyzer.AssemblyAnalyzer.notassembly={0} is not a .NET assembly or executable and as such cannot be analyzed by dependency-check NOTASSEMBLY={0} is not a .NET assembly or executable and as such cannot be analyzed by dependency-check
analyzer.AssemblyAnalyzer.grokassembly.rc=Return code {0} from GrokAssembly GROKRC=Return code {0} from GrokAssembly
analyzer.AssemblyAnalyzer.grokassembly.deployed=Extracted GrokAssembly.exe to {0} GROKDEPLOYED=Extracted GrokAssembly.exe to {0}
analyzer.AssemblyAnalyzer.grokassembly.notdeployed=Could not extract GrokAssembly.exe: {0} GROKNOTDEPLOYED=Could not extract GrokAssembly.exe: {0}
analyzer.AssemblyAnalyzer.grokassembly.initialization.failed=An error occurred with the .NET AssemblyAnalyzer; \ GROKINITFAIL=An error occurred with the .NET AssemblyAnalyzer; \
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.
analyzer.AssemblyAnalyzer.grokassembly.initialization.message=Could not execute GrokAssembly {0} GROKINITMSG=Could not execute GrokAssembly {0}
analyzer.AssemblyAnalyzer.grokassembly.notdeleted=Can't delete temporary GrokAssembly.exe GROKNOTDELETED=Can't delete temporary GrokAssembly.exe

View File

@@ -0,0 +1,10 @@
NOTDEPLOYED=GrokAssembly didn't get deployed
GROKERROR=Error from GrokAssembly: {0}
NOTASSEMBLY={0} is not a .NET assembly or executable and as such cannot be analyzed by dependency-check
GROKRC=Return code {0} from GrokAssembly
GROKDEPLOYED=Extracted GrokAssembly.exe to {0}
GROKNOTDEPLOYED=Could not extract GrokAssembly.exe: {0}
GROKINITFAIL=An error occurred with the .NET AssemblyAnalyzer; \
this can be ignored unless you are scanning .NET DLLs. Please see the log for more details.
GROKINITMSG=Could not execute GrokAssembly {0}
GROKNOTDELETED=Can't delete temporary GrokAssembly.exe

View File

@@ -26,13 +26,12 @@ import org.owasp.dependencycheck.dependency.Dependency;
import org.owasp.dependencycheck.suppression.SuppressionParseException; import org.owasp.dependencycheck.suppression.SuppressionParseException;
import org.owasp.dependencycheck.suppression.SuppressionRule; import org.owasp.dependencycheck.suppression.SuppressionRule;
import org.owasp.dependencycheck.utils.Settings; import org.owasp.dependencycheck.utils.Settings;
import org.slf4j.LoggerFactory;
import java.net.MalformedURLException; import java.net.MalformedURLException;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import static org.junit.Assert.assertNull; import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
@@ -93,9 +92,9 @@ public class AbstractSuppressionAnalyzerTest extends BaseTest {
final String uri = this.getClass().getClassLoader().getResource("suppressions.xml").toURI().toURL().toString(); final String uri = this.getClass().getClassLoader().getResource("suppressions.xml").toURI().toURL().toString();
Settings.setString(Settings.KEYS.SUPPRESSION_FILE, uri); Settings.setString(Settings.KEYS.SUPPRESSION_FILE, uri);
} catch (URISyntaxException ex) { } catch (URISyntaxException ex) {
Logger.getLogger(AbstractSuppressionAnalyzerTest.class.getName()).log(Level.SEVERE, null, ex); LoggerFactory.getLogger(AbstractSuppressionAnalyzerTest.class).error("", ex);
} catch (MalformedURLException ex) { } catch (MalformedURLException ex) {
Logger.getLogger(AbstractSuppressionAnalyzerTest.class.getName()).log(Level.SEVERE, null, ex); LoggerFactory.getLogger(AbstractSuppressionAnalyzerTest.class).error("", ex);
} }
} }

View File

@@ -18,8 +18,6 @@
package org.owasp.dependencycheck.analyzer; package org.owasp.dependencycheck.analyzer;
import java.io.File; import java.io.File;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.junit.After; import org.junit.After;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
@@ -34,6 +32,10 @@ import org.owasp.dependencycheck.dependency.Confidence;
import org.owasp.dependencycheck.dependency.Dependency; import org.owasp.dependencycheck.dependency.Dependency;
import org.owasp.dependencycheck.dependency.Evidence; import org.owasp.dependencycheck.dependency.Evidence;
import org.owasp.dependencycheck.utils.Settings; import org.owasp.dependencycheck.utils.Settings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.impl.SimpleLogger;
import org.slf4j.impl.SimpleLoggerFactory;
/** /**
* Tests for the AssemblyAnalyzer. * Tests for the AssemblyAnalyzer.
@@ -43,7 +45,9 @@ import org.owasp.dependencycheck.utils.Settings;
*/ */
public class AssemblyAnalyzerTest extends BaseTest { public class AssemblyAnalyzerTest extends BaseTest {
private static final Logger LOGGER = Logger.getLogger(AssemblyAnalyzerTest.class.getName()); private static final Logger LOGGER = LoggerFactory.getLogger(AssemblyAnalyzerTest.class);
private static final String LOG_KEY = "org.slf4j.simpleLogger.org.owasp.dependencycheck.analyzer.AssemblyAnalyzer";
AssemblyAnalyzer analyzer; AssemblyAnalyzer analyzer;
@@ -60,9 +64,9 @@ public class AssemblyAnalyzerTest extends BaseTest {
analyzer.initialize(); analyzer.initialize();
} catch (Exception e) { } catch (Exception e) {
if (e.getMessage().contains("Could not execute .NET AssemblyAnalyzer")) { if (e.getMessage().contains("Could not execute .NET AssemblyAnalyzer")) {
LOGGER.log(Level.WARNING, "Exception setting up AssemblyAnalyzer. Tests will be incomplete"); LOGGER.warn("Exception setting up AssemblyAnalyzer. Tests will be incomplete");
} else { } else {
LOGGER.log(Level.WARNING, "Exception setting up AssemblyAnalyzer. Tests will be incomplete", e); LOGGER.warn("Exception setting up AssemblyAnalyzer. Tests will be incomplete", e);
} }
Assume.assumeNoException("Is mono installed? TESTS WILL BE INCOMPLETE", e); Assume.assumeNoException("Is mono installed? TESTS WILL BE INCOMPLETE", e);
} }
@@ -113,11 +117,8 @@ public class AssemblyAnalyzerTest extends BaseTest {
@Test @Test
public void testNonexistent() { public void testNonexistent() {
Level oldLevel = Logger.getLogger(AssemblyAnalyzer.class.getName()).getLevel();
Level oldDependency = Logger.getLogger(Dependency.class.getName()).getLevel();
// Tweak the log level so the warning doesn't show in the console // Tweak the log level so the warning doesn't show in the console
Logger.getLogger(AssemblyAnalyzer.class.getName()).setLevel(Level.OFF); String oldProp = System.getProperty(LOG_KEY, "info");
Logger.getLogger(Dependency.class.getName()).setLevel(Level.OFF);
//File f = new File(AssemblyAnalyzerTest.class.getClassLoader().getResource("log4net.dll").getPath()); //File f = new File(AssemblyAnalyzerTest.class.getClassLoader().getResource("log4net.dll").getPath());
File f = BaseTest.getResourceAsFile(this, "log4net.dll"); File f = BaseTest.getResourceAsFile(this, "log4net.dll");
File test = new File(f.getParent(), "nonexistent.dll"); File test = new File(f.getParent(), "nonexistent.dll");
@@ -129,8 +130,7 @@ public class AssemblyAnalyzerTest extends BaseTest {
} catch (AnalysisException ae) { } catch (AnalysisException ae) {
assertEquals("File does not exist", ae.getMessage()); assertEquals("File does not exist", ae.getMessage());
} finally { } finally {
Logger.getLogger(AssemblyAnalyzer.class.getName()).setLevel(oldLevel); System.setProperty(LOG_KEY, oldProp);
Logger.getLogger(Dependency.class.getName()).setLevel(oldDependency);
} }
} }
@@ -151,10 +151,10 @@ public class AssemblyAnalyzerTest extends BaseTest {
Settings.setString(Settings.KEYS.ANALYZER_ASSEMBLY_MONO_PATH, "/yooser/bine/mono"); Settings.setString(Settings.KEYS.ANALYZER_ASSEMBLY_MONO_PATH, "/yooser/bine/mono");
} }
Level oldLevel = Logger.getLogger(AssemblyAnalyzer.class.getName()).getLevel(); String oldProp = System.getProperty(LOG_KEY, "info");
try { try {
// Tweak the logging to swallow the warning when testing // Tweak the logging to swallow the warning when testing
Logger.getLogger(AssemblyAnalyzer.class.getName()).setLevel(Level.OFF); System.setProperty(LOG_KEY, "error");
// Have to make a NEW analyzer because during setUp, it would have gotten the correct one // Have to make a NEW analyzer because during setUp, it would have gotten the correct one
AssemblyAnalyzer aanalyzer = new AssemblyAnalyzer(); AssemblyAnalyzer aanalyzer = new AssemblyAnalyzer();
aanalyzer.supportsExtension("dll"); aanalyzer.supportsExtension("dll");
@@ -163,8 +163,8 @@ public class AssemblyAnalyzerTest extends BaseTest {
} catch (AnalysisException ae) { } catch (AnalysisException ae) {
assertEquals("An error occured with the .NET AssemblyAnalyzer", ae.getMessage()); assertEquals("An error occured with the .NET AssemblyAnalyzer", ae.getMessage());
} finally { } finally {
System.setProperty(LOG_KEY, oldProp);
// Recover the logger // Recover the logger
Logger.getLogger(AssemblyAnalyzer.class.getName()).setLevel(oldLevel);
// Now recover the way we came in. If we had to set a System property, delete it. Otherwise, // Now recover the way we came in. If we had to set a System property, delete it. Otherwise,
// reset the old value // reset the old value
if (oldValue == null) { if (oldValue == null) {

View File

@@ -5,11 +5,12 @@ import org.junit.Test;
import org.owasp.dependencycheck.BaseTest; import org.owasp.dependencycheck.BaseTest;
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;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.net.URL; import java.net.URL;
import java.util.List; import java.util.List;
import java.util.logging.Logger;
import static org.junit.Assert.*; import static org.junit.Assert.*;
@@ -17,13 +18,13 @@ import static org.junit.Assert.*;
* Created by colezlaw on 10/13/14. * Created by colezlaw on 10/13/14.
*/ */
public class CentralSearchTest extends BaseTest { public class CentralSearchTest extends BaseTest {
private static final Logger LOGGER = Logger.getLogger(CentralSearchTest.class.getName()); private static final Logger LOGGER = LoggerFactory.getLogger(CentralSearchTest.class);
private CentralSearch searcher; private CentralSearch searcher;
@Before @Before
public void setUp() throws Exception { public void setUp() throws Exception {
String centralUrl = Settings.getString(Settings.KEYS.ANALYZER_CENTRAL_URL); String centralUrl = Settings.getString(Settings.KEYS.ANALYZER_CENTRAL_URL);
LOGGER.fine(centralUrl); LOGGER.debug(centralUrl);
searcher = new CentralSearch(new URL(centralUrl)); searcher = new CentralSearch(new URL(centralUrl));
} }

View File

@@ -19,7 +19,6 @@ package org.owasp.dependencycheck.data.nexus;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.net.URL; import java.net.URL;
import java.util.logging.Logger;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotNull;
import org.junit.Assume; import org.junit.Assume;
@@ -28,16 +27,18 @@ import org.junit.Ignore;
import org.junit.Test; import org.junit.Test;
import org.owasp.dependencycheck.BaseTest; import org.owasp.dependencycheck.BaseTest;
import org.owasp.dependencycheck.utils.Settings; import org.owasp.dependencycheck.utils.Settings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class NexusSearchTest extends BaseTest { public class NexusSearchTest extends BaseTest {
private static final Logger LOGGER = Logger.getLogger(NexusSearchTest.class.getName()); private static final Logger LOGGER = LoggerFactory.getLogger(NexusSearchTest.class);
private NexusSearch searcher; private NexusSearch searcher;
@Before @Before
public void setUp() throws Exception { public void setUp() throws Exception {
String nexusUrl = Settings.getString(Settings.KEYS.ANALYZER_NEXUS_URL); String nexusUrl = Settings.getString(Settings.KEYS.ANALYZER_NEXUS_URL);
LOGGER.fine(nexusUrl); LOGGER.debug(nexusUrl);
searcher = new NexusSearch(new URL(nexusUrl)); searcher = new NexusSearch(new URL(nexusUrl));
Assume.assumeTrue(searcher.preflightRequest()); Assume.assumeTrue(searcher.preflightRequest());
} }

View File

@@ -22,13 +22,12 @@ import java.io.BufferedOutputStream;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.ZipEntry; import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream; import java.util.zip.ZipInputStream;
import org.junit.Before; import org.junit.Before;
import org.owasp.dependencycheck.BaseTest; import org.owasp.dependencycheck.BaseTest;
import org.owasp.dependencycheck.utils.Settings; import org.owasp.dependencycheck.utils.Settings;
import org.slf4j.LoggerFactory;
/** /**
* *
@@ -76,7 +75,7 @@ public abstract class BaseDBTestCase extends BaseTest {
dest.write(data, 0, count); dest.write(data, 0, count);
} }
} catch (Throwable ex) { } catch (Throwable ex) {
Logger.getLogger(BaseDBTestCase.class.getName()).log(Level.SEVERE, null, ex); LoggerFactory.getLogger(BaseDBTestCase.class).error("", ex);
} finally { } finally {
try { try {
if (dest != null) { if (dest != null) {
@@ -84,14 +83,14 @@ public abstract class BaseDBTestCase extends BaseTest {
dest.close(); dest.close();
} }
} catch (Throwable ex) { } catch (Throwable ex) {
Logger.getLogger(BaseDBTestCase.class.getName()).log(Level.FINEST, null, ex); LoggerFactory.getLogger(BaseDBTestCase.class).trace("", ex);
} }
try { try {
if (fos != null) { if (fos != null) {
fos.close(); fos.close();
} }
} catch (Throwable ex) { } catch (Throwable ex) {
Logger.getLogger(BaseDBTestCase.class.getName()).log(Level.FINEST, null, ex); LoggerFactory.getLogger(BaseDBTestCase.class).trace("", ex);
} }
} }
} }
@@ -101,14 +100,14 @@ public abstract class BaseDBTestCase extends BaseTest {
zin.close(); zin.close();
} }
} catch (Throwable ex) { } catch (Throwable ex) {
Logger.getLogger(BaseDBTestCase.class.getName()).log(Level.FINEST, null, ex); LoggerFactory.getLogger(BaseDBTestCase.class).trace("", ex);
} }
try { try {
if (fis != null) { if (fis != null) {
fis.close(); fis.close();
} }
} catch (Throwable ex) { } catch (Throwable ex) {
Logger.getLogger(BaseDBTestCase.class.getName()).log(Level.FINEST, null, ex); LoggerFactory.getLogger(BaseDBTestCase.class).trace("", ex);
} }
} }
} }

View File

@@ -25,8 +25,6 @@ import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.Set; import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.LifecyclePhase;
@@ -54,12 +52,6 @@ import org.owasp.dependencycheck.utils.Settings;
requiresOnline = true requiresOnline = true
) )
public class AggregateMojo extends BaseDependencyCheckMojo { public class AggregateMojo extends BaseDependencyCheckMojo {
/**
* Logger field reference.
*/
private static final Logger LOGGER = Logger.getLogger(AggregateMojo.class.getName());
/** /**
* Executes the aggregate dependency-check goal. This runs dependency-check and generates the subsequent reports. * Executes the aggregate dependency-check goal. This runs dependency-check and generates the subsequent reports.
* *
@@ -76,7 +68,9 @@ public class AggregateMojo extends BaseDependencyCheckMojo {
for (MavenProject current : getReactorProjects()) { for (MavenProject current : getReactorProjects()) {
final File dataFile = getDataFile(current); final File dataFile = getDataFile(current);
if (dataFile == null) { //dc was never run on this project. write the ser to the target. if (dataFile == null) { //dc was never run on this project. write the ser to the target.
LOGGER.fine(String.format("Executing dependency-check on %s", current.getName())); if (getLog().isDebugEnabled()) {
getLog().debug(String.format("Executing dependency-check on %s", current.getName()));
}
generateDataFile(engine, current); generateDataFile(engine, current);
} }
} }
@@ -90,22 +84,32 @@ public class AggregateMojo extends BaseDependencyCheckMojo {
for (MavenProject reportOn : childProjects) { for (MavenProject reportOn : childProjects) {
final List<Dependency> childDeps = readDataFile(reportOn); final List<Dependency> childDeps = readDataFile(reportOn);
if (childDeps != null && !childDeps.isEmpty()) { if (childDeps != null && !childDeps.isEmpty()) {
LOGGER.fine(String.format("Adding %d dependencies from %s", childDeps.size(), reportOn.getName())); if (getLog().isDebugEnabled()) {
getLog().debug(String.format("Adding %d dependencies from %s", childDeps.size(), reportOn.getName()));
}
dependencies.addAll(childDeps); dependencies.addAll(childDeps);
} else { } else {
LOGGER.fine(String.format("No dependencies read for %s", reportOn.getName())); if (getLog().isDebugEnabled()) {
getLog().debug(String.format("No dependencies read for %s", reportOn.getName()));
}
} }
} }
engine.getDependencies().clear(); engine.getDependencies().clear();
engine.getDependencies().addAll(dependencies); engine.getDependencies().addAll(dependencies);
final DependencyBundlingAnalyzer bundler = new DependencyBundlingAnalyzer(); final DependencyBundlingAnalyzer bundler = new DependencyBundlingAnalyzer();
try { try {
LOGGER.fine(String.format("Dependency count pre-bundler: %s", engine.getDependencies().size())); if (getLog().isDebugEnabled()) {
getLog().debug(String.format("Dependency count pre-bundler: %s", engine.getDependencies().size()));
}
bundler.analyze(null, engine); bundler.analyze(null, engine);
LOGGER.fine(String.format("Dependency count post-bundler: %s", engine.getDependencies().size())); if (getLog().isDebugEnabled()) {
getLog().debug(String.format("Dependency count post-bundler: %s", engine.getDependencies().size()));
}
} catch (AnalysisException ex) { } catch (AnalysisException ex) {
LOGGER.log(Level.WARNING, "An error occured grouping the dependencies; duplicate entries may exist in the report", ex); getLog().warn("An error occured grouping the dependencies; duplicate entries may exist in the report", ex);
LOGGER.log(Level.FINE, "Bundling Exception", ex); if (getLog().isDebugEnabled()) {
getLog().debug("Bundling Exception", ex);
}
} }
File outputDir = getCorrectOutputDirectory(current); File outputDir = getCorrectOutputDirectory(current);
@@ -133,17 +137,23 @@ public class AggregateMojo extends BaseDependencyCheckMojo {
} }
final Set<MavenProject> descendants = new HashSet<MavenProject>(); final Set<MavenProject> descendants = new HashSet<MavenProject>();
int size = 0; int size = 0;
LOGGER.fine(String.format("Collecting descendants of %s", project.getName())); if (getLog().isDebugEnabled()) {
getLog().debug(String.format("Collecting descendants of %s", project.getName()));
}
for (String m : project.getModules()) { for (String m : project.getModules()) {
for (MavenProject mod : getReactorProjects()) { for (MavenProject mod : getReactorProjects()) {
try { try {
File mpp = new File(project.getBasedir(), m); File mpp = new File(project.getBasedir(), m);
mpp = mpp.getCanonicalFile(); mpp = mpp.getCanonicalFile();
if (mpp.compareTo(mod.getBasedir()) == 0 && descendants.add(mod)) { if (mpp.compareTo(mod.getBasedir()) == 0 && descendants.add(mod)) {
LOGGER.fine(String.format("Decendent module %s added", mod.getName())); if (getLog().isDebugEnabled()) {
getLog().debug(String.format("Decendent module %s added", mod.getName()));
};
} }
} catch (IOException ex) { } catch (IOException ex) {
LOGGER.log(Level.FINE, "Unable to determine module path", ex); if (getLog().isDebugEnabled()) {
getLog().debug("Unable to determine module path", ex);
}
} }
} }
} }
@@ -152,12 +162,16 @@ public class AggregateMojo extends BaseDependencyCheckMojo {
for (MavenProject p : getReactorProjects()) { for (MavenProject p : getReactorProjects()) {
if (project.equals(p.getParent()) || descendants.contains(p.getParent())) { if (project.equals(p.getParent()) || descendants.contains(p.getParent())) {
if (descendants.add(p)) { if (descendants.add(p)) {
LOGGER.fine(String.format("Decendent %s added", p.getName())); if (getLog().isDebugEnabled()) {
getLog().debug(String.format("Decendent %s added", p.getName()));
}
} }
for (MavenProject modTest : getReactorProjects()) { for (MavenProject modTest : getReactorProjects()) {
if (p.getModules() != null && p.getModules().contains(modTest.getName()) if (p.getModules() != null && p.getModules().contains(modTest.getName())
&& descendants.add(modTest)) { && descendants.add(modTest)) {
LOGGER.fine(String.format("Decendent %s added", modTest.getName())); if (getLog().isDebugEnabled()) {
getLog().debug(String.format("Decendent %s added", modTest.getName()));
}
} }
} }
} }
@@ -167,16 +181,22 @@ public class AggregateMojo extends BaseDependencyCheckMojo {
File mpp = new File(dec.getBasedir(), mod); File mpp = new File(dec.getBasedir(), mod);
mpp = mpp.getCanonicalFile(); mpp = mpp.getCanonicalFile();
if (mpp.compareTo(p.getBasedir()) == 0 && descendants.add(p)) { if (mpp.compareTo(p.getBasedir()) == 0 && descendants.add(p)) {
LOGGER.fine(String.format("Decendent module %s added", p.getName())); if (getLog().isDebugEnabled()) {
getLog().debug(String.format("Decendent module %s added", p.getName()));
}
} }
} catch (IOException ex) { } catch (IOException ex) {
LOGGER.log(Level.FINE, "Unable to determine module path", ex); if (getLog().isDebugEnabled()) {
getLog().debug("Unable to determine module path", ex);
}
} }
} }
} }
} }
} while (size != 0 && size != descendants.size()); } while (size != 0 && size != descendants.size());
LOGGER.fine(String.format("%s has %d children", project, descendants.size())); if (getLog().isDebugEnabled()) {
getLog().debug(String.format("%s has %d children", project, descendants.size()));
}
return descendants; return descendants;
} }
@@ -202,7 +222,9 @@ public class AggregateMojo extends BaseDependencyCheckMojo {
try { try {
engine = initializeEngine(); engine = initializeEngine();
} catch (DatabaseException ex) { } catch (DatabaseException ex) {
LOGGER.log(Level.FINE, "Database connection error", ex); if (getLog().isDebugEnabled()) {
getLog().debug("Database connection error", ex);
}
throw new MojoExecutionException("An exception occured connecting to the local database. Please see the log file for more details.", ex); throw new MojoExecutionException("An exception occured connecting to the local database. Please see the log file for more details.", ex);
} }
return generateDataFile(engine, getProject()); return generateDataFile(engine, getProject());
@@ -218,7 +240,9 @@ public class AggregateMojo extends BaseDependencyCheckMojo {
* @throws MojoFailureException thrown if dependency-check is configured to fail the build if severe CVEs are identified. * @throws MojoFailureException thrown if dependency-check is configured to fail the build if severe CVEs are identified.
*/ */
protected Engine generateDataFile(Engine engine, MavenProject project) throws MojoExecutionException, MojoFailureException { protected Engine generateDataFile(Engine engine, MavenProject project) throws MojoExecutionException, MojoFailureException {
LOGGER.fine(String.format("Begin Scanning: %s", project.getName())); if (getLog().isDebugEnabled()) {
getLog().debug(String.format("Begin Scanning: %s", project.getName()));
}
engine.getDependencies().clear(); engine.getDependencies().clear();
engine.resetFileTypeAnalyzers(); engine.resetFileTypeAnalyzers();
scanArtifacts(project, engine); scanArtifacts(project, engine);

View File

@@ -29,8 +29,6 @@ import java.io.ObjectOutputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.metadata.ArtifactMetadataRetrievalException; import org.apache.maven.artifact.metadata.ArtifactMetadataRetrievalException;
import org.apache.maven.artifact.metadata.ArtifactMetadataSource; import org.apache.maven.artifact.metadata.ArtifactMetadataSource;
@@ -66,10 +64,6 @@ import org.owasp.dependencycheck.utils.Settings;
public abstract class BaseDependencyCheckMojo extends AbstractMojo implements MavenReport { public abstract class BaseDependencyCheckMojo extends AbstractMojo implements MavenReport {
//<editor-fold defaultstate="collapsed" desc="Private fields"> //<editor-fold defaultstate="collapsed" desc="Private fields">
/**
* Logger field reference.
*/
private static final Logger LOGGER = Logger.getLogger(BaseDependencyCheckMojo.class.getName());
/** /**
* The properties file location. * The properties file location.
*/ */
@@ -407,7 +401,7 @@ public abstract class BaseDependencyCheckMojo extends AbstractMojo implements Ma
} catch (MojoExecutionException ex) { } catch (MojoExecutionException ex) {
throw new MavenReportException(ex.getMessage(), ex); throw new MavenReportException(ex.getMessage(), ex);
} catch (MojoFailureException ex) { } catch (MojoFailureException ex) {
LOGGER.warning("Vulnerabilities were identifies that exceed the CVSS threshold for failing the build"); getLog().warn("Vulnerabilities were identifies that exceed the CVSS threshold for failing the build");
} }
} }
@@ -446,14 +440,18 @@ public abstract class BaseDependencyCheckMojo extends AbstractMojo implements Ma
* @return the directory to write the report(s) * @return the directory to write the report(s)
*/ */
protected File getDataFile(MavenProject current) { protected File getDataFile(MavenProject current) {
LOGGER.fine(String.format("Getting data filefor %s using key '%s'", current.getName(), getDataFileContextKey())); if (getLog().isDebugEnabled()) {
getLog().debug(String.format("Getting data filefor %s using key '%s'", current.getName(), getDataFileContextKey()));
}
final Object obj = current.getContextValue(getDataFileContextKey()); final Object obj = current.getContextValue(getDataFileContextKey());
if (obj != null) { if (obj != null) {
if (obj instanceof File) { if (obj instanceof File) {
return (File) obj; return (File) obj;
} }
} else { } else {
LOGGER.fine("Context value not found"); if (getLog().isDebugEnabled()) {
getLog().debug("Context value not found");
}
} }
return null; return null;
} }
@@ -477,8 +475,10 @@ public abstract class BaseDependencyCheckMojo extends AbstractMojo implements Ma
final MavenArtifact ma = new MavenArtifact(a.getGroupId(), a.getArtifactId(), a.getVersion()); final MavenArtifact ma = new MavenArtifact(a.getGroupId(), a.getArtifactId(), a.getVersion());
d.addAsEvidence("pom", ma, Confidence.HIGHEST); d.addAsEvidence("pom", ma, Confidence.HIGHEST);
d.addProjectReference(project.getName()); d.addProjectReference(project.getName());
LOGGER.fine(String.format("Adding project reference %s on dependency %s", project.getName(), if (getLog().isDebugEnabled()) {
getLog().debug(String.format("Adding project reference %s on dependency %s", project.getName(),
d.getDisplayFileName())); d.getDisplayFileName()));
}
if (metadataSource != null) { if (metadataSource != null) {
try { try {
final DependencyVersion currentVersion = new DependencyVersion(a.getVersion()); final DependencyVersion currentVersion = new DependencyVersion(a.getVersion());
@@ -491,20 +491,26 @@ public abstract class BaseDependencyCheckMojo extends AbstractMojo implements Ma
} }
} }
} catch (ArtifactMetadataRetrievalException ex) { } catch (ArtifactMetadataRetrievalException ex) {
LOGGER.log(Level.WARNING, getLog().warn(
"Unable to check for new versions of dependencies; see the log for more details."); "Unable to check for new versions of dependencies; see the log for more details.");
LOGGER.log(Level.FINE, null, ex); if (getLog().isDebugEnabled()) {
getLog().debug("", ex);
}
} catch (Throwable t) { } catch (Throwable t) {
LOGGER.log(Level.WARNING, getLog().warn(
"Unexpected error occured checking for new versions; see the log for more details."); "Unexpected error occured checking for new versions; see the log for more details.");
LOGGER.log(Level.FINE, "", t); if (getLog().isDebugEnabled()) {
getLog().debug("", t);
}
} }
} }
} }
} else { } else {
if (getLog().isDebugEnabled()) {
final String msg = String.format("More then 1 dependency was identified in first pass scan of '%s:%s:%s'", final String msg = String.format("More then 1 dependency was identified in first pass scan of '%s:%s:%s'",
a.getGroupId(), a.getArtifactId(), a.getVersion()); a.getGroupId(), a.getArtifactId(), a.getVersion());
LOGGER.fine(msg); getLog().debug(msg);
}
} }
} }
} }
@@ -570,7 +576,7 @@ public abstract class BaseDependencyCheckMojo extends AbstractMojo implements Ma
} else if ("VULN".equalsIgnoreCase(this.format)) { } else if ("VULN".equalsIgnoreCase(this.format)) {
return "dependency-check-vulnerability"; return "dependency-check-vulnerability";
} else { } else {
LOGGER.log(Level.WARNING, "Unknown report format used during site generation."); getLog().warn("Unknown report format used during site generation.");
return "dependency-check-report"; return "dependency-check-report";
} }
} }
@@ -613,26 +619,30 @@ public abstract class BaseDependencyCheckMojo extends AbstractMojo implements Ma
mojoProperties = this.getClass().getClassLoader().getResourceAsStream(PROPERTIES_FILE); mojoProperties = this.getClass().getClassLoader().getResourceAsStream(PROPERTIES_FILE);
Settings.mergeProperties(mojoProperties); Settings.mergeProperties(mojoProperties);
} catch (IOException ex) { } catch (IOException ex) {
LOGGER.log(Level.WARNING, "Unable to load the dependency-check ant task.properties file."); getLog().warn("Unable to load the dependency-check ant task.properties file.");
LOGGER.log(Level.FINE, null, ex); if (getLog().isDebugEnabled()) {
getLog().debug("", ex);
}
} finally { } finally {
if (mojoProperties != null) { if (mojoProperties != null) {
try { try {
mojoProperties.close(); mojoProperties.close();
} catch (IOException ex) { } catch (IOException ex) {
LOGGER.log(Level.FINEST, null, ex); if (getLog().isDebugEnabled()) {
getLog().debug("", ex);
}
} }
} }
} }
Settings.setBoolean(Settings.KEYS.AUTO_UPDATE, autoUpdate); Settings.setBoolean(Settings.KEYS.AUTO_UPDATE, autoUpdate);
if (externalReport != null) { if (externalReport != null) {
LOGGER.warning("The 'externalReport' option was set; this configuration option has been removed. " getLog().warn("The 'externalReport' option was set; this configuration option has been removed. "
+ "Please update the dependency-check-maven plugin's configuration"); + "Please update the dependency-check-maven plugin's configuration");
} }
if (proxyUrl != null && !proxyUrl.isEmpty()) { if (proxyUrl != null && !proxyUrl.isEmpty()) {
LOGGER.warning("Deprecated configuration detected, proxyUrl will be ignored; use the maven settings " + "to configure the proxy instead"); getLog().warn("Deprecated configuration detected, proxyUrl will be ignored; use the maven settings " + "to configure the proxy instead");
} }
final Proxy proxy = getMavenProxy(); final Proxy proxy = getMavenProxy();
if (proxy != null) { if (proxy != null) {
@@ -739,7 +749,7 @@ public abstract class BaseDependencyCheckMojo extends AbstractMojo implements Ma
} else if (proxies.size() == 1) { } else if (proxies.size() == 1) {
return proxies.get(0); return proxies.get(0);
} else { } else {
LOGGER.warning("Multiple proxy definitions exist in the Maven settings. In the dependency-check " getLog().warn("Multiple proxy definitions exist in the Maven settings. In the dependency-check "
+ "configuration set the mavenSettingsProxyId so that the correct proxy will be used."); + "configuration set the mavenSettingsProxyId so that the correct proxy will be used.");
throw new IllegalStateException("Ambiguous proxy definition"); throw new IllegalStateException("Ambiguous proxy definition");
} }
@@ -812,7 +822,9 @@ public abstract class BaseDependencyCheckMojo extends AbstractMojo implements Ma
cve.open(); cve.open();
prop = cve.getDatabaseProperties(); prop = cve.getDatabaseProperties();
} catch (DatabaseException ex) { } catch (DatabaseException ex) {
LOGGER.log(Level.FINE, "Unable to retrieve DB Properties", ex); if (getLog().isDebugEnabled()) {
getLog().debug("Unable to retrieve DB Properties", ex);
}
} finally { } finally {
if (cve != null) { if (cve != null) {
cve.close(); cve.close();
@@ -822,13 +834,17 @@ public abstract class BaseDependencyCheckMojo extends AbstractMojo implements Ma
try { try {
r.generateReports(outputDir.getAbsolutePath(), format); r.generateReports(outputDir.getAbsolutePath(), format);
} catch (IOException ex) { } catch (IOException ex) {
LOGGER.log(Level.SEVERE, getLog().error(
"Unexpected exception occurred during analysis; please see the verbose error log for more details."); "Unexpected exception occurred during analysis; please see the verbose error log for more details.");
LOGGER.log(Level.FINE, null, ex); if (getLog().isDebugEnabled()) {
getLog().debug("", ex);
}
} catch (Throwable ex) { } catch (Throwable ex) {
LOGGER.log(Level.SEVERE, getLog().error(
"Unexpected exception occurred during analysis; please see the verbose error log for more details."); "Unexpected exception occurred during analysis; please see the verbose error log for more details.");
LOGGER.log(Level.FINE, null, ex); if (getLog().isDebugEnabled()) {
getLog().debug("", ex);
}
} }
} }
@@ -903,7 +919,7 @@ public abstract class BaseDependencyCheckMojo extends AbstractMojo implements Ma
if (summary.length() > 0) { if (summary.length() > 0) {
final String msg = String.format("%n%n" + "One or more dependencies were identified with known vulnerabilities in %s:%n%n%s" final String msg = String.format("%n%n" + "One or more dependencies were identified with known vulnerabilities in %s:%n%n%s"
+ "%n%nSee the dependency-check report for more details.%n%n", mp.getName(), summary.toString()); + "%n%nSee the dependency-check report for more details.%n%n", mp.getName(), summary.toString());
LOGGER.log(Level.WARNING, msg); getLog().warn(msg);
} }
} }
} }
@@ -962,33 +978,43 @@ public abstract class BaseDependencyCheckMojo extends AbstractMojo implements Ma
//https://www.securecoding.cert.org/confluence/display/java/SER10-J.+Avoid+memory+and+resource+leaks+during+serialization //https://www.securecoding.cert.org/confluence/display/java/SER10-J.+Avoid+memory+and+resource+leaks+during+serialization
out.reset(); out.reset();
} }
LOGGER.fine(String.format("Serialized data file written to '%s' for %s, referenced by key %s", if (getLog().isDebugEnabled()) {
getLog().debug(String.format("Serialized data file written to '%s' for %s, referenced by key %s",
file.getAbsolutePath(), mp.getName(), this.getDataFileContextKey())); file.getAbsolutePath(), mp.getName(), this.getDataFileContextKey()));
}
mp.setContextValue(this.getDataFileContextKey(), file.getAbsolutePath()); mp.setContextValue(this.getDataFileContextKey(), file.getAbsolutePath());
} catch (IOException ex) { } catch (IOException ex) {
LOGGER.log(Level.WARNING, "Unable to create data file used for report aggregation; " getLog().warn("Unable to create data file used for report aggregation; "
+ "if report aggregation is being used the results may be incomplete."); + "if report aggregation is being used the results may be incomplete.");
LOGGER.log(Level.FINE, ex.getMessage(), ex); if (getLog().isDebugEnabled()) {
getLog().debug(ex.getMessage(), ex);
}
} finally { } finally {
if (out != null) { if (out != null) {
try { try {
out.close(); out.close();
} catch (IOException ex) { } catch (IOException ex) {
LOGGER.log(Level.FINEST, "ignore", ex); if (getLog().isDebugEnabled()) {
getLog().debug("ignore", ex);
}
} }
} }
if (bos != null) { if (bos != null) {
try { try {
bos.close(); bos.close();
} catch (IOException ex) { } catch (IOException ex) {
LOGGER.log(Level.FINEST, "ignore", ex); if (getLog().isDebugEnabled()) {
getLog().debug("ignore", ex);
}
} }
} }
if (os != null) { if (os != null) {
try { try {
os.close(); os.close();
} catch (IOException ex) { } catch (IOException ex) {
LOGGER.log(Level.FINEST, "ignore", ex); if (getLog().isDebugEnabled()) {
getLog().debug("ignore", ex);
}
} }
} }
} }
@@ -1016,17 +1042,17 @@ public abstract class BaseDependencyCheckMojo extends AbstractMojo implements Ma
ret = (List<Dependency>) ois.readObject(); ret = (List<Dependency>) ois.readObject();
} catch (FileNotFoundException ex) { } catch (FileNotFoundException ex) {
//TODO fix logging //TODO fix logging
LOGGER.log(Level.SEVERE, null, ex); getLog().error("", ex);
} catch (IOException ex) { } catch (IOException ex) {
LOGGER.log(Level.SEVERE, null, ex); getLog().error("", ex);
} catch (ClassNotFoundException ex) { } catch (ClassNotFoundException ex) {
LOGGER.log(Level.SEVERE, null, ex); getLog().error("", ex);
} finally { } finally {
if (ois != null) { if (ois != null) {
try { try {
ois.close(); ois.close();
} catch (IOException ex) { } catch (IOException ex) {
LOGGER.log(Level.SEVERE, null, ex); getLog().error("", ex);
} }
} }
} }

View File

@@ -18,8 +18,6 @@
package org.owasp.dependencycheck.maven; package org.owasp.dependencycheck.maven;
import java.util.Locale; import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.Artifact;
import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugin.MojoFailureException;
@@ -43,11 +41,6 @@ import org.owasp.dependencycheck.utils.Settings;
) )
public class CheckMojo extends BaseDependencyCheckMojo { public class CheckMojo extends BaseDependencyCheckMojo {
/**
* Logger field reference.
*/
private static final Logger LOGGER = Logger.getLogger(CheckMojo.class.getName());
/** /**
* Returns whether or not a the report can be generated. * Returns whether or not a the report can be generated.
* *
@@ -77,12 +70,14 @@ public class CheckMojo extends BaseDependencyCheckMojo {
try { try {
engine = initializeEngine(); engine = initializeEngine();
} catch (DatabaseException ex) { } catch (DatabaseException ex) {
LOGGER.log(Level.FINE, "Database connection error", ex); if (getLog().isDebugEnabled()) {
getLog().debug("Database connection error", ex);
}
throw new MojoExecutionException("An exception occured connecting to the local database. Please see the log file for more details.", ex); throw new MojoExecutionException("An exception occured connecting to the local database. Please see the log file for more details.", ex);
} }
scanArtifacts(getProject(), engine); scanArtifacts(getProject(), engine);
if (engine.getDependencies().isEmpty()) { if (engine.getDependencies().isEmpty()) {
LOGGER.info("No dependencies were identified that could be analyzed by dependency-check"); getLog().info("No dependencies were identified that could be analyzed by dependency-check");
} else { } else {
engine.analyzeDependencies(); engine.analyzeDependencies();
writeReports(engine, getProject(), getCorrectOutputDirectory()); writeReports(engine, getProject(), getCorrectOutputDirectory());

View File

@@ -18,13 +18,14 @@
package org.owasp.dependencycheck.maven; package org.owasp.dependencycheck.maven;
import java.util.List; import java.util.List;
import java.util.logging.Logger;
import org.apache.maven.project.MavenProject; import org.apache.maven.project.MavenProject;
import org.owasp.dependencycheck.analyzer.Analyzer; import org.owasp.dependencycheck.analyzer.Analyzer;
import org.owasp.dependencycheck.analyzer.CPEAnalyzer; import org.owasp.dependencycheck.analyzer.CPEAnalyzer;
import org.owasp.dependencycheck.analyzer.FileTypeAnalyzer; import org.owasp.dependencycheck.analyzer.FileTypeAnalyzer;
import org.owasp.dependencycheck.data.nvdcve.DatabaseException; import org.owasp.dependencycheck.data.nvdcve.DatabaseException;
import org.owasp.dependencycheck.utils.Settings; import org.owasp.dependencycheck.utils.Settings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* A modified version of the core engine specifically designed to persist some data between multiple executions of a multi-module * A modified version of the core engine specifically designed to persist some data between multiple executions of a multi-module
@@ -37,7 +38,7 @@ public class Engine extends org.owasp.dependencycheck.Engine {
/** /**
* The logger. * The logger.
*/ */
private static final transient Logger LOGGER = Logger.getLogger(Engine.class.getName()); private static final transient Logger LOGGER = LoggerFactory.getLogger(Engine.class);
/** /**
* A key used to persist an object in the MavenProject. * A key used to persist an object in the MavenProject.
*/ */
@@ -75,9 +76,9 @@ public class Engine extends org.owasp.dependencycheck.Engine {
public void analyzeDependencies() { public void analyzeDependencies() {
final MavenProject root = getExecutionRoot(); final MavenProject root = getExecutionRoot();
if (root != null) { if (root != null) {
LOGGER.fine(String.format("Checking root project, %s, if updates have already been completed", root.getArtifactId())); LOGGER.debug("Checking root project, {}, if updates have already been completed", root.getArtifactId());
} else { } else {
LOGGER.fine("Checking root project, null, if updates have already been completed"); LOGGER.debug("Checking root project, null, if updates have already been completed");
} }
if (root != null && root.getContextValue(UPDATE_EXECUTED_FLAG) != null) { if (root != null && root.getContextValue(UPDATE_EXECUTED_FLAG) != null) {
System.setProperty(Settings.KEYS.AUTO_UPDATE, Boolean.FALSE.toString()); System.setProperty(Settings.KEYS.AUTO_UPDATE, Boolean.FALSE.toString());

View File

@@ -0,0 +1,320 @@
/*
* This file is part of dependency-check-ant.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright (c) 2013 Jeremy Long. All Rights Reserved.
*/
package org.owasp.dependencycheck.maven;
import org.apache.maven.plugin.logging.Log;
import org.slf4j.helpers.FormattingTuple;
import org.slf4j.helpers.MarkerIgnoringBase;
import org.slf4j.helpers.MessageFormatter;
/**
* Created by colezlaw on 6/14/15.
*/
public class MavenLoggerAdapter extends MarkerIgnoringBase {
private Log log;
public MavenLoggerAdapter(Log log) {
super();
this.log = log;
}
@Override
public boolean isTraceEnabled() {
if (log != null) {
return log.isDebugEnabled();
}
return true;
}
@Override
public void trace(String msg) {
if (log != null) {
log.debug(msg);
} else {
System.out.println(msg);
}
}
@Override
public void trace(String format, Object arg) {
String message = MessageFormatter.format(format, arg).getMessage();
if (log != null) {
log.debug(message);
} else {
System.out.println(message);
}
}
@Override
public void trace(String format, Object arg1, Object arg2) {
String message = MessageFormatter.format(format, arg1, arg2).getMessage();
if (log != null) {
log.debug(message);
} else {
System.out.println(message);
}
}
@Override
public void trace(String format, Object... arguments) {
String message = MessageFormatter.format(format, arguments).getMessage();
if (log != null) {
log.debug(message);
} else {
System.out.println(message);
}
}
@Override
public void trace(String msg, Throwable t) {
if (log != null) {
log.debug(msg, t);
} else {
System.out.println(msg);
t.printStackTrace();
}
}
@Override
public boolean isDebugEnabled() {
if (log != null) {
return log.isDebugEnabled();
}
return true;
}
@Override
public void debug(String msg) {
if (log != null) {
log.debug(msg);
} else {
System.out.println(msg);
}
}
@Override
public void debug(String format, Object arg) {
String message = MessageFormatter.format(format, arg).getMessage();
if (log != null) {
log.debug(message);
} else {
System.out.println(message);
}
}
@Override
public void debug(String format, Object arg1, Object arg2) {
String message = MessageFormatter.format(format, arg1, arg2).getMessage();
if (log != null) {
log.debug(message);
} else {
System.out.println(message);
}
}
@Override
public void debug(String format, Object... arguments) {
String message = MessageFormatter.format(format, arguments).getMessage();
if (log != null) {
log.debug(message);
} else {
System.out.println(message);
}
}
@Override
public void debug(String msg, Throwable t) {
if (log != null) {
log.debug(msg, t);
} else {
System.out.println(msg);
t.printStackTrace();
}
}
@Override
public boolean isInfoEnabled() {
if (log != null) {
return log.isInfoEnabled();
}
return true;
}
@Override
public void info(String msg) {
if (log != null) {
log.info(msg);
} else {
System.out.println(msg);
}
}
@Override
public void info(String format, Object arg) {
String message = MessageFormatter.format(format, arg).getMessage();
if (log != null) {
log.info(message);
} else {
System.out.println(message);
}
}
@Override
public void info(String format, Object arg1, Object arg2) {
String message = MessageFormatter.format(format, arg1, arg2).getMessage();
if (log != null) {
log.info(message);
} else {
System.out.println(message);
}
}
@Override
public void info(String format, Object... arguments) {
String message = MessageFormatter.format(format, arguments).getMessage();
if (log != null) {
log.info(message);
} else {
System.out.println(message);
}
}
@Override
public void info(String msg, Throwable t) {
if (log != null) {
log.info(msg, t);
} else {
System.out.println(msg);
t.printStackTrace();
}
}
@Override
public boolean isWarnEnabled() {
if (log != null) {
return log.isWarnEnabled();
}
return true;
}
@Override
public void warn(String msg) {
if (log != null) {
log.warn(msg);
} else {
System.out.println(msg);
}
}
@Override
public void warn(String format, Object arg) {
String message = MessageFormatter.format(format, arg).getMessage();
if (log != null) {
log.warn(message);
} else {
System.out.println(message);
}
}
@Override
public void warn(String format, Object arg1, Object arg2) {
String message = MessageFormatter.format(format, arg1, arg2).getMessage();
if (log != null) {
log.warn(message);
} else {
System.out.println(message);
}
}
@Override
public void warn(String format, Object... arguments) {
String message = MessageFormatter.format(format, arguments).getMessage();
if (log != null) {
log.warn(message);
} else {
System.out.println(message);
}
}
@Override
public void warn(String msg, Throwable t) {
if (log != null) {
log.warn(msg, t);
} else {
System.out.println(msg);
t.printStackTrace();
}
}
@Override
public boolean isErrorEnabled() {
if (log != null) {
return log.isErrorEnabled();
}
return true;
}
@Override
public void error(String msg) {
if (log != null) {
log.error(msg);
} else {
System.out.println(msg);
}
}
@Override
public void error(String format, Object arg) {
String message = MessageFormatter.format(format, arg).getMessage();
if (log != null) {
log.error(message);
} else {
System.out.println(message);
}
}
@Override
public void error(String format, Object arg1, Object arg2) {
String message = MessageFormatter.format(format, arg1, arg2).getMessage();
if (log != null) {
log.error(message);
} else {
System.out.println(message);
}
}
@Override
public void error(String format, Object... arguments) {
String message = MessageFormatter.format(format, arguments).getMessage();
if (log != null) {
log.error(message);
} else {
System.out.println(message);
}
}
@Override
public void error(String msg, Throwable t) {
if (log != null) {
log.error(msg, t);
} else {
System.out.println(msg);
t.printStackTrace();
}
}
}

View File

@@ -0,0 +1,38 @@
/*
* This file is part of dependency-check-ant.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright (c) 2013 Jeremy Long. All Rights Reserved.
*/
package org.owasp.dependencycheck.maven;
import org.apache.maven.plugin.logging.Log;
import org.slf4j.ILoggerFactory;
import org.slf4j.Logger;
/**
* Created by colezlaw on 6/14/15.
*/
public class MavenLoggerFactory implements ILoggerFactory {
private MavenLoggerAdapter mavenLoggerAdapter;
public MavenLoggerFactory(Log log) {
super();
this.mavenLoggerAdapter = new MavenLoggerAdapter(log);
}
public Logger getLogger(String name) {
return mavenLoggerAdapter;
}
}

View File

@@ -18,8 +18,6 @@
package org.owasp.dependencycheck.maven; package org.owasp.dependencycheck.maven;
import java.util.Locale; import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.LifecyclePhase;
@@ -42,11 +40,6 @@ import org.owasp.dependencycheck.utils.Settings;
) )
public class UpdateMojo extends BaseDependencyCheckMojo { public class UpdateMojo extends BaseDependencyCheckMojo {
/**
* Logger field reference.
*/
private static final Logger LOGGER = Logger.getLogger(UpdateMojo.class.getName());
/** /**
* Returns false; this mojo cannot generate a report. * Returns false; this mojo cannot generate a report.
* *
@@ -70,7 +63,9 @@ public class UpdateMojo extends BaseDependencyCheckMojo {
engine = initializeEngine(); engine = initializeEngine();
engine.update(); engine.update();
} catch (DatabaseException ex) { } catch (DatabaseException ex) {
LOGGER.log(Level.FINE, "Database connection error", ex); if (getLog().isDebugEnabled()) {
getLog().debug("Database connection error", ex);
}
throw new MojoExecutionException("An exception occured connecting to the local database. Please see the log file for more details.", ex); throw new MojoExecutionException("An exception occured connecting to the local database. Please see the log file for more details.", ex);
} }
engine.cleanup(); engine.cleanup();

View File

@@ -0,0 +1,88 @@
/*
* This file is part of dependency-check-ant.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright (c) 2013 Jeremy Long. All Rights Reserved.
*/
package org.slf4j.impl;
import org.apache.maven.plugin.logging.Log;
import org.owasp.dependencycheck.maven.MavenLoggerFactory;
import org.slf4j.ILoggerFactory;
import org.slf4j.spi.LoggerFactoryBinder;
/**
* The binding of {@link org.slf4j.LoggerFactory} class with an actual instance of
* {@link ILoggerFactory} is performed using information returned by this class.
*
* @author colezlaw
*/
public class StaticLoggerBinder implements LoggerFactoryBinder {
/**
* The unique instance of this class
*
*/
private static final StaticLoggerBinder SINGLETON = new StaticLoggerBinder();
/**
* Return the singleton of this class.
*
* @return the StaticLoggerBinder singleton
*/
public static final StaticLoggerBinder getSingleton() {
return SINGLETON;
}
/**
* Maven mojos have their own logger, so we'll use one of those
*/
private Log log;
/**
* Set the Task which will this is to log through.
*
* @param log the task through which to log
*/
public void setLog(Log log) {
this.log = log;
loggerFactory = new MavenLoggerFactory(log);
}
/**
* Declare the version of the SLF4J API this implementation is compiled
* against. The value of this filed is usually modified with each release.
*/
// to avoid constant folding by the compiler, this field must *not* be final
public static String REQUESTED_API_VERSION = "1.7.12"; // final
private static final String loggerFactoryClassStr = MavenLoggerFactory.class.getName();
/**
* The ILoggerFactory instance returned by the {@link #getLoggerFactory}
* method should always be the smae object
*/
private ILoggerFactory loggerFactory;
private StaticLoggerBinder() {
loggerFactory = new MavenLoggerFactory(log);
}
public ILoggerFactory getLoggerFactory() {
return loggerFactory;
}
public String getLoggerFactoryClassStr() {
return loggerFactoryClassStr;
}
}

View File

@@ -224,5 +224,16 @@ Copyright (c) 2014 - Jeremy Long. All Rights Reserved.
<groupId>commons-io</groupId> <groupId>commons-io</groupId>
<artifactId>commons-io</artifactId> <artifactId>commons-io</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
</project> </project>

View File

@@ -17,6 +17,9 @@
*/ */
package org.owasp.dependencycheck.utils; package org.owasp.dependencycheck.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
@@ -24,8 +27,6 @@ import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel; import java.nio.channels.FileChannel;
import java.security.MessageDigest; import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;
/** /**
* Includes methods to generate the MD5 and SHA1 checksum. * Includes methods to generate the MD5 and SHA1 checksum.
@@ -38,7 +39,7 @@ public final class Checksum {
/** /**
* The logger. * The logger.
*/ */
private static final Logger LOGGER = Logger.getLogger(Checksum.class.getName()); private static final Logger LOGGER = LoggerFactory.getLogger(Checksum.class);
/** /**
* Private constructor for a utility class. * Private constructor for a utility class.
@@ -89,7 +90,7 @@ public final class Checksum {
try { try {
fis.close(); fis.close();
} catch (IOException ex) { } catch (IOException ex) {
LOGGER.log(Level.FINEST, "Error closing file '" + file.getName() + "'.", ex); LOGGER.trace("Error closing file '{}'.", file.getName(), ex);
} }
} }
} }

View File

@@ -17,6 +17,9 @@
*/ */
package org.owasp.dependencycheck.utils; package org.owasp.dependencycheck.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedOutputStream; import java.io.BufferedOutputStream;
import java.io.File; import java.io.File;
import java.io.FileOutputStream; import java.io.FileOutputStream;
@@ -26,8 +29,6 @@ import java.net.HttpURLConnection;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.net.URL; import java.net.URL;
import java.security.InvalidAlgorithmParameterException; import java.security.InvalidAlgorithmParameterException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.GZIPInputStream; import java.util.zip.GZIPInputStream;
import java.util.zip.InflaterInputStream; import java.util.zip.InflaterInputStream;
@@ -41,7 +42,7 @@ public final class Downloader {
/** /**
* The logger. * The logger.
*/ */
private static final Logger LOGGER = Logger.getLogger(Downloader.class.getName()); private static final Logger LOGGER = LoggerFactory.getLogger(Downloader.class);
/** /**
* The maximum number of redirects that will be followed when attempting to download a file. * The maximum number of redirects that will be followed when attempting to download a file.
*/ */
@@ -95,7 +96,7 @@ public final class Downloader {
} else { } else {
HttpURLConnection conn = null; HttpURLConnection conn = null;
try { try {
LOGGER.fine(String.format("Attempting download of %s", url.toString())); LOGGER.debug("Attempting download of {}", url.toString());
conn = URLConnectionFactory.createHttpURLConnection(url, useProxy); conn = URLConnectionFactory.createHttpURLConnection(url, useProxy);
conn.setRequestProperty("Accept-Encoding", "gzip, deflate"); conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
conn.connect(); conn.connect();
@@ -111,7 +112,7 @@ public final class Downloader {
} finally { } finally {
conn = null; conn = null;
} }
LOGGER.fine(String.format("Download is being redirected from %s to %s", url.toString(), location)); LOGGER.debug("Download is being redirected from {} to {}", url.toString(), location);
conn = URLConnectionFactory.createHttpURLConnection(new URL(location), useProxy); conn = URLConnectionFactory.createHttpURLConnection(new URL(location), useProxy);
conn.setRequestProperty("Accept-Encoding", "gzip, deflate"); conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
conn.connect(); conn.connect();
@@ -157,7 +158,7 @@ public final class Downloader {
while ((bytesRead = reader.read(buffer)) > 0) { while ((bytesRead = reader.read(buffer)) > 0) {
writer.write(buffer, 0, bytesRead); writer.write(buffer, 0, bytesRead);
} }
LOGGER.fine(String.format("Download of %s complete", url.toString())); LOGGER.debug("Download of {} complete", url.toString());
} catch (IOException ex) { } catch (IOException ex) {
analyzeException(ex); analyzeException(ex);
final String msg = String.format("Error saving '%s' to file '%s'%nConnection Timeout: %d%nEncoding: %s%n", final String msg = String.format("Error saving '%s' to file '%s'%nConnection Timeout: %d%nEncoding: %s%n",
@@ -172,14 +173,14 @@ public final class Downloader {
try { try {
writer.close(); writer.close();
} catch (IOException ex) { } catch (IOException ex) {
LOGGER.log(Level.FINEST, "Error closing the writer in Downloader.", ex); LOGGER.trace("Error closing the writer in Downloader.", ex);
} }
} }
if (reader != null) { if (reader != null) {
try { try {
reader.close(); reader.close();
} catch (IOException ex) { } catch (IOException ex) {
LOGGER.log(Level.FINEST, "Error closing the reader in Downloader.", ex); LOGGER.trace("Error closing the reader in Downloader.", ex);
} }
} }
try { try {
@@ -258,8 +259,8 @@ public final class Downloader {
LOGGER.info("Error making HTTPS request - InvalidAlgorithmParameterException"); LOGGER.info("Error making HTTPS request - InvalidAlgorithmParameterException");
LOGGER.info("There appears to be an issue with the installation of Java and the cacerts." LOGGER.info("There appears to be an issue with the installation of Java and the cacerts."
+ "See closed issue #177 here: https://github.com/jeremylong/DependencyCheck/issues/177"); + "See closed issue #177 here: https://github.com/jeremylong/DependencyCheck/issues/177");
LOGGER.info(String.format("Java Info:%njavax.net.ssl.keyStore='%s'%njava.version='%s'%njava.vendor='%s'", LOGGER.info("Java Info:\njavax.net.ssl.keyStore='{}'\njava.version='{}'\njava.vendor='{}'",
keystore, version, vendor)); keystore, version, vendor);
throw new DownloadFailedException("Error making HTTPS request. Please see the log for more details."); throw new DownloadFailedException("Error making HTTPS request. Please see the log for more details.");
} }
cause = cause.getCause(); cause = cause.getCause();

View File

@@ -17,13 +17,14 @@
*/ */
package org.owasp.dependencycheck.utils; package org.owasp.dependencycheck.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.net.URLDecoder; import java.net.URLDecoder;
import java.util.UUID; import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
/** /**
* A collection of utilities for processing information about files. * A collection of utilities for processing information about files.
@@ -35,7 +36,7 @@ public final class FileUtils {
/** /**
* The logger. * The logger.
*/ */
private static final Logger LOGGER = Logger.getLogger(FileUtils.class.getName()); private static final Logger LOGGER = LoggerFactory.getLogger(FileUtils.class);
/** /**
* Bit bucket for non-Windows systems * Bit bucket for non-Windows systems
*/ */
@@ -77,8 +78,7 @@ public final class FileUtils {
boolean success = true; boolean success = true;
if (!org.apache.commons.io.FileUtils.deleteQuietly(file)) { if (!org.apache.commons.io.FileUtils.deleteQuietly(file)) {
success = false; success = false;
final String msg = String.format("Failed to delete file: %s; attempting to delete on exit.", file.getPath()); LOGGER.info("Failed to delete file: {}; attempting to delete on exit.", file.getPath());
LOGGER.log(Level.INFO, msg);
file.deleteOnExit(); file.deleteOnExit();
} }
return success; return success;

View File

@@ -17,6 +17,9 @@
*/ */
package org.owasp.dependencycheck.utils; package org.owasp.dependencycheck.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
@@ -28,8 +31,6 @@ import java.io.UnsupportedEncodingException;
import java.net.URLDecoder; import java.net.URLDecoder;
import java.util.Enumeration; import java.util.Enumeration;
import java.util.Properties; import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
/** /**
* A simple settings container that wraps the dependencycheck.properties file. * A simple settings container that wraps the dependencycheck.properties file.
@@ -264,7 +265,7 @@ public final class Settings {
/** /**
* The logger. * The logger.
*/ */
private static final Logger LOGGER = Logger.getLogger(Settings.class.getName()); private static final Logger LOGGER = LoggerFactory.getLogger(Settings.class);
/** /**
* The properties file location. * The properties file location.
*/ */
@@ -290,14 +291,14 @@ public final class Settings {
in = this.getClass().getClassLoader().getResourceAsStream(propertiesFilePath); in = this.getClass().getClassLoader().getResourceAsStream(propertiesFilePath);
props.load(in); props.load(in);
} catch (IOException ex) { } catch (IOException ex) {
LOGGER.log(Level.SEVERE, "Unable to load default settings."); LOGGER.error("Unable to load default settings.");
LOGGER.log(Level.FINE, null, ex); LOGGER.debug("", ex);
} finally { } finally {
if (in != null) { if (in != null) {
try { try {
in.close(); in.close();
} catch (IOException ex) { } catch (IOException ex) {
LOGGER.log(Level.FINEST, null, ex); LOGGER.trace("", ex);
} }
} }
} }
@@ -342,7 +343,7 @@ public final class Settings {
try { try {
localSettings.remove(); localSettings.remove();
} catch (Throwable ex) { } catch (Throwable ex) {
LOGGER.log(Level.FINE, "Error cleaning up Settings", ex); LOGGER.debug("Error cleaning up Settings", ex);
} }
} }
@@ -371,7 +372,7 @@ public final class Settings {
* @param properties the properties to log * @param properties the properties to log
*/ */
private static void logProperties(String header, Properties properties) { private static void logProperties(String header, Properties properties) {
if (LOGGER.isLoggable(Level.FINE)) { if (LOGGER.isDebugEnabled()) {
final StringWriter sw = new StringWriter(); final StringWriter sw = new StringWriter();
PrintWriter pw = null; PrintWriter pw = null;
try { try {
@@ -390,7 +391,7 @@ public final class Settings {
} }
} }
pw.flush(); pw.flush();
LOGGER.fine(sw.toString()); LOGGER.debug(sw.toString());
} finally { } finally {
if (pw != null) { if (pw != null) {
pw.close(); pw.close();
@@ -408,9 +409,7 @@ public final class Settings {
*/ */
public static void setString(String key, String value) { public static void setString(String key, String value) {
localSettings.get().props.setProperty(key, value); localSettings.get().props.setProperty(key, value);
if (LOGGER.isLoggable(Level.FINE)) { LOGGER.debug("Setting: {}='{}'", key, value);
LOGGER.fine(String.format("Setting: %s='%s'", key, value));
}
} }
/** /**
@@ -425,9 +424,7 @@ public final class Settings {
} else { } else {
localSettings.get().props.setProperty(key, Boolean.FALSE.toString()); localSettings.get().props.setProperty(key, Boolean.FALSE.toString());
} }
if (LOGGER.isLoggable(Level.FINE)) { LOGGER.debug("Setting: {}='{}'", key, value);
LOGGER.fine(String.format("Setting: %s='%b'", key, value));
}
} }
/** /**
@@ -449,7 +446,7 @@ public final class Settings {
try { try {
fis.close(); fis.close();
} catch (IOException ex) { } catch (IOException ex) {
LOGGER.log(Level.FINEST, "close error", ex); LOGGER.trace("close error", ex);
} }
} }
} }
@@ -474,7 +471,7 @@ public final class Settings {
try { try {
fis.close(); fis.close();
} catch (IOException ex) { } catch (IOException ex) {
LOGGER.log(Level.FINEST, "close error", ex); LOGGER.trace("close error", ex);
} }
} }
} }
@@ -523,16 +520,16 @@ public final class Settings {
*/ */
protected static File getDataFile(String key) { protected static File getDataFile(String key) {
final String file = getString(key); final String file = getString(key);
LOGGER.log(Level.FINE, String.format("Settings.getDataFile() - file: '%s'", file)); LOGGER.debug("Settings.getDataFile() - file: '{}'", file);
if (file == null) { if (file == null) {
return null; return null;
} }
if (file.startsWith("[JAR]")) { if (file.startsWith("[JAR]")) {
LOGGER.log(Level.FINE, "Settings.getDataFile() - transforming filename"); LOGGER.debug("Settings.getDataFile() - transforming filename");
final File jarPath = getJarPath(); final File jarPath = getJarPath();
LOGGER.log(Level.FINE, String.format("Settings.getDataFile() - jar file: '%s'", jarPath.toString())); LOGGER.debug("Settings.getDataFile() - jar file: '{}'", jarPath.toString());
final File retVal = new File(jarPath, file.substring(6)); final File retVal = new File(jarPath, file.substring(6));
LOGGER.log(Level.FINE, String.format("Settings.getDataFile() - returning: '%s'", retVal.toString())); LOGGER.debug("Settings.getDataFile() - returning: '{}'", retVal.toString());
return retVal; return retVal;
} }
return new File(file); return new File(file);
@@ -549,7 +546,7 @@ public final class Settings {
try { try {
decodedPath = URLDecoder.decode(jarPath, "UTF-8"); decodedPath = URLDecoder.decode(jarPath, "UTF-8");
} catch (UnsupportedEncodingException ex) { } catch (UnsupportedEncodingException ex) {
LOGGER.log(Level.FINEST, null, ex); LOGGER.trace("", ex);
} }
final File path = new File(decodedPath); final File path = new File(decodedPath);
@@ -652,8 +649,7 @@ public final class Settings {
try { try {
value = Integer.parseInt(Settings.getString(key)); value = Integer.parseInt(Settings.getString(key));
} catch (NumberFormatException ex) { } catch (NumberFormatException ex) {
final String msg = String.format("Could not convert property '%s' to an int.", key); LOGGER.trace("Could not convert property '{}' to an int.", key, ex);
LOGGER.log(Level.FINEST, msg, ex);
value = defaultValue; value = defaultValue;
} }
return value; return value;
@@ -770,7 +766,7 @@ public final class Settings {
// yes, for H2 this path won't actually exists - but this is sufficient to get the value needed // yes, for H2 this path won't actually exists - but this is sufficient to get the value needed
final File dbFile = new File(directory, fileName); final File dbFile = new File(directory, fileName);
final String cString = String.format(connStr, dbFile.getCanonicalPath()); final String cString = String.format(connStr, dbFile.getCanonicalPath());
LOGGER.log(Level.FINE, String.format("Connection String: '%s'", cString)); LOGGER.debug("Connection String: '{}'", cString);
return cString; return cString;
} }
return connStr; return connStr;

11
pom.xml
View File

@@ -124,6 +124,7 @@ Copyright (c) 2012 - Jeremy Long
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<github.global.server>github</github.global.server> <github.global.server>github</github.global.server>
<slf4j.version>1.7.12</slf4j.version>
</properties> </properties>
<distributionManagement> <distributionManagement>
<site> <site>
@@ -366,6 +367,16 @@ Copyright (c) 2012 - Jeremy Long
<artifactId>commons-io</artifactId> <artifactId>commons-io</artifactId>
<version>2.4</version> <version>2.4</version>
</dependency> </dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency> <dependency>
<groupId>junit</groupId> <groupId>junit</groupId>
<artifactId>junit</artifactId> <artifactId>junit</artifactId>