Merge branch 'upmaster' into ruby-bundler

This commit is contained in:
Dale Visser
2015-09-14 17:14:20 -04:00
122 changed files with 974 additions and 10408 deletions

View File

@@ -110,7 +110,7 @@ Copyright & License
Dependency-Check is Copyright (c) 2012-2015 Jeremy Long. All Rights Reserved.
Permission to modify and redistribute is granted under the terms of the Apache 2.0 license. See the [LICENSE.txt](https://github.com/jeremylong/DependencyCheck/dependency-check-cli/blob/master/LICENSE.txt) file for the full license.
Permission to modify and redistribute is granted under the terms of the Apache 2.0 license. See the [LICENSE.txt](https://raw.githubusercontent.com/jeremylong/DependencyCheck/master/LICENSE.txt) file for the full license.
Dependency-Check makes use of several other open source libraries. Please see the [NOTICE.txt] [notices] file for more information.

View File

@@ -1,9 +1,6 @@
-----------------------------
---begin dependency-check----
-----------------------------
dependency-check
OWASP dependency-check
Copyright (c) 2012-2013 Jeremy Long. All Rights Reserved.
Copyright (c) 2012-2015 Jeremy Long. All Rights Reserved.
The licenses for the software listed below can be found in the META-INF/licenses/[dependency name].
@@ -19,11 +16,3 @@ An original copy of the license agreement can be found at: http://www.h2database
This product includes data from the Common Weakness Enumeration (CWE): http://cwe.mitre.org/
This product downloads and utilizes data from the National Vulnerability Database hosted by NIST: http://nvd.nist.gov/download.cfm
-----------------------------
---end dependency-check------
-----------------------------
Notices below are from dependent libraries and have been included via maven-shade-plugin.
-----------------------------

View File

@@ -20,6 +20,6 @@ Copyright & License
Dependency-Check is Copyright (c) 2012-2014 Jeremy Long. All Rights Reserved.
Permission to modify and redistribute is granted under the terms of the Apache 2.0 license. See the [LICENSE.txt](https://github.com/jeremylong/DependencyCheck/dependency-check-cli/blob/master/LICENSE.txt) file for the full license.
Permission to modify and redistribute is granted under the terms of the Apache 2.0 license. See the [LICENSE.txt](https://raw.githubusercontent.com/jeremylong/DependencyCheck/master/LICENSE.txt) file for the full license.
Dependency-Check-Ant makes use of other open source libraries. Please see the [NOTICE.txt](https://github.com/jeremylong/DependencyCheck/dependency-check-ant/blob/master/NOTICES.txt) file for more information.
Dependency-Check-Ant makes use of other open source libraries. Please see the [NOTICE.txt](https://raw.githubusercontent.com/jeremylong/DependencyCheck/master/dependency-check-ant/NOTICE.txt) file for more information.

View File

@@ -192,28 +192,34 @@ Copyright (c) 2013 - Jeremy Long. All Rights Reserved.
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.4.1</version>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer" />
<transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
<resource>META-INF/NOTICE.txt</resource>
</transformer>
<transformer implementation="org.apache.maven.plugins.shade.resource.DontIncludeResourceTransformer">
<resource>META-INF/NOTICE</resource>
</transformer>
<transformer implementation="org.apache.maven.plugins.shade.resource.DontIncludeResourceTransformer">
<resource>META-INF/LICENSE</resource>
</transformer>
</transformers>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<classpathPrefix>lib/</classpathPrefix>
</manifest>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<attach>false</attach> <!-- don't install/deploy this archive -->
</configuration>
<executions>
<execution>
<id>create-distribution</id>
<phase>package</phase>
<goals>
<goal>shade</goal>
<goal>single</goal>
</goals>
<configuration>
<descriptors>
<descriptor>src/main/assembly/release.xml</descriptor>
</descriptors>
</configuration>
</execution>
</executions>
</plugin>
@@ -221,9 +227,6 @@ Copyright (c) 2013 - Jeremy Long. All Rights Reserved.
<groupId>org.codehaus.mojo</groupId>
<artifactId>cobertura-maven-plugin</artifactId>
<configuration>
<!--instrumentation>
<ignoreTrivial>true</ignoreTrivial>
</instrumentation-->
<check>
<branchRate>85</branchRate>
<lineRate>85</lineRate>
@@ -320,6 +323,7 @@ Copyright (c) 2013 - Jeremy Long. All Rights Reserved.
<dependency>
<groupId>org.apache.ant</groupId>
<artifactId>ant</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.ant</groupId>

View File

@@ -12,18 +12,25 @@
<format>zip</format>
</formats>
<includeBaseDirectory>false</includeBaseDirectory>
<fileSets>
<!--fileSets>
<fileSet>
<outputDirectory>/</outputDirectory>
<outputDirectory>dependency-check</outputDirectory>
<directory>${project.build.directory}</directory>
<includes>
<include>dependency-check*.jar</include>
</includes>
</fileSet>
</fileSets>
</fileSets-->
<files>
<file>
<source>${project.build.directory}/${project.artifactId}-${project.version}.jar</source>
<outputDirectory>dependency-check</outputDirectory>
<destName>dependency-check-ant.jar</destName>
</file>
</files>
<dependencySets>
<dependencySet>
<outputDirectory>/lib</outputDirectory>
<outputDirectory>dependency-check/lib</outputDirectory>
<scope>runtime</scope>
</dependencySet>
</dependencySets>

View File

@@ -30,6 +30,11 @@ import org.slf4j.helpers.MessageFormatter;
*/
public class AntLoggerAdapter extends MarkerIgnoringBase {
/**
* The serial version UID for serialization.
*/
private static final long serialVersionUID = 1L;
/**
* A reference to the Ant task used for logging.
*/

View File

@@ -19,11 +19,9 @@ package org.owasp.dependencycheck.taskdefs;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.types.EnumeratedAttribute;
import org.apache.tools.ant.types.Reference;
import org.apache.tools.ant.types.Resource;
@@ -47,12 +45,8 @@ import org.slf4j.impl.StaticLoggerBinder;
*
* @author Jeremy Long
*/
public class DependencyCheckTask extends Task {
public class Check extends Update {
/**
* The properties file location.
*/
private static final String PROPERTIES_FILE = "task.properties";
/**
* System specific new line character.
*/
@@ -61,7 +55,7 @@ public class DependencyCheckTask extends Task {
/**
* Construct a new DependencyCheckTask.
*/
public DependencyCheckTask() {
public Check() {
super();
// Call this before Dependency Check Core starts logging anything - this way, all SLF4J messages from
// core end up coming through this tasks logger
@@ -168,7 +162,7 @@ public class DependencyCheckTask extends Task {
this.applicationName = applicationName;
}
private String projectName = "Dependency-Check";
private String projectName = "dependency-check";
/**
* Get the value of projectName.
@@ -178,7 +172,7 @@ public class DependencyCheckTask extends Task {
public String getProjectName() {
if (applicationName != null) {
log("Configuration 'applicationName' has been deprecated, please use 'projectName' instead", Project.MSG_WARN);
if ("Dependency-Check".equals(projectName)) {
if ("dependency-check".equals(projectName)) {
projectName = applicationName;
}
}
@@ -194,28 +188,6 @@ public class DependencyCheckTask extends Task {
this.projectName = projectName;
}
/**
* The location of the data directory that contains
*/
private String dataDirectory = null;
/**
* Get the value of dataDirectory.
*
* @return the value of dataDirectory
*/
public String getDataDirectory() {
return dataDirectory;
}
/**
* Set the value of dataDirectory.
*
* @param dataDirectory new value of dataDirectory
*/
public void setDataDirectory(String dataDirectory) {
this.dataDirectory = dataDirectory;
}
/**
* Specifies the destination directory for the generated Dependency-Check report.
*/
@@ -330,139 +302,6 @@ public class DependencyCheckTask extends Task {
public void setReportFormat(ReportFormats reportFormat) {
this.reportFormat = reportFormat.getValue();
}
/**
* The Proxy Server.
*/
private String proxyServer;
/**
* Get the value of proxyServer.
*
* @return the value of proxyServer
*/
public String getProxyServer() {
return proxyServer;
}
/**
* Set the value of proxyServer.
*
* @param server new value of proxyServer
*/
public void setProxyServer(String server) {
this.proxyServer = server;
}
/**
* Get the value of proxyServer.
*
* @return the value of proxyServer
* @deprecated use {@link org.owasp.dependencycheck.taskdefs.DependencyCheckTask#getProxyServer()} instead
*/
@Deprecated
public String getProxyUrl() {
return proxyServer;
}
/**
* Set the value of proxyServer.
*
* @param proxyUrl new value of proxyServer
* @deprecated use {@link org.owasp.dependencycheck.taskdefs.DependencyCheckTask#setProxyServer(java.lang.String)} instead
*/
@Deprecated
public void setProxyUrl(String proxyUrl) {
log("A deprecated configuration option 'proxyUrl' was detected; use 'proxyServer' instead.", Project.MSG_WARN);
this.proxyServer = proxyUrl;
}
/**
* The Proxy Port.
*/
private String proxyPort;
/**
* Get the value of proxyPort.
*
* @return the value of proxyPort
*/
public String getProxyPort() {
return proxyPort;
}
/**
* Set the value of proxyPort.
*
* @param proxyPort new value of proxyPort
*/
public void setProxyPort(String proxyPort) {
this.proxyPort = proxyPort;
}
/**
* The Proxy username.
*/
private String proxyUsername;
/**
* Get the value of proxyUsername.
*
* @return the value of proxyUsername
*/
public String getProxyUsername() {
return proxyUsername;
}
/**
* Set the value of proxyUsername.
*
* @param proxyUsername new value of proxyUsername
*/
public void setProxyUsername(String proxyUsername) {
this.proxyUsername = proxyUsername;
}
/**
* The Proxy password.
*/
private String proxyPassword;
/**
* Get the value of proxyPassword.
*
* @return the value of proxyPassword
*/
public String getProxyPassword() {
return proxyPassword;
}
/**
* Set the value of proxyPassword.
*
* @param proxyPassword new value of proxyPassword
*/
public void setProxyPassword(String proxyPassword) {
this.proxyPassword = proxyPassword;
}
/**
* The Connection Timeout.
*/
private String connectionTimeout;
/**
* Get the value of connectionTimeout.
*
* @return the value of connectionTimeout
*/
public String getConnectionTimeout() {
return connectionTimeout;
}
/**
* Set the value of connectionTimeout.
*
* @param connectionTimeout new value of connectionTimeout
*/
public void setConnectionTimeout(String connectionTimeout) {
this.connectionTimeout = connectionTimeout;
}
/**
* The path to the suppression file.
*/
@@ -508,6 +347,20 @@ public class DependencyCheckTask extends Task {
this.showSummary = showSummary;
}
/**
* Whether or not the Jar Analyzer is enabled.
*/
private boolean jarAnalyzerEnabled = true;
/**
* Returns whether or not the analyzer is enabled.
*
* @return true if the analyzer is enabled
*/
public boolean isJarAnalyzerEnabled() {
return jarAnalyzerEnabled;
}
/**
* Sets whether or not the analyzer is enabled.
*
@@ -605,29 +458,6 @@ public class DependencyCheckTask extends Task {
this.centralAnalyzerEnabled = centralAnalyzerEnabled;
}
/**
* Whether or not the local copy of the NVD should be purged.
*/
private boolean purge = false;
/**
* Used to determine if the local copy of the NVD should be purged.
*
* @return true if the local copy of the NVD should be purged
*/
public boolean isPurge() {
return purge;
}
/**
* Set whether or not the local copy of the NVD should be purged.
*
* @param purge setting to true will cause the local copy of the NVD to be deleted.
*/
public void setPurge(boolean purge) {
this.purge = purge;
}
/**
* Whether or not the nexus analyzer is enabled.
*/
@@ -696,119 +526,6 @@ public class DependencyCheckTask extends Task {
this.nexusUsesProxy = nexusUsesProxy;
}
/**
* The database driver name; such as org.h2.Driver.
*/
private String databaseDriverName;
/**
* Get the value of databaseDriverName.
*
* @return the value of databaseDriverName
*/
public String getDatabaseDriverName() {
return databaseDriverName;
}
/**
* Set the value of databaseDriverName.
*
* @param databaseDriverName new value of databaseDriverName
*/
public void setDatabaseDriverName(String databaseDriverName) {
this.databaseDriverName = databaseDriverName;
}
/**
* The path to the database driver JAR file if it is not on the class path.
*/
private String databaseDriverPath;
/**
* Get the value of databaseDriverPath.
*
* @return the value of databaseDriverPath
*/
public String getDatabaseDriverPath() {
return databaseDriverPath;
}
/**
* Set the value of databaseDriverPath.
*
* @param databaseDriverPath new value of databaseDriverPath
*/
public void setDatabaseDriverPath(String databaseDriverPath) {
this.databaseDriverPath = databaseDriverPath;
}
/**
* The database connection string.
*/
private String connectionString;
/**
* Get the value of connectionString.
*
* @return the value of connectionString
*/
public String getConnectionString() {
return connectionString;
}
/**
* Set the value of connectionString.
*
* @param connectionString new value of connectionString
*/
public void setConnectionString(String connectionString) {
this.connectionString = connectionString;
}
/**
* The user name for connecting to the database.
*/
private String databaseUser;
/**
* Get the value of databaseUser.
*
* @return the value of databaseUser
*/
public String getDatabaseUser() {
return databaseUser;
}
/**
* Set the value of databaseUser.
*
* @param databaseUser new value of databaseUser
*/
public void setDatabaseUser(String databaseUser) {
this.databaseUser = databaseUser;
}
/**
* The password to use when connecting to the database.
*/
private String databasePassword;
/**
* Get the value of databasePassword.
*
* @return the value of databasePassword
*/
public String getDatabasePassword() {
return databasePassword;
}
/**
* Set the value of databasePassword.
*
* @param databasePassword new value of databasePassword
*/
public void setDatabasePassword(String databasePassword) {
this.databasePassword = databasePassword;
}
/**
* Additional ZIP File extensions to add analyze. This should be a comma-separated list of file extensions to treat like ZIP
* files.
@@ -833,97 +550,6 @@ public class DependencyCheckTask extends Task {
this.zipExtensions = zipExtensions;
}
/**
* The url for the modified NVD CVE (1.2 schema).
*/
private String cveUrl12Modified;
/**
* Get the value of cveUrl12Modified.
*
* @return the value of cveUrl12Modified
*/
public String getCveUrl12Modified() {
return cveUrl12Modified;
}
/**
* Set the value of cveUrl12Modified.
*
* @param cveUrl12Modified new value of cveUrl12Modified
*/
public void setCveUrl12Modified(String cveUrl12Modified) {
this.cveUrl12Modified = cveUrl12Modified;
}
/**
* The url for the modified NVD CVE (2.0 schema).
*/
private String cveUrl20Modified;
/**
* Get the value of cveUrl20Modified.
*
* @return the value of cveUrl20Modified
*/
public String getCveUrl20Modified() {
return cveUrl20Modified;
}
/**
* Set the value of cveUrl20Modified.
*
* @param cveUrl20Modified new value of cveUrl20Modified
*/
public void setCveUrl20Modified(String cveUrl20Modified) {
this.cveUrl20Modified = cveUrl20Modified;
}
/**
* Base Data Mirror URL for CVE 1.2.
*/
private String cveUrl12Base;
/**
* Get the value of cveUrl12Base.
*
* @return the value of cveUrl12Base
*/
public String getCveUrl12Base() {
return cveUrl12Base;
}
/**
* Set the value of cveUrl12Base.
*
* @param cveUrl12Base new value of cveUrl12Base
*/
public void setCveUrl12Base(String cveUrl12Base) {
this.cveUrl12Base = cveUrl12Base;
}
/**
* Data Mirror URL for CVE 2.0.
*/
private String cveUrl20Base;
/**
* Get the value of cveUrl20Base.
*
* @return the value of cveUrl20Base
*/
public String getCveUrl20Base() {
return cveUrl20Base;
}
/**
* Set the value of cveUrl20Base.
*
* @param cveUrl20Base new value of cveUrl20Base
*/
public void setCveUrl20Base(String cveUrl20Base) {
this.cveUrl20Base = cveUrl20Base;
}
/**
* The path to Mono for .NET assembly analysis on non-windows systems.
*/
@@ -952,28 +578,11 @@ public class DependencyCheckTask extends Task {
dealWithReferences();
validateConfiguration();
populateSettings();
if (purge) {
File db;
try {
db = new File(Settings.getDataDirectory(), "dc.h2.db");
if (db.exists()) {
if (db.delete()) {
log("Database file purged; local copy of the NVD has been removed", Project.MSG_INFO);
} else {
log(String.format("Unable to delete '%s'; please delete the file manually", db.getAbsolutePath()), Project.MSG_ERR);
}
} else {
log(String.format("Unable to purge database; the database file does not exists: %s", db.getAbsolutePath()), Project.MSG_ERR);
}
} catch (IOException ex) {
log("Unable to delete the database", Project.MSG_ERR);
}
}
Engine engine = null;
try {
engine = new Engine(DependencyCheckTask.class.getClassLoader());
//todo - should this be its own task?
if (updateOnly) {
engine = new Engine(Check.class.getClassLoader());
if (isUpdateOnly()) {
log("Deprecated 'UpdateOnly' property set; please use the UpdateTask instead", Project.MSG_WARN);
engine.doUpdates();
} else {
try {
@@ -1046,50 +655,11 @@ public class DependencyCheckTask extends Task {
* Takes the properties supplied and updates the dependency-check settings. Additionally, this sets the system properties
* required to change the proxy server, port, and connection timeout.
*/
private void populateSettings() {
Settings.initialize();
InputStream taskProperties = null;
try {
taskProperties = this.getClass().getClassLoader().getResourceAsStream(PROPERTIES_FILE);
Settings.mergeProperties(taskProperties);
} catch (IOException ex) {
log("Unable to load the dependency-check ant task.properties file.", ex, Project.MSG_WARN);
} finally {
if (taskProperties != null) {
try {
taskProperties.close();
} catch (IOException ex) {
log("", ex, Project.MSG_DEBUG);
}
}
}
if (dataDirectory != null) {
Settings.setString(Settings.KEYS.DATA_DIRECTORY, dataDirectory);
} else {
final File jarPath = new File(DependencyCheckTask.class.getProtectionDomain().getCodeSource().getLocation().getPath());
final File base = jarPath.getParentFile();
final String sub = Settings.getString(Settings.KEYS.DATA_DIRECTORY);
final File dataDir = new File(base, sub);
Settings.setString(Settings.KEYS.DATA_DIRECTORY, dataDir.getAbsolutePath());
}
@Override
protected void populateSettings() {
super.populateSettings();
Settings.setBoolean(Settings.KEYS.AUTO_UPDATE, autoUpdate);
if (proxyServer != null && !proxyServer.isEmpty()) {
Settings.setString(Settings.KEYS.PROXY_SERVER, proxyServer);
}
if (proxyPort != null && !proxyPort.isEmpty()) {
Settings.setString(Settings.KEYS.PROXY_PORT, proxyPort);
}
if (proxyUsername != null && !proxyUsername.isEmpty()) {
Settings.setString(Settings.KEYS.PROXY_USERNAME, proxyUsername);
}
if (proxyPassword != null && !proxyPassword.isEmpty()) {
Settings.setString(Settings.KEYS.PROXY_PASSWORD, proxyPassword);
}
if (connectionTimeout != null && !connectionTimeout.isEmpty()) {
Settings.setString(Settings.KEYS.CONNECTION_TIMEOUT, connectionTimeout);
}
if (suppressionFile != null && !suppressionFile.isEmpty()) {
Settings.setString(Settings.KEYS.SUPPRESSION_FILE, suppressionFile);
}
@@ -1117,34 +687,6 @@ public class DependencyCheckTask extends Task {
if (pathToMono != null && !pathToMono.isEmpty()) {
Settings.setString(Settings.KEYS.ANALYZER_ASSEMBLY_MONO_PATH, pathToMono);
}
if (databaseDriverName != null && !databaseDriverName.isEmpty()) {
Settings.setString(Settings.KEYS.DB_DRIVER_NAME, databaseDriverName);
}
if (databaseDriverPath != null && !databaseDriverPath.isEmpty()) {
Settings.setString(Settings.KEYS.DB_DRIVER_PATH, databaseDriverPath);
}
if (connectionString != null && !connectionString.isEmpty()) {
Settings.setString(Settings.KEYS.DB_CONNECTION_STRING, connectionString);
}
if (databaseUser != null && !databaseUser.isEmpty()) {
Settings.setString(Settings.KEYS.DB_USER, databaseUser);
}
if (databasePassword != null && !databasePassword.isEmpty()) {
Settings.setString(Settings.KEYS.DB_PASSWORD, databasePassword);
}
if (cveUrl12Modified != null && !cveUrl12Modified.isEmpty()) {
Settings.setString(Settings.KEYS.CVE_MODIFIED_12_URL, cveUrl12Modified);
}
if (cveUrl20Modified != null && !cveUrl20Modified.isEmpty()) {
Settings.setString(Settings.KEYS.CVE_MODIFIED_20_URL, cveUrl20Modified);
}
if (cveUrl12Base != null && !cveUrl12Base.isEmpty()) {
Settings.setString(Settings.KEYS.CVE_SCHEMA_1_2, cveUrl12Base);
}
if (cveUrl20Base != null && !cveUrl20Base.isEmpty()) {
Settings.setString(Settings.KEYS.CVE_SCHEMA_2_0, cveUrl20Base);
}
}
/**
@@ -1236,18 +778,4 @@ public class DependencyCheckTask extends Task {
return values;
}
}
/**
* Whether or not the Jar Analyzer is enabled.
*/
private boolean jarAnalyzerEnabled = true;
/**
* Returns whether or not the analyzer is enabled.
*
* @return true if the analyzer is enabled
*/
public boolean isJarAnalyzerEnabled() {
return jarAnalyzerEnabled;
}
}

View File

@@ -0,0 +1,127 @@
/*
* 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) 2015 Jeremy Long. All Rights Reserved.
*/
package org.owasp.dependencycheck.taskdefs;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.Task;
import org.owasp.dependencycheck.utils.Settings;
import org.slf4j.impl.StaticLoggerBinder;
/**
* An Ant task definition to execute dependency-check during an Ant build.
*
* @author Jeremy Long
*/
public class Purge extends Task {
/**
* The properties file location.
*/
private static final String PROPERTIES_FILE = "task.properties";
/**
* Construct a new DependencyCheckTask.
*/
public Purge() {
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 location of the data directory that contains
*/
private String dataDirectory = null;
/**
* Get the value of dataDirectory.
*
* @return the value of dataDirectory
*/
public String getDataDirectory() {
return dataDirectory;
}
/**
* Set the value of dataDirectory.
*
* @param dataDirectory new value of dataDirectory
*/
public void setDataDirectory(String dataDirectory) {
this.dataDirectory = dataDirectory;
}
@Override
public void execute() throws BuildException {
populateSettings();
File db;
try {
db = new File(Settings.getDataDirectory(), "dc.h2.db");
if (db.exists()) {
if (db.delete()) {
log("Database file purged; local copy of the NVD has been removed", Project.MSG_INFO);
} else {
log(String.format("Unable to delete '%s'; please delete the file manually", db.getAbsolutePath()), Project.MSG_ERR);
}
} else {
log(String.format("Unable to purge database; the database file does not exists: %s", db.getAbsolutePath()), Project.MSG_ERR);
}
} catch (IOException ex) {
log("Unable to delete the database", Project.MSG_ERR);
} finally {
Settings.cleanup(true);
}
}
/**
* Takes the properties supplied and updates the dependency-check settings. Additionally, this sets the system properties
* required to change the proxy server, port, and connection timeout.
*/
protected void populateSettings() {
Settings.initialize();
InputStream taskProperties = null;
try {
taskProperties = this.getClass().getClassLoader().getResourceAsStream(PROPERTIES_FILE);
Settings.mergeProperties(taskProperties);
} catch (IOException ex) {
log("Unable to load the dependency-check ant task.properties file.", ex, Project.MSG_WARN);
} finally {
if (taskProperties != null) {
try {
taskProperties.close();
} catch (IOException ex) {
log("", ex, Project.MSG_DEBUG);
}
}
}
if (dataDirectory != null) {
Settings.setString(Settings.KEYS.DATA_DIRECTORY, dataDirectory);
} else {
final File jarPath = new File(Purge.class.getProtectionDomain().getCodeSource().getLocation().getPath());
final File base = jarPath.getParentFile();
final String sub = Settings.getString(Settings.KEYS.DATA_DIRECTORY);
final File dataDir = new File(base, sub);
Settings.setString(Settings.KEYS.DATA_DIRECTORY, dataDir.getAbsolutePath());
}
}
}

View File

@@ -0,0 +1,433 @@
/*
* 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) 2015 Jeremy Long. All Rights Reserved.
*/
package org.owasp.dependencycheck.taskdefs;
import org.apache.tools.ant.BuildException;
import org.owasp.dependencycheck.Engine;
import org.owasp.dependencycheck.data.nvdcve.DatabaseException;
import org.owasp.dependencycheck.utils.Settings;
import org.slf4j.impl.StaticLoggerBinder;
/**
* An Ant task definition to execute dependency-check update. This will download the latest data from the National Vulnerability
* Database (NVD) and store a copy in the local database.
*
* @author Jeremy Long
*/
public class Update extends Purge {
/**
* Construct a new UpdateTask.
*/
public Update() {
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 Proxy Server.
*/
private String proxyServer;
/**
* Get the value of proxyServer.
*
* @return the value of proxyServer
*/
public String getProxyServer() {
return proxyServer;
}
/**
* Set the value of proxyServer.
*
* @param server new value of proxyServer
*/
public void setProxyServer(String server) {
this.proxyServer = server;
}
/**
* The Proxy Port.
*/
private String proxyPort;
/**
* Get the value of proxyPort.
*
* @return the value of proxyPort
*/
public String getProxyPort() {
return proxyPort;
}
/**
* Set the value of proxyPort.
*
* @param proxyPort new value of proxyPort
*/
public void setProxyPort(String proxyPort) {
this.proxyPort = proxyPort;
}
/**
* The Proxy username.
*/
private String proxyUsername;
/**
* Get the value of proxyUsername.
*
* @return the value of proxyUsername
*/
public String getProxyUsername() {
return proxyUsername;
}
/**
* Set the value of proxyUsername.
*
* @param proxyUsername new value of proxyUsername
*/
public void setProxyUsername(String proxyUsername) {
this.proxyUsername = proxyUsername;
}
/**
* The Proxy password.
*/
private String proxyPassword;
/**
* Get the value of proxyPassword.
*
* @return the value of proxyPassword
*/
public String getProxyPassword() {
return proxyPassword;
}
/**
* Set the value of proxyPassword.
*
* @param proxyPassword new value of proxyPassword
*/
public void setProxyPassword(String proxyPassword) {
this.proxyPassword = proxyPassword;
}
/**
* The Connection Timeout.
*/
private String connectionTimeout;
/**
* Get the value of connectionTimeout.
*
* @return the value of connectionTimeout
*/
public String getConnectionTimeout() {
return connectionTimeout;
}
/**
* Set the value of connectionTimeout.
*
* @param connectionTimeout new value of connectionTimeout
*/
public void setConnectionTimeout(String connectionTimeout) {
this.connectionTimeout = connectionTimeout;
}
/**
* The database driver name; such as org.h2.Driver.
*/
private String databaseDriverName;
/**
* Get the value of databaseDriverName.
*
* @return the value of databaseDriverName
*/
public String getDatabaseDriverName() {
return databaseDriverName;
}
/**
* Set the value of databaseDriverName.
*
* @param databaseDriverName new value of databaseDriverName
*/
public void setDatabaseDriverName(String databaseDriverName) {
this.databaseDriverName = databaseDriverName;
}
/**
* The path to the database driver JAR file if it is not on the class path.
*/
private String databaseDriverPath;
/**
* Get the value of databaseDriverPath.
*
* @return the value of databaseDriverPath
*/
public String getDatabaseDriverPath() {
return databaseDriverPath;
}
/**
* Set the value of databaseDriverPath.
*
* @param databaseDriverPath new value of databaseDriverPath
*/
public void setDatabaseDriverPath(String databaseDriverPath) {
this.databaseDriverPath = databaseDriverPath;
}
/**
* The database connection string.
*/
private String connectionString;
/**
* Get the value of connectionString.
*
* @return the value of connectionString
*/
public String getConnectionString() {
return connectionString;
}
/**
* Set the value of connectionString.
*
* @param connectionString new value of connectionString
*/
public void setConnectionString(String connectionString) {
this.connectionString = connectionString;
}
/**
* The user name for connecting to the database.
*/
private String databaseUser;
/**
* Get the value of databaseUser.
*
* @return the value of databaseUser
*/
public String getDatabaseUser() {
return databaseUser;
}
/**
* Set the value of databaseUser.
*
* @param databaseUser new value of databaseUser
*/
public void setDatabaseUser(String databaseUser) {
this.databaseUser = databaseUser;
}
/**
* The password to use when connecting to the database.
*/
private String databasePassword;
/**
* Get the value of databasePassword.
*
* @return the value of databasePassword
*/
public String getDatabasePassword() {
return databasePassword;
}
/**
* Set the value of databasePassword.
*
* @param databasePassword new value of databasePassword
*/
public void setDatabasePassword(String databasePassword) {
this.databasePassword = databasePassword;
}
/**
* The url for the modified NVD CVE (1.2 schema).
*/
private String cveUrl12Modified;
/**
* Get the value of cveUrl12Modified.
*
* @return the value of cveUrl12Modified
*/
public String getCveUrl12Modified() {
return cveUrl12Modified;
}
/**
* Set the value of cveUrl12Modified.
*
* @param cveUrl12Modified new value of cveUrl12Modified
*/
public void setCveUrl12Modified(String cveUrl12Modified) {
this.cveUrl12Modified = cveUrl12Modified;
}
/**
* The url for the modified NVD CVE (2.0 schema).
*/
private String cveUrl20Modified;
/**
* Get the value of cveUrl20Modified.
*
* @return the value of cveUrl20Modified
*/
public String getCveUrl20Modified() {
return cveUrl20Modified;
}
/**
* Set the value of cveUrl20Modified.
*
* @param cveUrl20Modified new value of cveUrl20Modified
*/
public void setCveUrl20Modified(String cveUrl20Modified) {
this.cveUrl20Modified = cveUrl20Modified;
}
/**
* Base Data Mirror URL for CVE 1.2.
*/
private String cveUrl12Base;
/**
* Get the value of cveUrl12Base.
*
* @return the value of cveUrl12Base
*/
public String getCveUrl12Base() {
return cveUrl12Base;
}
/**
* Set the value of cveUrl12Base.
*
* @param cveUrl12Base new value of cveUrl12Base
*/
public void setCveUrl12Base(String cveUrl12Base) {
this.cveUrl12Base = cveUrl12Base;
}
/**
* Data Mirror URL for CVE 2.0.
*/
private String cveUrl20Base;
/**
* Get the value of cveUrl20Base.
*
* @return the value of cveUrl20Base
*/
public String getCveUrl20Base() {
return cveUrl20Base;
}
/**
* Set the value of cveUrl20Base.
*
* @param cveUrl20Base new value of cveUrl20Base
*/
public void setCveUrl20Base(String cveUrl20Base) {
this.cveUrl20Base = cveUrl20Base;
}
/**
* Executes the update by initializing the settings, downloads the NVD XML data, and then processes the data storing it in the
* local database.
*
* @throws BuildException thrown if a connection to the local database cannot be made.
*/
@Override
public void execute() throws BuildException {
populateSettings();
Engine engine = null;
try {
engine = new Engine(Update.class.getClassLoader());
engine.doUpdates();
} catch (DatabaseException ex) {
throw new BuildException("Unable to connect to the dependency-check database; unable to update the NVD data", ex);
} finally {
Settings.cleanup(true);
if (engine != null) {
engine.cleanup();
}
}
}
/**
* Takes the properties supplied and updates the dependency-check settings. Additionally, this sets the system properties
* required to change the proxy server, port, and connection timeout.
*/
@Override
protected void populateSettings() {
super.populateSettings();
if (proxyServer != null && !proxyServer.isEmpty()) {
Settings.setString(Settings.KEYS.PROXY_SERVER, proxyServer);
}
if (proxyPort != null && !proxyPort.isEmpty()) {
Settings.setString(Settings.KEYS.PROXY_PORT, proxyPort);
}
if (proxyUsername != null && !proxyUsername.isEmpty()) {
Settings.setString(Settings.KEYS.PROXY_USERNAME, proxyUsername);
}
if (proxyPassword != null && !proxyPassword.isEmpty()) {
Settings.setString(Settings.KEYS.PROXY_PASSWORD, proxyPassword);
}
if (connectionTimeout != null && !connectionTimeout.isEmpty()) {
Settings.setString(Settings.KEYS.CONNECTION_TIMEOUT, connectionTimeout);
}
if (databaseDriverName != null && !databaseDriverName.isEmpty()) {
Settings.setString(Settings.KEYS.DB_DRIVER_NAME, databaseDriverName);
}
if (databaseDriverPath != null && !databaseDriverPath.isEmpty()) {
Settings.setString(Settings.KEYS.DB_DRIVER_PATH, databaseDriverPath);
}
if (connectionString != null && !connectionString.isEmpty()) {
Settings.setString(Settings.KEYS.DB_CONNECTION_STRING, connectionString);
}
if (databaseUser != null && !databaseUser.isEmpty()) {
Settings.setString(Settings.KEYS.DB_USER, databaseUser);
}
if (databasePassword != null && !databasePassword.isEmpty()) {
Settings.setString(Settings.KEYS.DB_PASSWORD, databasePassword);
}
if (cveUrl12Modified != null && !cveUrl12Modified.isEmpty()) {
Settings.setString(Settings.KEYS.CVE_MODIFIED_12_URL, cveUrl12Modified);
}
if (cveUrl20Modified != null && !cveUrl20Modified.isEmpty()) {
Settings.setString(Settings.KEYS.CVE_MODIFIED_20_URL, cveUrl20Modified);
}
if (cveUrl12Base != null && !cveUrl12Base.isEmpty()) {
Settings.setString(Settings.KEYS.CVE_SCHEMA_1_2, cveUrl12Base);
}
if (cveUrl20Base != null && !cveUrl20Base.isEmpty()) {
Settings.setString(Settings.KEYS.CVE_SCHEMA_2_0, cveUrl20Base);
}
}
}

View File

@@ -0,0 +1,3 @@
dependency-check=org.owasp.dependencycheck.taskdefs.Check
dependency-check-purge=org.owasp.dependencycheck.taskdefs.Purge
dependency-check-update=org.owasp.dependencycheck.taskdefs.Update

View File

@@ -1,2 +1,2 @@
# the path to the data directory
data.directory=dependency-check-data
data.directory=data

View File

@@ -1,3 +0,0 @@
# define custom tasks here
dependencycheck=org.owasp.dependencycheck.taskdefs.DependencyCheckTask

View File

@@ -0,0 +1,19 @@
Configuration
====================
The dependency-check-purge task deletes the local copy of the NVD. This task
should rarely be used, if ever. This is included as a convenience method in
the rare circumstance that the local H2 database because corrupt.
```xml
<target name="dependency-check-purge" description="Dependency-Check purge">
<dependency-check-purge />
</target>
```
Configuration: dependency-check-purge Task
--------------------
The following properties can be set on the dependency-check-purge task.
Property | Description | Default Value
----------------------|----------------------------------------------------------------|------------------
dataDirectory | Data directory that is used to store the local copy of the NVD | data

View File

@@ -0,0 +1,44 @@
Configuration
====================
The dependency-check-update task downloads and updates the local copy of the NVD.
There are several reasons that one may want to use this task; primarily, creating
an update that will be run only once a day or once every few days (but not greater
then 7 days) and then use the `autoUpdate="false"` setting on individual
dependency-check scans. See [Internet Access Required](https://jeremylong.github.io/DependencyCheck/data/index.html)
for more information on why this task would be used.
```xml
<target name="dependency-check-update" description="Dependency-Check Update">
<dependency-check-update />
</target>
```
Configuration: dependency-check-update Task
--------------------
The following properties can be set on the dependency-check task.
Property | Description | Default Value
----------------------|------------------------------------|------------------
proxyServer | The Proxy Server. | &nbsp;
proxyPort | The Proxy Port. | &nbsp;
proxyUsername | Defines the proxy user name. | &nbsp;
proxyPassword | Defines the proxy password. | &nbsp;
connectionTimeout | The URL Connection Timeout. | &nbsp;
Advanced Configuration
====================
The following properties can be configured in the plugin. However, they are less frequently changed. One exception
may be the cvedUrl properties, which can be used to host a mirror of the NVD within an enterprise environment.
Property | Description | Default Value
---------------------|-------------------------------------------------------------------------------------------------------|------------------
cveUrl12Modified | URL for the modified CVE 1.2. | http://nvd.nist.gov/download/nvdcve-modified.xml
cveUrl20Modified | URL for the modified CVE 2.0. | http://static.nvd.nist.gov/feeds/xml/cve/nvdcve-2.0-modified.xml
cveUrl12Base | Base URL for each year's CVE 1.2, the %d will be replaced with the year. | http://nvd.nist.gov/download/nvdcve-%d.xml
cveUrl20Base | Base URL for each year's CVE 2.0, the %d will be replaced with the year. | http://static.nvd.nist.gov/feeds/xml/cve/nvdcve-2.0-%d.xml
dataDirectory | Data directory that is used to store the local copy of the NVD. This should generally not be changed. | data
databaseDriverName | The name of the database driver. Example: org.h2.Driver. | &nbsp;
databaseDriverPath | The path to the database driver JAR file; only used if the driver is not in the class path. | &nbsp;
connectionString | The connection string used to connect to the database. | &nbsp;
databaseUser | The username used when connecting to the database. | &nbsp;
databasePassword | The password used when connecting to the database. | &nbsp;

View File

@@ -1,5 +1,11 @@
Configuration
====================
Once dependency-check-ant has been [installed](index.html) the defined tasks can be used.
* dependency-check - the primary task used to check the project dependencies. Configuration options are below.
* dependency-check-purge - deletes the local copy of the NVD; this should rarely be used (if ever). See the [purge configuration](config-purge.html) for more information.
* dependency-check-update - downloads and updates the local copy of the NVD. See the [update configuration](config-update.html) for more information.
To configure the dependency-check task you can add it to a target and include a
file based [resource collection](http://ant.apache.org/manual/Types/resources.html#collection)
such as a [FileSet](http://ant.apache.org/manual/Types/fileset.html), [DirSet](http://ant.apache.org/manual/Types/dirset.html),
@@ -19,14 +25,13 @@ the project's dependencies.
</target>
```
Configuration
====================
The following properties can be set on the dependency-check-maven plugin.
Configuration: dependency-check Task
--------------------
The following properties can be set on the dependency-check-update task.
Property | Description | Default Value
----------------------|------------------------------------|------------------
autoUpdate | Sets whether auto-updating of the NVD CVE/CPE data is enabled. It is not recommended that this be turned to false. | true
updateOnly | If set to true only the update phase of dependency-check will be executed; no scan will be executed and no report will be generated. | false
projectName | The name of the project being scanned. | Dependency-Check
reportOutputDirectory | The location to write the report(s). Note, this is not used if generating the report as part of a `mvn site` build | 'target'
failBuildOnCVSS | Specifies if the build should be failed if a CVSS score above a specified level is identified. The default is 11 which means since the CVSS scores are 0-10, by default the build will never fail. | 11
@@ -70,10 +75,9 @@ cveUrl12Modified | URL for the modified CVE 1.2.
cveUrl20Modified | URL for the modified CVE 2.0. | http://static.nvd.nist.gov/feeds/xml/cve/nvdcve-2.0-modified.xml
cveUrl12Base | Base URL for each year's CVE 1.2, the %d will be replaced with the year. | http://nvd.nist.gov/download/nvdcve-%d.xml
cveUrl20Base | Base URL for each year's CVE 2.0, the %d will be replaced with the year. | http://static.nvd.nist.gov/feeds/xml/cve/nvdcve-2.0-%d.xml
dataDirectory | Data directory to hold SQL CVEs contents. This should generally not be changed. | &nbsp;
dataDirectory | Data directory that is used to store the local copy of the NVD. This should generally not be changed. | data
databaseDriverName | The name of the database driver. Example: org.h2.Driver. | &nbsp;
databaseDriverPath | The path to the database driver JAR file; only used if the driver is not in the class path. | &nbsp;
connectionString | The connection string used to connect to the database. | &nbsp;
databaseUser | The username used when connecting to the database. | &nbsp;
databasePassword | The password used when connecting to the database. | &nbsp;
purge | Delete the local copy of the NVD. This is used to force a refresh of the data. | &nbsp;

View File

@@ -7,23 +7,25 @@ identifiers, and the associated Common Vulnerability and Exposure (CVE) entries.
Installation
====================
Download dependency-check-ant from [bintray here](http://dl.bintray.com/jeremy-long/owasp/dependency-check-ant-${project.version}.jar).
To install dependency-check-ant place the dependency-check-ant-${project.version}.jar into
the lib directory of your Ant instalation directory. Once installed you can add
the taskdef to you build.xml and add the task to a new or existing target:
1. Download dependency-check-ant from [bintray here](http://dl.bintray.com/jeremy-long/owasp/dependency-check-ant-${project.version}-release.zip).
2. Unzip the archive
3. Add the taskdef to your build.xml:
```xml
<taskdef name="dependency-check" classname="org.owasp.dependencycheck.taskdefs.DependencyCheckTask"/>
```
If you do not want to install dependency-check-ant into your ant's lib directory when you define the task def you
must add the classpath to the taskdef:
```xml
<taskdef name="dependency-check" classname="org.owasp.dependencycheck.taskdefs.DependencyCheckTask">
<classpath path="[path]/[to]/dependency-check-ant-${project.version}.jar"/>
<!-- Set the value to the installation directory's path -->
<property name="dependency-check.home" value="C:/tools/dependency-check-ant"/>
<path id="dependency-check.path">
<pathelement location="${dependency-check.home}/dependency-check-ant.jar"/>
</path>
<taskdef resource="dependency-check-taskdefs.properties">
<classpath refid="dependency-check.path" />
</taskdef>
```
4. Use the defined taskdefs:
* [dependency-check](configuration.html) - the primary task used to check the project dependencies.
* [dependency-check-purge](config-purge.html) - deletes the local copy of the NVD; this should rarely be used (if ever).
* [dependency-check-update](config-update.html) - downloads and updates the local copy of the NVD.
It is important to understand that the first time this task is executed it may
take 10 minutes or more as it downloads and processes the data from the National

View File

@@ -1,33 +0,0 @@
Usage
====================
First, add the dependency-check-ant taskdef to your build.xml (see the [installation guide](installation.html)):
```xml
<taskdef name="dependency-check" classname="org.owasp.dependencycheck.taskdefs.DependencyCheckTask"/>
```
Or
```xml
<taskdef name="dependency-check" classname="org.owasp.dependencycheck.taskdefs.DependencyCheckTask">
<classpath path="[path]/[to]/dependency-check-ant-${project.version}.jar"/>
</taskdef>
```
Next, add the task to a target of your choosing:
```xml
<target name="dependency-check" description="Dependency-Check Analysis">
<dependency-check applicationname="Hello World"
autoupdate="true"
reportoutputdirectory="${basedir}"
reportformat="HTML">
<fileset dir="lib">
<include name="**/*.jar"/>
</fileset>
</dependency-check>
</target>
```
See the [configuration guide](configuration.html) for more information.

View File

@@ -28,7 +28,6 @@ Copyright (c) 2013 Jeremy Long. All Rights Reserved.
</breadcrumbs>
<menu name="Getting Started">
<item name="Installation" href="installation.html"/>
<item name="Usage" href="usage.html"/>
<item name="Configuration" href="configuration.html"/>
</menu>
<menu ref="reports" />

View File

@@ -1,7 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<project name="Dependency-Check Test Build" default="test.fileset" basedir=".">
<taskdef name="dependency-check" classname="org.owasp.dependencycheck.taskdefs.DependencyCheckTask" />
<taskdef name="dependency-check" classname="org.owasp.dependencycheck.taskdefs.Check" />
<target name="test.fileset">
<dependency-check

View File

@@ -19,6 +19,6 @@ Copyright & License
Dependency-Check is Copyright (c) 2012-2014 Jeremy Long. All Rights Reserved.
Permission to modify and redistribute is granted under the terms of the Apache 2.0 license. See the [LICENSE.txt](https://github.com/jeremylong/DependencyCheck/dependency-check-cli/blob/master/LICENSE.txt) file for the full license.
Permission to modify and redistribute is granted under the terms of the Apache 2.0 license. See the [LICENSE.txt](https://raw.githubusercontent.com/jeremylong/DependencyCheck/master/LICENSE.txt) file for the full license.
Dependency-Check Command Line makes use of other open source libraries. Please see the [NOTICE.txt](https://github.com/jeremylong/DependencyCheck/dependency-check-cli/blob/master/NOTICES.txt) file for more information.
Dependency-Check Command Line makes use of other open source libraries. Please see the [NOTICE.txt](https://raw.githubusercontent.com/jeremylong/DependencyCheck/master/dependency-check-cli/NOTICE.txt) file for more information.

View File

@@ -235,5 +235,15 @@ Copyright (c) 2012 - Jeremy Long. All Rights Reserved.
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
</dependency>
<dependency>
<groupId>org.apache.ant</groupId>
<artifactId>ant</artifactId>
<exclusions>
<exclusion>
<groupId>org.apache.ant</groupId>
<artifactId>ant-launcher</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
</project>

View File

@@ -32,13 +32,12 @@ import org.owasp.dependencycheck.data.nvdcve.CveDB;
import org.owasp.dependencycheck.data.nvdcve.DatabaseException;
import org.owasp.dependencycheck.data.nvdcve.DatabaseProperties;
import org.owasp.dependencycheck.dependency.Dependency;
import org.owasp.dependencycheck.org.apache.tools.ant.DirectoryScanner;
import org.apache.tools.ant.DirectoryScanner;
import org.owasp.dependencycheck.reporting.ReportGenerator;
import org.owasp.dependencycheck.utils.Settings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ch.qos.logback.core.FileAppender;
import java.util.logging.Level;
import org.slf4j.impl.StaticLoggerBinder;
/**
@@ -179,7 +178,8 @@ public class App {
//LOGGER.debug("baseDir: {}", baseDir);
//LOGGER.debug("include: {}", include);
scanner.setBasedir(baseDir);
scanner.setIncludes(include);
final String[] includes = {include};
scanner.setIncludes(includes);
scanner.setMaxLevelsOfSymlinks(symLinkDepth);
if (symLinkDepth <= 0) {
scanner.setFollowSymlinks(false);

View File

@@ -19,7 +19,6 @@ package org.owasp.dependencycheck;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.logging.Level;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;

View File

@@ -24,6 +24,11 @@ package org.owasp.dependencycheck;
*/
class InvalidScanPathException extends Exception {
/**
* The serial version UID for serialization.
*/
private static final long serialVersionUID = 1L;
/**
* Creates a new InvalidScanPathException.
*/

View File

@@ -17,7 +17,7 @@ Copyright & License
Dependency-Check is Copyright (c) 2012-2014 Jeremy Long. All Rights Reserved.
Permission to modify and redistribute is granted under the terms of the Apache 2.0 license. See the [LICENSE.txt](https://github.com/jeremylong/DependencyCheck/dependency-check-cli/blob/master/LICENSE.txt) file for the full license.
Permission to modify and redistribute is granted under the terms of the Apache 2.0 license. See the [LICENSE.txt](https://raw.githubusercontent.com/jeremylong/DependencyCheck/master/LICENSE.txt) file for the full license.
Dependency-Check makes use of several other open source libraries. Please see the [NOTICE.txt] [notices] file for more information.
@@ -25,4 +25,4 @@ Dependency-Check makes use of several other open source libraries. Please see th
[wiki]: https://github.com/jeremylong/DependencyCheck/wiki
[subscribe]: mailto:dependency-check+subscribe@googlegroups.com
[post]: mailto:dependency-check@googlegroups.com
[notices]: https://github.com/jeremylong/DependencyCheck/blob/master/NOTICES.txt
[notices]: https://raw.githubusercontent.com/jeremylong/DependencyCheck/master/NOTICE.txt

View File

@@ -210,13 +210,6 @@ Copyright (c) 2012 Jeremy Long. All Rights Reserved.
</systemProperties>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<compilerArgument>-Xlint:unchecked</compilerArgument>
</configuration>
</plugin>
</plugins>
</build>
<reporting>

View File

@@ -42,6 +42,7 @@ import java.util.EnumMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
@@ -59,7 +60,7 @@ public class Engine implements FileFilter {
/**
* A Map of analyzers grouped by Analysis phase.
*/
private EnumMap<AnalysisPhase, List<Analyzer>> analyzers = new EnumMap<AnalysisPhase, List<Analyzer>>(AnalysisPhase.class);
private Map<AnalysisPhase, List<Analyzer>> analyzers = new EnumMap<AnalysisPhase, List<Analyzer>>(AnalysisPhase.class);
/**
* A Map of analyzers grouped by Analysis phase.
@@ -478,6 +479,7 @@ public class Engine implements FileFilter {
* @param file a file extension
* @return true or false depending on whether or not the file extension is supported
*/
@Override
public boolean accept(File file) {
if (file == null) {
return false;

View File

@@ -28,6 +28,7 @@ import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream;
import org.apache.commons.compress.compressors.bzip2.BZip2Utils;
import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream;
import org.apache.commons.compress.compressors.gzip.GzipUtils;
import org.apache.commons.compress.utils.IOUtils;
import org.owasp.dependencycheck.Engine;
import org.owasp.dependencycheck.analyzer.exception.AnalysisException;
import org.owasp.dependencycheck.analyzer.exception.ArchiveExtractionException;
@@ -54,10 +55,6 @@ public class ArchiveAnalyzer extends AbstractFileTypeAnalyzer {
* The logger.
*/
private static final Logger LOGGER = LoggerFactory.getLogger(ArchiveAnalyzer.class);
/**
* The buffer size to use when extracting files from the archive.
*/
private static final int BUFFER_SIZE = 4096;
/**
* The count of directories created during analysis. This is used for creating temporary directories.
*/
@@ -385,7 +382,6 @@ public class ArchiveAnalyzer extends AbstractFileTypeAnalyzer {
private static void extractAcceptedFile(ArchiveInputStream input, File file) throws AnalysisException {
LOGGER.debug("Extracting '{}'", file.getPath());
BufferedOutputStream bos = null;
FileOutputStream fos = null;
try {
final File parent = file.getParentFile();
@@ -396,13 +392,7 @@ public class ArchiveAnalyzer extends AbstractFileTypeAnalyzer {
}
}
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos, BUFFER_SIZE);
int count;
final byte[] data = new byte[BUFFER_SIZE];
while ((count = input.read(data, 0, BUFFER_SIZE)) != -1) {
bos.write(data, 0, count);
}
bos.flush();
IOUtils.copy(input, fos);
} catch (FileNotFoundException ex) {
LOGGER.debug("", ex);
final String msg = String.format("Unable to find file '%s'.", file.getName());
@@ -412,7 +402,6 @@ public class ArchiveAnalyzer extends AbstractFileTypeAnalyzer {
final String msg = String.format("IO Exception while parsing file '%s'.", file.getName());
throw new AnalysisException(msg, ex);
} finally {
close(bos);
close(fos);
}
}
@@ -429,11 +418,7 @@ public class ArchiveAnalyzer extends AbstractFileTypeAnalyzer {
FileOutputStream out = null;
try {
out = new FileOutputStream(outputFile);
final byte[] buffer = new byte[BUFFER_SIZE];
int n; // = 0
while (-1 != (n = inputStream.read(buffer))) {
out.write(buffer, 0, n);
}
IOUtils.copy(inputStream, out);
} catch (FileNotFoundException ex) {
LOGGER.debug("", ex);
throw new ArchiveExtractionException(ex);

View File

@@ -147,7 +147,7 @@ public class AssemblyAnalyzer extends AbstractFileTypeAnalyzer {
// First, see if there was an error
final String error = xpath.evaluate("/assembly/error", doc);
if (error != null && !"".equals(error)) {
if (error != null && !error.isEmpty()) {
throw new AnalysisException(error);
}
@@ -246,7 +246,7 @@ public class AssemblyAnalyzer extends AbstractFileTypeAnalyzer {
final Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(p.getInputStream());
final XPath xpath = XPathFactory.newInstance().newXPath();
final String error = xpath.evaluate("/assembly/error", doc);
if (p.waitFor() != 1 || error == null || "".equals(error)) {
if (p.waitFor() != 1 || error == null || error.isEmpty()) {
LOGGER.warn("An error occurred with the .NET AssemblyAnalyzer, please see the log for more details.");
LOGGER.debug("GrokAssembly.exe is not working properly");
grokAssemblyExe = null;

View File

@@ -339,7 +339,7 @@ public class CPEAnalyzer implements Analyzer {
final String cleanText = cleanseText(searchText);
if ("".equals(cleanText)) {
if (cleanText.isEmpty()) {
return false;
}

View File

@@ -75,6 +75,7 @@ public class DependencyBundlingAnalyzer extends AbstractAnalyzer implements Anal
*
* @return the name of the analyzer.
*/
@Override
public String getName() {
return ANALYZER_NAME;
}
@@ -84,6 +85,7 @@ public class DependencyBundlingAnalyzer extends AbstractAnalyzer implements Anal
*
* @return the phase that the analyzer is intended to run in.
*/
@Override
public AnalysisPhase getAnalysisPhase() {
return ANALYSIS_PHASE;
}

View File

@@ -69,6 +69,7 @@ public class FalsePositiveAnalyzer extends AbstractAnalyzer {
*
* @return the name of the analyzer.
*/
@Override
public String getName() {
return ANALYZER_NAME;
}
@@ -78,6 +79,7 @@ public class FalsePositiveAnalyzer extends AbstractAnalyzer {
*
* @return the phase that the analyzer is intended to run in.
*/
@Override
public AnalysisPhase getAnalysisPhase() {
return ANALYSIS_PHASE;
}
@@ -378,18 +380,16 @@ public class FalsePositiveAnalyzer extends AbstractAnalyzer {
*/
private void addFalseNegativeCPEs(Dependency dependency) {
//TODO move this to the hint analyzer
final Iterator<Identifier> itr = dependency.getIdentifiers().iterator();
while (itr.hasNext()) {
final Identifier i = itr.next();
if ("cpe".equals(i.getType()) && i.getValue() != null
&& (i.getValue().startsWith("cpe:/a:oracle:opensso:")
|| i.getValue().startsWith("cpe:/a:oracle:opensso_enterprise:")
|| i.getValue().startsWith("cpe:/a:sun:opensso_enterprise:")
|| i.getValue().startsWith("cpe:/a:sun:opensso:"))) {
final String newCpe = String.format("cpe:/a:sun:opensso_enterprise:%s", i.getValue().substring(22));
final String newCpe2 = String.format("cpe:/a:oracle:opensso_enterprise:%s", i.getValue().substring(22));
final String newCpe3 = String.format("cpe:/a:sun:opensso:%s", i.getValue().substring(22));
final String newCpe4 = String.format("cpe:/a:oracle:opensso:%s", i.getValue().substring(22));
for (final Identifier identifier : dependency.getIdentifiers()) {
if ("cpe".equals(identifier.getType()) && identifier.getValue() != null
&& (identifier.getValue().startsWith("cpe:/a:oracle:opensso:")
|| identifier.getValue().startsWith("cpe:/a:oracle:opensso_enterprise:")
|| identifier.getValue().startsWith("cpe:/a:sun:opensso_enterprise:")
|| identifier.getValue().startsWith("cpe:/a:sun:opensso:"))) {
final String newCpe = String.format("cpe:/a:sun:opensso_enterprise:%s", identifier.getValue().substring(22));
final String newCpe2 = String.format("cpe:/a:oracle:opensso_enterprise:%s", identifier.getValue().substring(22));
final String newCpe3 = String.format("cpe:/a:sun:opensso:%s", identifier.getValue().substring(22));
final String newCpe4 = String.format("cpe:/a:oracle:opensso:%s", identifier.getValue().substring(22));
try {
dependency.addIdentifier("cpe",
newCpe,

View File

@@ -48,6 +48,7 @@ public class FileNameAnalyzer extends AbstractAnalyzer implements Analyzer {
*
* @return the name of the analyzer.
*/
@Override
public String getName() {
return ANALYZER_NAME;
}
@@ -57,6 +58,7 @@ public class FileNameAnalyzer extends AbstractAnalyzer implements Analyzer {
*
* @return the phase that the analyzer is intended to run in.
*/
@Override
public AnalysisPhase getAnalysisPhase() {
return ANALYSIS_PHASE;
}

View File

@@ -17,7 +17,6 @@
*/
package org.owasp.dependencycheck.analyzer;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileOutputStream;
@@ -42,6 +41,7 @@ import java.util.jar.JarFile;
import java.util.jar.Manifest;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import org.apache.commons.compress.utils.IOUtils;
import org.jsoup.Jsoup;
import org.owasp.dependencycheck.Engine;
import org.owasp.dependencycheck.analyzer.exception.AnalysisException;
@@ -69,10 +69,6 @@ public class JarAnalyzer extends AbstractFileTypeAnalyzer {
* The logger.
*/
private static final Logger LOGGER = LoggerFactory.getLogger(JarAnalyzer.class);
/**
* The buffer size to use when extracting files from the archive.
*/
private static final int BUFFER_SIZE = 4096;
/**
* The count of directories created during analysis. This is used for creating temporary directories.
*/
@@ -198,6 +194,7 @@ public class JarAnalyzer extends AbstractFileTypeAnalyzer {
*
* @return the phase that the analyzer is intended to run in.
*/
@Override
public AnalysisPhase getAnalysisPhase() {
return ANALYSIS_PHASE;
}
@@ -396,26 +393,18 @@ public class JarAnalyzer extends AbstractFileTypeAnalyzer {
private Model extractPom(String path, JarFile jar, Dependency dependency) throws AnalysisException {
InputStream input = null;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
final File tmpDir = getNextTempDirectory();
final File file = new File(tmpDir, "pom.xml");
try {
final ZipEntry entry = jar.getEntry(path);
input = jar.getInputStream(entry);
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos, BUFFER_SIZE);
int count;
final byte[] data = new byte[BUFFER_SIZE];
while ((count = input.read(data, 0, BUFFER_SIZE)) != -1) {
bos.write(data, 0, count);
}
bos.flush();
IOUtils.copy(input, fos);
dependency.setActualFilePath(file.getAbsolutePath());
} catch (IOException ex) {
LOGGER.warn("An error occurred reading '{}' from '{}'.", path, dependency.getFilePath());
LOGGER.error("", ex);
} finally {
closeStream(bos);
closeStream(fos);
closeStream(input);
}

View File

@@ -116,7 +116,7 @@ public class CentralSearch {
if ("0".equals(numFound)) {
missing = true;
} else {
final ArrayList<MavenArtifact> result = new ArrayList<MavenArtifact>();
final List<MavenArtifact> result = new ArrayList<MavenArtifact>();
final NodeList docs = (NodeList) xpath.evaluate("/response/result/doc", doc, XPathConstants.NODESET);
for (int i = 0; i < docs.getLength(); i++) {
final String g = xpath.evaluate("./str[@name='g']", docs.item(i));

View File

@@ -151,7 +151,7 @@ public final class CpeMemoryIndex {
*/
@SuppressWarnings("unchecked")
private Analyzer createIndexingAnalyzer() {
final Map fieldAnalyzers = new HashMap();
final Map<String,Analyzer> fieldAnalyzers = new HashMap<String, Analyzer>();
fieldAnalyzers.put(Fields.DOCUMENT_KEY, new KeywordAnalyzer());
return new PerFieldAnalyzerWrapper(new FieldAnalyzer(LuceneUtils.CURRENT_VERSION), fieldAnalyzers);
}

View File

@@ -24,6 +24,7 @@ import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.util.HashMap;
import java.util.Map;
/**
*
@@ -45,21 +46,21 @@ public final class CweDB {
/**
* A HashMap of the CWE data.
*/
private static final HashMap<String, String> CWE = loadData();
private static final Map<String, String> CWE = loadData();
/**
* Loads a HashMap containing the CWE data from a resource found in the jar.
*
* @return a HashMap of CWE data
*/
private static HashMap<String, String> loadData() {
private static Map<String, String> loadData() {
ObjectInputStream oin = null;
try {
final String filePath = "data/cwe.hashmap.serialized";
final InputStream input = CweDB.class.getClassLoader().getResourceAsStream(filePath);
oin = new ObjectInputStream(input);
@SuppressWarnings("unchecked")
final HashMap<String, String> ret = (HashMap<String, String>) oin.readObject();
final Map<String, String> ret = (HashMap<String, String>) oin.readObject();
return ret;
} catch (ClassNotFoundException ex) {
LOGGER.warn("Unable to load CWE data. This should not be an issue.");

View File

@@ -132,10 +132,10 @@ public class NexusSearch {
"/org.sonatype.nexus.rest.model.NexusArtifact/pomLink",
doc);
final MavenArtifact ma = new MavenArtifact(groupId, artifactId, version);
if (link != null && !"".equals(link)) {
if (link != null && !link.isEmpty()) {
ma.setArtifactUrl(link);
}
if (pomLink != null && !"".equals(pomLink)) {
if (pomLink != null && !pomLink.isEmpty()) {
ma.setPomUrl(pomLink);
}
return ma;

View File

@@ -340,7 +340,6 @@ public class CveDB {
* @throws DatabaseException thrown if there is an exception retrieving data
*/
public List<Vulnerability> getVulnerabilities(String cpeStr) throws DatabaseException {
ResultSet rs = null;
final VulnerableSoftware cpe = new VulnerableSoftware();
try {
cpe.parseName(cpeStr);
@@ -350,7 +349,8 @@ public class CveDB {
final DependencyVersion detectedVersion = parseDependencyVersion(cpe);
final List<Vulnerability> vulnerabilities = new ArrayList<Vulnerability>();
PreparedStatement ps;
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = getConnection().prepareStatement(statementBundle.getString("SELECT_CVE_FROM_SOFTWARE"));
ps.setString(1, cpe.getVendor());
@@ -384,12 +384,11 @@ public class CveDB {
v.setMatchedCPE(matchedCPE.getKey(), matchedCPE.getValue() ? "Y" : null);
vulnerabilities.add(v);
}
DBUtils.closeResultSet(rs);
DBUtils.closeStatement(ps);
} catch (SQLException ex) {
throw new DatabaseException("Exception retrieving vulnerability for " + cpeStr, ex);
} finally {
DBUtils.closeResultSet(rs);
DBUtils.closeStatement(ps);
}
return vulnerabilities;
}
@@ -490,7 +489,7 @@ public class CveDB {
deleteReferences = getConnection().prepareStatement(statementBundle.getString("DELETE_REFERENCE"));
deleteSoftware = getConnection().prepareStatement(statementBundle.getString("DELETE_SOFTWARE"));
updateVulnerability = getConnection().prepareStatement(statementBundle.getString("UPDATE_VULNERABILITY"));
final String ids[] = {"id"};
final String[] ids = {"id"};
insertVulnerability = getConnection().prepareStatement(statementBundle.getString("INSERT_VULNERABILITY"),
//Statement.RETURN_GENERATED_KEYS);
ids);
@@ -767,9 +766,9 @@ public class CveDB {
* @return a dependency version
*/
private DependencyVersion parseDependencyVersion(VulnerableSoftware cpe) {
DependencyVersion cpeVersion;
final DependencyVersion cpeVersion;
if (cpe.getVersion() != null && !cpe.getVersion().isEmpty()) {
String versionText;
final String versionText;
if (cpe.getUpdate() != null && !cpe.getUpdate().isEmpty()) {
versionText = String.format("%s.%s", cpe.getVersion(), cpe.getUpdate());
} else {
@@ -783,6 +782,8 @@ public class CveDB {
}
/**
* This method is only referenced in unused code.
*
* Deletes unused dictionary entries from the database.
*/
public void deleteUnusedCpe() {
@@ -798,6 +799,8 @@ public class CveDB {
}
/**
* This method is only referenced in unused code and will likely break on MySQL if ever used due to the MERGE statement.
*
* Merges CPE entries into the database.
*
* @param cpe the CPE identifier

View File

@@ -115,7 +115,7 @@ class DriverShim implements Driver {
* @throws SQLFeatureNotSupportedException thrown if the feature is not supported
* @see java.sql.Driver#getParentLogger()
*/
//@Override
@Override
public java.util.logging.Logger getParentLogger() throws SQLFeatureNotSupportedException {
//return driver.getParentLogger();
Method m = null;

View File

@@ -43,6 +43,9 @@ import org.slf4j.LoggerFactory;
import org.xml.sax.SAXException;
/**
*
* This class is currently unused and if enabled will likely not work on MySQL as the MERGE statement is used.
*
* The CpeUpdater is designed to download the CPE data file from NIST and import the data into the database. However, as this
* currently adds no beneficial data, compared to what is in the CPE data contained in the CVE data files, this class is not
* currently used. The code is being kept as a future update may utilize more data from the CPE xml files.

View File

@@ -28,7 +28,8 @@ import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.owasp.dependencycheck.data.nexus.MavenArtifact;
import org.owasp.dependencycheck.utils.Checksum;
import org.slf4j.Logger;
@@ -43,6 +44,10 @@ import org.slf4j.LoggerFactory;
*/
public class Dependency implements Serializable, Comparable<Dependency> {
/**
* The serial version UID for serialization.
*/
private static final long serialVersionUID = 1L;
/**
* The logger.
*/
@@ -692,6 +697,7 @@ public class Dependency implements Serializable, Comparable<Dependency> {
* @param o a dependency to compare
* @return an integer representing the natural ordering
*/
@Override
public int compareTo(Dependency o) {
return this.getFilePath().compareToIgnoreCase(o.getFilePath());
}
@@ -708,21 +714,24 @@ public class Dependency implements Serializable, Comparable<Dependency> {
return false;
}
final Dependency other = (Dependency) obj;
return ObjectUtils.equals(this.actualFilePath, other.actualFilePath)
&& ObjectUtils.equals(this.filePath, other.filePath)
&& ObjectUtils.equals(this.fileName, other.fileName)
&& ObjectUtils.equals(this.md5sum, other.md5sum)
&& ObjectUtils.equals(this.sha1sum, other.sha1sum)
&& ObjectUtils.equals(this.identifiers, other.identifiers)
&& ObjectUtils.equals(this.vendorEvidence, other.vendorEvidence)
&& ObjectUtils.equals(this.productEvidence, other.productEvidence)
&& ObjectUtils.equals(this.versionEvidence, other.versionEvidence)
&& ObjectUtils.equals(this.description, other.description)
&& ObjectUtils.equals(this.license, other.license)
&& ObjectUtils.equals(this.vulnerabilities, other.vulnerabilities)
//&& ObjectUtils.equals(this.relatedDependencies, other.relatedDependencies)
&& ObjectUtils.equals(this.projectReferences, other.projectReferences)
&& ObjectUtils.equals(this.availableVersions, other.availableVersions);
return new EqualsBuilder()
.appendSuper(super.equals(obj))
.append(this.actualFilePath, other.actualFilePath)
.append(this.filePath, other.filePath)
.append(this.fileName, other.fileName)
.append(this.md5sum, other.md5sum)
.append(this.sha1sum, other.sha1sum)
.append(this.identifiers, other.identifiers)
.append(this.vendorEvidence, other.vendorEvidence)
.append(this.productEvidence, other.productEvidence)
.append(this.versionEvidence, other.versionEvidence)
.append(this.description, other.description)
.append(this.license, other.license)
.append(this.vulnerabilities, other.vulnerabilities)
//.append(this.relatedDependencies, other.relatedDependencies)
.append(this.projectReferences, other.projectReferences)
.append(this.availableVersions, other.availableVersions)
.isEquals();
}
/**
@@ -732,15 +741,23 @@ public class Dependency implements Serializable, Comparable<Dependency> {
*/
@Override
public int hashCode() {
int hash = MAGIC_HASH_INIT_VALUE;
for (Object field : new Object[]{this.actualFilePath, this.filePath, this.fileName, this.md5sum,
this.sha1sum, this.identifiers, this.vendorEvidence, this.productEvidence, this.versionEvidence,
this.description, this.license, this.vulnerabilities,
//this.relatedDependencies,
this.projectReferences, this.availableVersions}) {
hash = MAGIC_HASH_MULTIPLIER * hash + ObjectUtils.hashCode(field);
}
return hash;
return new HashCodeBuilder(MAGIC_HASH_INIT_VALUE, MAGIC_HASH_MULTIPLIER)
.append(actualFilePath)
.append(filePath)
.append(fileName)
.append(md5sum)
.append(sha1sum)
.append(identifiers)
.append(vendorEvidence)
.append(productEvidence)
.append(versionEvidence)
.append(description)
.append(license)
.append(vulnerabilities)
//.append(relatedDependencies)
.append(projectReferences)
.append(availableVersions)
.toHashCode();
}
/**

View File

@@ -19,6 +19,7 @@ package org.owasp.dependencycheck.dependency;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import java.io.Serializable;
@@ -29,6 +30,10 @@ import java.io.Serializable;
*/
public class Evidence implements Serializable, Comparable<Evidence> {
/**
* The serial version UID for serialization.
*/
private static final long serialVersionUID = 1L;
/**
* Used as starting point for generating the value in {@link #hashCode()}.
*/
@@ -194,12 +199,12 @@ public class Evidence implements Serializable, Comparable<Evidence> {
*/
@Override
public int hashCode() {
int hash = MAGIC_HASH_INIT_VALUE;
hash = MAGIC_HASH_MULTIPLIER * hash + ObjectUtils.hashCode(StringUtils.lowerCase(this.name));
hash = MAGIC_HASH_MULTIPLIER * hash + ObjectUtils.hashCode(StringUtils.lowerCase(this.source));
hash = MAGIC_HASH_MULTIPLIER * hash + ObjectUtils.hashCode(StringUtils.lowerCase(this.value));
hash = MAGIC_HASH_MULTIPLIER * hash + ObjectUtils.hashCode(this.confidence);
return hash;
return new HashCodeBuilder(MAGIC_HASH_INIT_VALUE, MAGIC_HASH_MULTIPLIER)
.append(StringUtils.lowerCase(name))
.append(StringUtils.lowerCase(source))
.append(StringUtils.lowerCase(value))
.append(confidence)
.toHashCode();
}
/**
@@ -230,6 +235,7 @@ public class Evidence implements Serializable, Comparable<Evidence> {
* @param o the evidence being compared
* @return an integer indicating the ordering of the two objects
*/
@Override
public int compareTo(Evidence o) {
if (o == null) {
return 1;

View File

@@ -39,6 +39,10 @@ import org.slf4j.LoggerFactory;
*/
public class EvidenceCollection implements Serializable, Iterable<Evidence> {
/**
* The serial version UID for serialization.
*/
private static final long serialVersionUID = 1L;
/**
* The logger.
*/
@@ -47,6 +51,7 @@ public class EvidenceCollection implements Serializable, Iterable<Evidence> {
* Used to iterate over highest confidence evidence contained in the collection.
*/
private static final Filter<Evidence> HIGHEST_CONFIDENCE = new Filter<Evidence>() {
@Override
public boolean passes(Evidence evidence) {
return evidence.getConfidence() == Confidence.HIGHEST;
}
@@ -55,6 +60,7 @@ public class EvidenceCollection implements Serializable, Iterable<Evidence> {
* Used to iterate over high confidence evidence contained in the collection.
*/
private static final Filter<Evidence> HIGH_CONFIDENCE = new Filter<Evidence>() {
@Override
public boolean passes(Evidence evidence) {
return evidence.getConfidence() == Confidence.HIGH;
}
@@ -63,6 +69,7 @@ public class EvidenceCollection implements Serializable, Iterable<Evidence> {
* Used to iterate over medium confidence evidence contained in the collection.
*/
private static final Filter<Evidence> MEDIUM_CONFIDENCE = new Filter<Evidence>() {
@Override
public boolean passes(Evidence evidence) {
return evidence.getConfidence() == Confidence.MEDIUM;
}
@@ -71,6 +78,7 @@ public class EvidenceCollection implements Serializable, Iterable<Evidence> {
* Used to iterate over low confidence evidence contained in the collection.
*/
private static final Filter<Evidence> LOW_CONFIDENCE = new Filter<Evidence>() {
@Override
public boolean passes(Evidence evidence) {
return evidence.getConfidence() == Confidence.LOW;
}
@@ -79,6 +87,7 @@ public class EvidenceCollection implements Serializable, Iterable<Evidence> {
* Used to iterate over evidence that has was used (aka read) from the collection.
*/
private static final Filter<Evidence> EVIDENCE_USED = new Filter<Evidence>() {
@Override
public boolean passes(Evidence evidence) {
return evidence.isUsed();
}
@@ -218,6 +227,7 @@ public class EvidenceCollection implements Serializable, Iterable<Evidence> {
*
* @return an Iterator<Evidence>.
*/
@Override
public Iterator<Evidence> iterator() {
return list.iterator();
}

View File

@@ -25,6 +25,11 @@ import java.io.Serializable;
*/
public class Identifier implements Serializable, Comparable<Identifier> {
/**
* The serial version UID for serialization.
*/
private static final long serialVersionUID = 1L;
/**
* Default constructor. Should only be used for automatic class
* creation as is the case with many XML parsers (for the parsing
@@ -216,6 +221,7 @@ public class Identifier implements Serializable, Comparable<Identifier> {
* @param o the object being compared
* @return an integer indicating the ordering
*/
@Override
public int compareTo(Identifier o) {
if (o == null) {
return -1;

View File

@@ -133,6 +133,7 @@ public class Reference implements Serializable, Comparable<Reference> {
* @param o the Reference being compared
* @return an integer indicating the ordering of the two objects
*/
@Override
public int compareTo(Reference o) {
if (source.equals(o.source)) {
if (name.equals(o.name)) {

View File

@@ -390,6 +390,7 @@ public class Vulnerability implements Serializable, Comparable<Vulnerability> {
* @return a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than
* the specified vulnerability
*/
@Override
public int compareTo(Vulnerability v) {
return v.getName().compareTo(this.getName());
}

View File

@@ -39,6 +39,7 @@ public class VulnerabilityComparator implements Comparator<Vulnerability>, Seria
* @param o2 a second vulnerability
* @return the comparison
*/
@Override
public int compare(Vulnerability o1, Vulnerability o2) {
return o2.getName().compareTo(o1.getName());
}

View File

@@ -46,6 +46,7 @@ public class VelocityLoggerRedirect implements LogChute {
*
* @param rsvc the RuntimeServices
*/
@Override
public void init(RuntimeServices rsvc) {
// do nothing
}
@@ -57,6 +58,7 @@ public class VelocityLoggerRedirect implements LogChute {
* @param level the logging level
* @param message the message to be logged
*/
@Override
public void log(int level, String message) {
switch (level) {
case TRACE_ID:
@@ -87,6 +89,7 @@ public class VelocityLoggerRedirect implements LogChute {
* @param message the message to be logged
* @param t a throwable to log
*/
@Override
public void log(int level, String message, Throwable t) {
switch (level) {
case TRACE_ID:
@@ -115,6 +118,7 @@ public class VelocityLoggerRedirect implements LogChute {
* @param level the logging level
* @return true
*/
@Override
public boolean isLevelEnabled(int level) {
return true;
}

View File

@@ -86,7 +86,7 @@ public class SuppressionHandler extends DefaultHandler {
/**
* The current node text being extracted from the element.
*/
private StringBuffer currentText;
private StringBuilder currentText;
/**
* Handles the start element event.
@@ -100,7 +100,7 @@ public class SuppressionHandler extends DefaultHandler {
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
currentAttributes = attributes;
currentText = new StringBuffer();
currentText = new StringBuilder();
if (SUPPRESS.equals(qName)) {
rule = new SuppressionRule();
final String base = currentAttributes.getValue("base");

View File

@@ -26,6 +26,11 @@ import java.io.IOException;
*/
public class SuppressionParseException extends IOException {
/**
* The serial version UID for serialization.
*/
private static final long serialVersionUID = 1L;
/**
* Creates a new SuppressionParseException.
*/

View File

@@ -37,7 +37,7 @@ import org.apache.commons.lang3.StringUtils;
*
* @author Jeremy Long
*/
public class DependencyVersion implements Iterable, Comparable<DependencyVersion> {
public class DependencyVersion implements Iterable<String>, Comparable<DependencyVersion> {
/**
* Constructor for a empty DependencyVersion.
@@ -103,7 +103,8 @@ public class DependencyVersion implements Iterable, Comparable<DependencyVersion
*
* @return an iterator for the version parts
*/
public Iterator iterator() {
@Override
public Iterator<String> iterator() {
return versionParts.iterator();
}

View File

@@ -18,7 +18,6 @@
package org.owasp.dependencycheck.utils;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
@@ -26,13 +25,13 @@ import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.archivers.ArchiveInputStream;
import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream;
import org.apache.commons.compress.utils.IOUtils;
import org.owasp.dependencycheck.Engine;
import org.owasp.dependencycheck.analyzer.exception.AnalysisException;
import org.owasp.dependencycheck.analyzer.exception.ArchiveExtractionException;
@@ -50,10 +49,6 @@ public final class ExtractionUtil {
* The logger.
*/
private static final Logger LOGGER = LoggerFactory.getLogger(ExtractionUtil.class);
/**
* The buffer size to use when extracting files from the archive.
*/
private static final int BUFFER_SIZE = 4096;
/**
* Private constructor for a utility class.
@@ -108,12 +103,10 @@ public final class ExtractionUtil {
} else {
final File file = new File(extractTo, entry.getName());
if (engine == null || engine.accept(file)) {
BufferedOutputStream bos = null;
FileOutputStream fos;
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos, BUFFER_SIZE);
transferUsingBuffer(zis, bos);
IOUtils.copy(zis, fos);
} catch (FileNotFoundException ex) {
LOGGER.debug("", ex);
final String msg = String.format("Unable to find file '%s'.", file.getName());
@@ -123,7 +116,7 @@ public final class ExtractionUtil {
final String msg = String.format("IO Exception while parsing file '%s'.", file.getName());
throw new ExtractionException(msg, ex);
} finally {
closeStream(bos);
closeStream(fos);
}
}
}
@@ -225,13 +218,11 @@ public final class ExtractionUtil {
if (filter.accept(file.getParentFile(), file.getName())) {
LOGGER.debug("Extracting '{}'",
file.getPath());
BufferedOutputStream bos = null;
FileOutputStream fos = null;
try {
createParentFile(file);
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos, BUFFER_SIZE);
transferUsingBuffer(input, bos);
IOUtils.copy(input, fos);
} catch (FileNotFoundException ex) {
LOGGER.debug("", ex);
final String msg = String.format("Unable to find file '%s'.",
@@ -244,29 +235,11 @@ public final class ExtractionUtil {
file.getName());
throw new ExtractionException(msg, ex);
} finally {
closeStream(bos);
closeStream(fos);
}
}
}
/**
* Transfers data from one stream to another using a buffer.
*
* @param input the input stream
* @param bos the output stream
* @throws IOException thrown if there is an error reading/writing to the streams
*/
private static void transferUsingBuffer(InputStream input,
BufferedOutputStream bos) throws IOException {
int count;
final byte[] data = new byte[BUFFER_SIZE];
while ((count = input.read(data, 0, BUFFER_SIZE)) != -1) {
bos.write(data, 0, count);
}
bos.flush();
}
/**
* Closes the stream.
*

View File

@@ -23,6 +23,7 @@ public abstract class Filter<T> {
public Iterable<T> filter(final Iterable<T> iterable) {
return new Iterable<T>() {
@Override
public Iterator<T> iterator() {
return filter(iterable.iterator());
}
@@ -39,10 +40,12 @@ public abstract class Filter<T> {
toNext();
}
@Override
public boolean hasNext() {
return next != null;
}
@Override
public T next() {
if (next == null) {
throw new NoSuchElementException();
@@ -52,6 +55,7 @@ public abstract class Filter<T> {
return returnValue;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}

View File

@@ -100,7 +100,7 @@ public class PomHandler extends DefaultHandler {
/**
* The current node text being extracted from the element.
*/
private StringBuffer currentText;
private StringBuilder currentText;
/**
* Handles the start element event.
@@ -113,7 +113,7 @@ public class PomHandler extends DefaultHandler {
*/
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
currentText = new StringBuffer();
currentText = new StringBuilder();
stack.push(qName);
if (LICENSE.equals(qName)) {
license = new License();

View File

@@ -26,6 +26,11 @@ import java.io.IOException;
*/
public class PomParseException extends IOException {
/**
* The serial version UID for serialization.
*/
private static final long serialVersionUID = 1L;
/**
* Creates a new SuppressionParseException.
*/

View File

@@ -35,5 +35,6 @@ INSERT_PROPERTY=INSERT INTO properties (id, value) VALUES (?, ?)
UPDATE_PROPERTY=UPDATE properties SET value = ? WHERE id = ?
DELETE_PROPERTY=DELETE FROM properties WHERE id = ?
#the following two statements are unused and are only referenecd in dead code
DELETE_UNUSED_DICT_CPE=DELETE FROM cpeEntry WHERE dictionaryEntry=true AND id NOT IN (SELECT cpeEntryId FROM software)
ADD_DICT_CPE=MERGE INTO cpeEntry (cpe, vendor, product, dictionaryEntry) KEY(cpe) VALUES(?,?,?,true)

View File

@@ -56,6 +56,13 @@
<cpe>cpe:/a:oracle:glassfish</cpe>
<cpe>cpe:/a:oracle:oracle_client</cpe>
</suppress>
<suppress base="true">
<notes><![CDATA[
Suppresses false positives on glassfish
]]></notes>
<gav regex="true">org\.glassfish:.*(json|faces).*</gav>
<cpe>cpe:/a:oracle:glassfish</cpe>
</suppress>
<suppress base="true">
<notes><![CDATA[
Suppresses false positives on the grizzly-framework

View File

@@ -52,6 +52,7 @@ public class CMakeAnalyzerTest extends BaseDBTestCase {
*
* @throws Exception if there is a problem
*/
@Override
@Before
public void setUp() throws Exception {
super.setUp();

View File

@@ -17,14 +17,8 @@
*/
package org.owasp.dependencycheck.analyzer;
import java.io.File;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.owasp.dependencycheck.BaseTest;
import org.owasp.dependencycheck.Engine;
import org.owasp.dependencycheck.data.cpe.AbstractDatabaseTestCase;
import org.owasp.dependencycheck.dependency.Dependency;
import org.owasp.dependencycheck.utils.Settings;
/**
*

View File

@@ -23,8 +23,6 @@ import org.owasp.dependencycheck.dependency.Dependency;
import org.owasp.dependencycheck.dependency.Evidence;
import java.io.File;
import java.util.HashSet;
import java.util.Set;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

View File

@@ -17,39 +17,14 @@
*/
package org.owasp.dependencycheck.data.cpe;
import junit.framework.TestCase;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
/**
*
* @author Jeremy Long
*/
public class IndexEntryTest extends TestCase {
@BeforeClass
public static void setUpClass() throws Exception {
}
@AfterClass
public static void tearDownClass() throws Exception {
}
@Before
@Override
public void setUp() throws Exception {
super.setUp();
}
@After
@Override
public void tearDown() throws Exception {
super.tearDown();
}
public class IndexEntryTest {
/**
* Test of setName method, of class IndexEntry.

View File

@@ -47,11 +47,13 @@ public class TokenPairConcatenatingFilterTest extends BaseTokenStreamTestCase {
public static void tearDownClass() {
}
@Override
@Before
public void setUp() throws Exception {
super.setUp();
}
@Override
@After
public void tearDown() throws Exception {
super.tearDown();

View File

@@ -18,7 +18,6 @@
package org.owasp.dependencycheck.data.nuget;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.io.PrintStream;
import static org.junit.Assert.assertEquals;

View File

@@ -19,6 +19,7 @@ package org.owasp.dependencycheck.data.nvdcve;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.junit.Assert;
@@ -121,7 +122,7 @@ public class CveDBIntegrationTest extends BaseDBTestCase {
@Test
public void testGetMatchingSoftware() throws Exception {
CveDB instance = null;
HashMap<String, Boolean> versions = new HashMap<String, Boolean>();
Map<String, Boolean> versions = new HashMap<String, Boolean>();
DependencyVersion identifiedVersion = new DependencyVersion("1.0.1o");
versions.put("cpe:/a:openssl:openssl:1.0.1e", Boolean.FALSE);
try {

View File

@@ -15,12 +15,7 @@
*/
package org.owasp.dependencycheck.data.update;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
import org.owasp.dependencycheck.BaseTest;
/**

View File

@@ -20,13 +20,9 @@ package org.owasp.dependencycheck.suppression;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.junit.After;
import org.junit.AfterClass;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.owasp.dependencycheck.BaseTest;
import org.owasp.dependencycheck.dependency.Dependency;
@@ -40,25 +36,6 @@ import org.owasp.dependencycheck.dependency.Vulnerability;
*/
public class SuppressionRuleTest {
public SuppressionRuleTest() {
}
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
//<editor-fold defaultstate="collapsed" desc="Stupid tests of properties">
/**
* Test of FilePath property, of class SuppressionRule.
@@ -91,7 +68,7 @@ public class SuppressionRuleTest {
@Test
public void testCpe() {
SuppressionRule instance = new SuppressionRule();
ArrayList<PropertyType> cpe = new ArrayList<PropertyType>();
List<PropertyType> cpe = new ArrayList<PropertyType>();
instance.setCpe(cpe);
assertFalse(instance.hasCpe());
PropertyType pt = new PropertyType();
@@ -109,7 +86,7 @@ public class SuppressionRuleTest {
@Test
public void testGetCvssBelow() {
SuppressionRule instance = new SuppressionRule();
ArrayList<Float> cvss = new ArrayList<Float>();
List<Float> cvss = new ArrayList<Float>();
instance.setCvssBelow(cvss);
assertFalse(instance.hasCvssBelow());
instance.addCvssBelow(0.7f);
@@ -124,7 +101,7 @@ public class SuppressionRuleTest {
@Test
public void testCwe() {
SuppressionRule instance = new SuppressionRule();
ArrayList<String> cwe = new ArrayList<String>();
List<String> cwe = new ArrayList<String>();
instance.setCwe(cwe);
assertFalse(instance.hasCwe());
instance.addCwe("2");
@@ -139,7 +116,7 @@ public class SuppressionRuleTest {
@Test
public void testCve() {
SuppressionRule instance = new SuppressionRule();
ArrayList<String> cve = new ArrayList<String>();
List<String> cve = new ArrayList<String>();
instance.setCve(cve);
assertFalse(instance.hasCve());
instance.addCve("CVE-2013-1337");

View File

@@ -20,13 +20,9 @@ package org.owasp.dependencycheck.utils;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import org.junit.After;
import org.junit.AfterClass;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
/**
@@ -35,25 +31,6 @@ import org.junit.Test;
*/
public class DependencyVersionTest {
public DependencyVersionTest() {
}
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
/**
* Test of parseVersion method, of class DependencyVersion.
*/
@@ -73,6 +50,7 @@ public class DependencyVersionTest {
assertEquals(2, parts.size());
assertEquals("x6", parts.get(0));
assertEquals("0", parts.get(1));
// TODO(code review): should this be here/do something?
//assertEquals("0", parts.get(2));
}
@@ -84,6 +62,7 @@ public class DependencyVersionTest {
public void testIterator() {
DependencyVersion instance = new DependencyVersion("1.2.3");
Iterator result = instance.iterator();
assertTrue(result.hasNext());
int count = 1;
while (result.hasNext()) {
String v = (String) result.next();
@@ -155,7 +134,6 @@ public class DependencyVersionTest {
public void testCompareTo() {
DependencyVersion instance = new DependencyVersion("1.2.3");
DependencyVersion version = new DependencyVersion("1.2.3");
int expResult = 0;
assertEquals(0, instance.compareTo(version));
version = new DependencyVersion("1.1");
assertEquals(1, instance.compareTo(version));
@@ -204,7 +182,7 @@ public class DependencyVersionTest {
DependencyVersion instance = new DependencyVersion();
List<String> versionParts = Arrays.asList("1", "1", "1");
instance.setVersionParts(versionParts);
List<String> expResult = Arrays.asList("1", "1", "1");;
List<String> expResult = Arrays.asList("1", "1", "1");
List<String> result = instance.getVersionParts();
assertEquals(expResult, result);
}

View File

@@ -64,6 +64,7 @@ public class FilterTest {
}
private static final Filter<String> TEST_FILTER
= new Filter<String>() {
@Override
public boolean passes(String str) {
return str.contains("keep");
}

View File

@@ -18,10 +18,7 @@ package org.owasp.dependencycheck.xml.pom;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;

View File

@@ -15,18 +15,11 @@
*/
package org.owasp.dependencycheck.xml.pom;
import org.owasp.dependencycheck.xml.pom.PomUtils;
import java.io.File;
import javax.xml.transform.sax.SAXSource;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
import org.owasp.dependencycheck.BaseTest;
import org.owasp.dependencycheck.dependency.Dependency;
import org.owasp.dependencycheck.xml.pom.Model;
/**
*
@@ -34,25 +27,6 @@ import org.owasp.dependencycheck.xml.pom.Model;
*/
public class PomUtilsTest {
public PomUtilsTest() {
}
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
/**
* Test of readPom method, of class PomUtils.
*/

View File

@@ -3,7 +3,7 @@ Dependency-Check-Maven
Dependency-Check is a utility that attempts to detect publicly disclosed vulnerabilities contained within project dependencies. It does this by determining if there is a Common Platform Enumeration (CPE) identifier for a given dependency. If found, it will generate a report linking to the associated CVE entries.
Documentation and links to production binary releases can be found on the [github pages](http://jeremylong.github.io/DependencyCheck/dependency-check-maven/usage.html).
Documentation and links to production binary releases can be found on the [github pages](http://jeremylong.github.io/DependencyCheck/dependency-check-maven/index.html).
Mailing List
-
@@ -17,10 +17,10 @@ Copyright & License
Dependency-Check is Copyright (c) 2012-2014 Jeremy Long. All Rights Reserved.
Permission to modify and redistribute is granted under the terms of the Apache 2.0 license. See the [LICENSE.txt](https://github.com/jeremylong/DependencyCheck/dependency-check-cli/blob/master/LICENSE.txt) file for the full license.
Permission to modify and redistribute is granted under the terms of the Apache 2.0 license. See the [LICENSE.txt](https://raw.githubusercontent.com/jeremylong/DependencyCheck/master/LICENSE.txt) file for the full license.
Dependency-Check makes use of several other open source libraries. Please see the [NOTICE.txt] [notices] file for more information.
[subscribe]: mailto:dependency-check+subscribe@googlegroups.com
[post]: mailto:dependency-check@googlegroups.com
[notices]: https://github.com/jeremylong/DependencyCheck/blob/master/NOTICES.txt
[notices]: https://raw.githubusercontent.com/jeremylong/DependencyCheck/master/dependency-check-maven/NOTICE.txt

View File

@@ -69,7 +69,8 @@ public class AggregateMojo extends BaseDependencyCheckMojo {
for (MavenProject current : getReactorProjects()) {
final File dataFile = getDataFile(current);
if (dataFile == null) { //dc was never run on this project. write the ser to the target.
getLog().error(String.format("Module '%s' did not execute dependency-check; an attempt will be made to perform the check but dependencies may be missed resulting in false negatives.", current.getName()));
getLog().error(String.format("Module '%s' did not execute dependency-check; an attempt will be made to perform "
+ "the check but dependencies may be missed resulting in false negatives.", current.getName()));
generateDataFile(engine, current);
}
}
@@ -262,6 +263,7 @@ public class AggregateMojo extends BaseDependencyCheckMojo {
* @param locale the location
* @return the report name
*/
@Override
public String getName(Locale locale) {
return "dependency-check:aggregate";
}
@@ -272,6 +274,7 @@ public class AggregateMojo extends BaseDependencyCheckMojo {
* @param locale The Locale to get the description for
* @return the description
*/
@Override
public String getDescription(Locale locale) {
return "Generates an aggregate report of all child Maven projects providing details on any "
+ "published vulnerabilities within project dependencies. This report is a best "

View File

@@ -352,6 +352,7 @@ public abstract class BaseDependencyCheckMojo extends AbstractMojo implements Ma
* @throws MavenReportException if a maven report exception occurs
* @deprecated use {@link #generate(org.apache.maven.doxia.sink.Sink, java.util.Locale)} instead.
*/
@Override
@Deprecated
public final void generate(@SuppressWarnings("deprecation") org.codehaus.doxia.sink.Sink sink, Locale locale) throws MavenReportException {
generate((Sink) sink, locale);
@@ -519,6 +520,7 @@ public abstract class BaseDependencyCheckMojo extends AbstractMojo implements Ma
*
* @return the output name
*/
@Override
public String getOutputName() {
if ("HTML".equalsIgnoreCase(this.format) || "ALL".equalsIgnoreCase(this.format)) {
return "dependency-check-report";
@@ -537,6 +539,7 @@ public abstract class BaseDependencyCheckMojo extends AbstractMojo implements Ma
*
* @return the category name
*/
@Override
public String getCategoryName() {
return MavenReport.CATEGORY_PROJECT_REPORTS;
}

View File

@@ -95,6 +95,7 @@ public class CheckMojo extends BaseDependencyCheckMojo {
* @param locale the location
* @return the report name
*/
@Override
public String getName(Locale locale) {
return "dependency-check";
}
@@ -105,6 +106,7 @@ public class CheckMojo extends BaseDependencyCheckMojo {
* @param locale The Locale to get the description for
* @return the description
*/
@Override
public String getDescription(Locale locale) {
return "Generates a report providing details on any published vulnerabilities within project dependencies. "
+ "This report is a best effort and may contain false positives and false negatives.";

View File

@@ -89,6 +89,7 @@ public class PurgeMojo extends BaseDependencyCheckMojo {
* @param locale the location
* @return the report name
*/
@Override
public String getName(Locale locale) {
return "dependency-check-purge";
}
@@ -99,6 +100,7 @@ public class PurgeMojo extends BaseDependencyCheckMojo {
* @param locale The Locale to get the description for
* @return the description
*/
@Override
public String getDescription(Locale locale) {
return "Purges the local cache of the NVD dataT.";
}

View File

@@ -78,6 +78,7 @@ public class UpdateMojo extends BaseDependencyCheckMojo {
* @param locale the location
* @return the report name
*/
@Override
public String getName(Locale locale) {
return "dependency-check-update";
}
@@ -88,6 +89,7 @@ public class UpdateMojo extends BaseDependencyCheckMojo {
* @param locale The Locale to get the description for
* @return the description
*/
@Override
public String getDescription(Locale locale) {
return "Updates the local cache of the NVD data from NIST.";
}

View File

@@ -28,6 +28,11 @@ import org.slf4j.helpers.MessageFormatter;
*/
public class MavenLoggerAdapter extends MarkerIgnoringBase {
/**
* The serial version UID for serialization.
*/
private static final long serialVersionUID = 1L;
/**
* A reference to the Maven log.
*/

View File

@@ -28,7 +28,9 @@ import org.slf4j.spi.LoggerFactoryBinder;
*
* @author colezlaw
*/
//CSOFF: FinalClass
public class StaticLoggerBinder implements LoggerFactoryBinder {
//CSON: FinalClass
/**
* The unique instance of this class
@@ -64,7 +66,11 @@ public class StaticLoggerBinder implements LoggerFactoryBinder {
* with each release.
*/
// to avoid constant folding by the compiler, this field must *not* be final
//CSOFF: StaticVariableName
//CSOFF: VisibilityModifier
public static String REQUESTED_API_VERSION = "1.7.12"; // final
//CSON: VisibilityModifier
//CSON: StaticVariableName
/**
* The logger factory class string.

View File

@@ -155,5 +155,10 @@ Copyright (c) 2014 - Jeremy Long. All Rights Reserved.
<artifactId>logback-classic</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.code.findbugs</groupId>
<artifactId>annotations</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
</project>

View File

@@ -1,153 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*
*/
package org.owasp.dependencycheck.org.apache.tools.ant;
/**
* Signals an error condition during a build
*/
public class BuildException extends RuntimeException {
private static final long serialVersionUID = -5419014565354664240L;
/** Location in the build file where the exception occurred */
private Location location = Location.UNKNOWN_LOCATION;
/**
* Constructs a build exception with no descriptive information.
*/
public BuildException() {
super();
}
/**
* Constructs an exception with the given descriptive message.
*
* @param message A description of or information about the exception.
* Should not be <code>null</code>.
*/
public BuildException(String message) {
super(message);
}
/**
* Constructs an exception with the given message and exception as
* a root cause.
*
* @param message A description of or information about the exception.
* Should not be <code>null</code> unless a cause is specified.
* @param cause The exception that might have caused this one.
* May be <code>null</code>.
*/
public BuildException(String message, Throwable cause) {
super(message, cause);
}
/**
* Constructs an exception with the given message and exception as
* a root cause and a location in a file.
*
* @param msg A description of or information about the exception.
* Should not be <code>null</code> unless a cause is specified.
* @param cause The exception that might have caused this one.
* May be <code>null</code>.
* @param location The location in the project file where the error
* occurred. Must not be <code>null</code>.
*/
public BuildException(String msg, Throwable cause, Location location) {
this(msg, cause);
this.location = location;
}
/**
* Constructs an exception with the given exception as a root cause.
*
* @param cause The exception that might have caused this one.
* Should not be <code>null</code>.
*/
public BuildException(Throwable cause) {
super(cause);
}
/**
* Constructs an exception with the given descriptive message and a
* location in a file.
*
* @param message A description of or information about the exception.
* Should not be <code>null</code>.
* @param location The location in the project file where the error
* occurred. Must not be <code>null</code>.
*/
public BuildException(String message, Location location) {
super(message);
this.location = location;
}
/**
* Constructs an exception with the given exception as
* a root cause and a location in a file.
*
* @param cause The exception that might have caused this one.
* Should not be <code>null</code>.
* @param location The location in the project file where the error
* occurred. Must not be <code>null</code>.
*/
public BuildException(Throwable cause, Location location) {
this(cause);
this.location = location;
}
/**
* Returns the nested exception, if any.
*
* @return the nested exception, or <code>null</code> if no
* exception is associated with this one
* @deprecated Use {@link #getCause} instead.
*/
public Throwable getException() {
return getCause();
}
/**
* Returns the location of the error and the error message.
*
* @return the location of the error and the error message
*/
public String toString() {
return location.toString() + getMessage();
}
/**
* Sets the file location where the error occurred.
*
* @param location The file location where the error occurred.
* Must not be <code>null</code>.
*/
public void setLocation(Location location) {
this.location = location;
}
/**
* Returns the file location where the error occurred.
*
* @return the file location where the error occurred.
*/
public Location getLocation() {
return location;
}
}

View File

@@ -1,158 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*
*/
package org.owasp.dependencycheck.org.apache.tools.ant;
import java.io.File;
/**
* An interface used to describe the actions required of any type of
* directory scanner.
*
*/
public interface FileScanner {
/**
* Adds default exclusions to the current exclusions set.
*/
void addDefaultExcludes();
/**
* Returns the base directory to be scanned.
* This is the directory which is scanned recursively.
*
* @return the base directory to be scanned
*/
File getBasedir();
/**
* Returns the names of the directories which matched at least one of the
* include patterns and at least one of the exclude patterns.
* The names are relative to the base directory.
*
* @return the names of the directories which matched at least one of the
* include patterns and at least one of the exclude patterns.
*/
String[] getExcludedDirectories();
/**
* Returns the names of the files which matched at least one of the
* include patterns and at least one of the exclude patterns.
* The names are relative to the base directory.
*
* @return the names of the files which matched at least one of the
* include patterns and at least one of the exclude patterns.
*
*/
String[] getExcludedFiles();
/**
* Returns the names of the directories which matched at least one of the
* include patterns and none of the exclude patterns.
* The names are relative to the base directory.
*
* @return the names of the directories which matched at least one of the
* include patterns and none of the exclude patterns.
*/
String[] getIncludedDirectories();
/**
* Returns the names of the files which matched at least one of the
* include patterns and none of the exclude patterns.
* The names are relative to the base directory.
*
* @return the names of the files which matched at least one of the
* include patterns and none of the exclude patterns.
*/
String[] getIncludedFiles();
/**
* Returns the names of the directories which matched none of the include
* patterns. The names are relative to the base directory.
*
* @return the names of the directories which matched none of the include
* patterns.
*/
String[] getNotIncludedDirectories();
/**
* Returns the names of the files which matched none of the include
* patterns. The names are relative to the base directory.
*
* @return the names of the files which matched none of the include
* patterns.
*/
String[] getNotIncludedFiles();
/**
* Scans the base directory for files which match at least one include
* pattern and don't match any exclude patterns.
*
* @exception IllegalStateException if the base directory was set
* incorrectly (i.e. if it is <code>null</code>, doesn't exist,
* or isn't a directory).
*/
void scan() throws IllegalStateException;
/**
* Sets the base directory to be scanned. This is the directory which is
* scanned recursively. All '/' and '\' characters should be replaced by
* <code>File.separatorChar</code>, so the separator used need not match
* <code>File.separatorChar</code>.
*
* @param basedir The base directory to scan.
* Must not be <code>null</code>.
*/
void setBasedir(String basedir);
/**
* Sets the base directory to be scanned. This is the directory which is
* scanned recursively.
*
* @param basedir The base directory for scanning.
* Should not be <code>null</code>.
*/
void setBasedir(File basedir);
/**
* Sets the list of exclude patterns to use.
*
* @param excludes A list of exclude patterns.
* May be <code>null</code>, indicating that no files
* should be excluded. If a non-<code>null</code> list is
* given, all elements must be non-<code>null</code>.
*/
void setExcludes(String[] excludes);
/**
* Sets the list of include patterns to use.
*
* @param includes A list of include patterns.
* May be <code>null</code>, indicating that all files
* should be included. If a non-<code>null</code>
* list is given, all elements must be
* non-<code>null</code>.
*/
void setIncludes(String[] includes);
/**
* Sets whether or not the file system should be regarded as case sensitive.
*
* @param isCaseSensitive whether or not the file system should be
* regarded as a case sensitive one
*/
void setCaseSensitive(boolean isCaseSensitive);
}

View File

@@ -1,178 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*
*/
package org.owasp.dependencycheck.org.apache.tools.ant;
import java.io.Serializable;
import org.owasp.dependencycheck.org.apache.tools.ant.util.FileUtils;
import org.xml.sax.Locator;
/**
* Stores the location of a piece of text within a file (file name,
* line number and column number). Note that the column number is
* currently ignored.
*
*/
public class Location implements Serializable {
private static final long serialVersionUID = 1L;
/** Name of the file. */
private final String fileName;
/** Line number within the file. */
private final int lineNumber;
/** Column number within the file. */
private final int columnNumber;
/** Location to use when one is needed but no information is available */
public static final Location UNKNOWN_LOCATION = new Location();
private static final FileUtils FILE_UTILS = FileUtils.getFileUtils();
/**
* Creates an "unknown" location.
*/
private Location() {
this(null, 0, 0);
}
/**
* Creates a location consisting of a file name but no line number or
* column number.
*
* @param fileName The name of the file. May be <code>null</code>,
* in which case the location is equivalent to
* {@link #UNKNOWN_LOCATION UNKNOWN_LOCATION}.
*/
public Location(String fileName) {
this(fileName, 0, 0);
}
/**
* Creates a location from the SAX locator using the system ID as
* the filename.
*
* @param loc Must not be <code>null</code>.
*
* @since Ant 1.6
*/
public Location(Locator loc) {
this(loc.getSystemId(), loc.getLineNumber(), loc.getColumnNumber());
}
/**
* Creates a location consisting of a file name, line number and
* column number.
*
* @param fileName The name of the file. May be <code>null</code>,
* in which case the location is equivalent to
* {@link #UNKNOWN_LOCATION UNKNOWN_LOCATION}.
*
* @param lineNumber Line number within the file. Use 0 for unknown
* positions within a file.
* @param columnNumber Column number within the line.
*/
public Location(String fileName, int lineNumber, int columnNumber) {
if (fileName != null && fileName.startsWith("file:")) {
this.fileName = FILE_UTILS.fromURI(fileName);
} else {
this.fileName = fileName;
}
this.lineNumber = lineNumber;
this.columnNumber = columnNumber;
}
/**
* @return the filename portion of the location
* @since Ant 1.6
*/
public String getFileName() {
return fileName;
}
/**
* @return the line number
* @since Ant 1.6
*/
public int getLineNumber() {
return lineNumber;
}
/**
* @return the column number
* @since Ant 1.7
*/
public int getColumnNumber() {
return columnNumber;
}
/**
* Returns the file name, line number, a colon and a trailing space.
* An error message can be appended easily. For unknown locations, an
* empty string is returned.
*
* @return a String of the form <code>"fileName:lineNumber: "</code>
* if both file name and line number are known,
* <code>"fileName: "</code> if only the file name is known,
* and the empty string for unknown locations.
*/
public String toString() {
StringBuffer buf = new StringBuffer();
if (fileName != null) {
buf.append(fileName);
if (lineNumber != 0) {
buf.append(":");
buf.append(lineNumber);
}
buf.append(": ");
}
return buf.toString();
}
/**
* Equality operation.
* @param other the object to compare to.
* @return true if the other object contains the same information
* as this object.
* @since Ant 1.6.3
*/
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (other == null) {
return false;
}
if (!(other.getClass() == getClass())) {
return false;
}
return toString().equals(other.toString());
}
/**
* Hash operation.
* @return a hash code value for this location.
* @since Ant 1.6.3
*/
public int hashCode() {
return toString().hashCode();
}
}

View File

@@ -1,165 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*
*/
package org.owasp.dependencycheck.org.apache.tools.ant;
import java.io.File;
import java.util.NoSuchElementException;
import java.util.StringTokenizer;
import org.owasp.dependencycheck.org.apache.tools.ant.taskdefs.condition.Os;
/**
* A Path tokenizer takes a path and returns the components that make up
* that path.
*
* The path can use path separators of either ':' or ';' and file separators
* of either '/' or '\'.
*
*/
public class PathTokenizer {
/**
* A tokenizer to break the string up based on the ':' or ';' separators.
*/
private StringTokenizer tokenizer;
/**
* A String which stores any path components which have been read ahead
* due to DOS filesystem compensation.
*/
private String lookahead = null;
/**
* A boolean that determines if we are running on Novell NetWare, which
* exhibits slightly different path name characteristics (multi-character
* volume / drive names)
*/
private boolean onNetWare = Os.isFamily("netware");
/**
* Flag to indicate whether or not we are running on a platform with a
* DOS style filesystem
*/
private boolean dosStyleFilesystem;
/**
* Constructs a path tokenizer for the specified path.
*
* @param path The path to tokenize. Must not be <code>null</code>.
*/
public PathTokenizer(String path) {
if (onNetWare) {
// For NetWare, use the boolean=true mode, so we can use delimiter
// information to make a better decision later.
tokenizer = new StringTokenizer(path, ":;", true);
} else {
// on Windows and Unix, we can ignore delimiters and still have
// enough information to tokenize correctly.
tokenizer = new StringTokenizer(path, ":;", false);
}
dosStyleFilesystem = File.pathSeparatorChar == ';';
}
/**
* Tests if there are more path elements available from this tokenizer's
* path. If this method returns <code>true</code>, then a subsequent call
* to nextToken will successfully return a token.
*
* @return <code>true</code> if and only if there is at least one token
* in the string after the current position; <code>false</code> otherwise.
*/
public boolean hasMoreTokens() {
if (lookahead != null) {
return true;
}
return tokenizer.hasMoreTokens();
}
/**
* Returns the next path element from this tokenizer.
*
* @return the next path element from this tokenizer.
*
* @exception NoSuchElementException if there are no more elements in this
* tokenizer's path.
*/
public String nextToken() throws NoSuchElementException {
String token = null;
if (lookahead != null) {
token = lookahead;
lookahead = null;
} else {
token = tokenizer.nextToken().trim();
}
if (!onNetWare) {
if (token.length() == 1 && Character.isLetter(token.charAt(0))
&& dosStyleFilesystem
&& tokenizer.hasMoreTokens()) {
// we are on a dos style system so this path could be a drive
// spec. We look at the next token
String nextToken = tokenizer.nextToken().trim();
if (nextToken.startsWith("\\") || nextToken.startsWith("/")) {
// we know we are on a DOS style platform and the next path
// starts with a slash or backslash, so we know this is a
// drive spec
token += ":" + nextToken;
} else {
// store the token just read for next time
lookahead = nextToken;
}
}
} else {
// we are on NetWare, tokenizing is handled a little differently,
// due to the fact that NetWare has multiple-character volume names.
if (token.equals(File.pathSeparator) || token.equals(":")) {
// ignore ";" and get the next token
token = tokenizer.nextToken().trim();
}
if (tokenizer.hasMoreTokens()) {
// this path could be a drive spec, so look at the next token
String nextToken = tokenizer.nextToken().trim();
// make sure we aren't going to get the path separator next
if (!nextToken.equals(File.pathSeparator)) {
if (nextToken.equals(":")) {
if (!token.startsWith("/") && !token.startsWith("\\")
&& !token.startsWith(".")
&& !token.startsWith("..")) {
// it indeed is a drive spec, get the next bit
String oneMore = tokenizer.nextToken().trim();
if (!oneMore.equals(File.pathSeparator)) {
token += ":" + oneMore;
} else {
token += ":";
lookahead = oneMore;
}
}
// implicit else: ignore the ':' since we have either a
// UNIX or a relative path
} else {
// store the token just read for next time
lookahead = nextToken;
}
}
}
}
return token;
}
}

View File

@@ -1,161 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*
*/
package org.owasp.dependencycheck.org.apache.tools.ant;
/**
* Base class for components of a project, including tasks and data types. Provides common facilities.
*
*/
public abstract class ProjectComponent implements Cloneable {
// // CheckStyle:VisibilityModifier OFF - bc
// /**
// * Project object of this component.
// * @deprecated since 1.6.x.
// * You should not be directly accessing this variable directly.
// * You should access project object via the getProject()
// * or setProject() accessor/mutators.
// */
// protected Project project;
/**
* Location within the build file of this task definition.
*
* @deprecated since 1.6.x. You should not be accessing this variable directly. Please use the
* {@link #getLocation()} method.
*/
protected Location location = Location.UNKNOWN_LOCATION;
/**
* Description of this component, if any.
*
* @deprecated since 1.6.x. You should not be accessing this variable directly.
*/
protected String description;
// CheckStyle:VisibilityModifier ON
/**
* Sole constructor.
*/
public ProjectComponent() {
}
// /**
// * Sets the project object of this component. This method is used by
// * Project when a component is added to it so that the component has
// * access to the functions of the project. It should not be used
// * for any other purpose.
// *
// * @param project Project in whose scope this component belongs.
// * Must not be <code>null</code>.
// */
// public void setProject(Project project) {
// this.project = project;
// }
//
// /**
// * Returns the project to which this component belongs.
// *
// * @return the components's project.
// */
// public Project getProject() {
// return project;
// }
/**
* Returns the file/location where this task was defined.
*
* @return the file/location where this task was defined. Should not return <code>null</code>.
* Location.UNKNOWN_LOCATION is used for unknown locations.
*
* @see Location#UNKNOWN_LOCATION
*/
public Location getLocation() {
return location;
}
/**
* Sets the file/location where this task was defined.
*
* @param location The file/location where this task was defined. Should not be <code>null</code>--use
* Location.UNKNOWN_LOCATION if the location isn't known.
*
* @see Location#UNKNOWN_LOCATION
*/
public void setLocation(Location location) {
this.location = location;
}
/**
* Sets a description of the current action. This may be used for logging purposes.
*
* @param desc Description of the current action. May be <code>null</code>, indicating that no description is
* available.
*
*/
public void setDescription(String desc) {
description = desc;
}
/**
* Returns the description of the current action.
*
* @return the description of the current action, or <code>null</code> if no description is available.
*/
public String getDescription() {
return description;
}
/**
* Logs a message with the default (INFO) priority.
*
* @param msg The message to be logged. Should not be <code>null</code>.
*/
public void log(String msg) {
// log(msg, Project.MSG_INFO);
}
/**
* Logs a message with the given priority.
*
* @param msg The message to be logged. Should not be <code>null</code>.
* @param msgLevel the message priority at which this message is to be logged.
*/
public void log(String msg, int msgLevel) {
// if (getProject() != null) {
// getProject().log(msg, msgLevel);
// } else {
// // 'reasonable' default, if the component is used without
// // a Project ( for example as a standalone Bean ).
// // Most ant components can be used this way.
// if (msgLevel <= Project.MSG_INFO) {
// System.err.println(msg);
// }
// }
}
/**
* @since Ant 1.7
* @return a shallow copy of this projectcomponent.
* @throws CloneNotSupportedException does not happen, but is declared to allow subclasses to do so.
*/
public Object clone() throws CloneNotSupportedException {
ProjectComponent pc = (ProjectComponent) super.clone();
pc.setLocation(getLocation());
//pc.setProject(getProject());
return pc;
}
}

View File

@@ -1,530 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*
*/
package org.owasp.dependencycheck.org.apache.tools.ant.launch;
import java.net.MalformedURLException;
import java.net.URL;
import java.io.File;
import java.io.FilenameFilter;
import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.text.CharacterIterator;
import java.text.StringCharacterIterator;
import java.util.Locale;
import org.owasp.dependencycheck.org.apache.tools.ant.util.FileUtils;
// CheckStyle:LineLengthCheck OFF - urls are long!
/**
* The Locator is a utility class which is used to find certain items
* in the environment.
*
* It is used at boot time in the launcher, and cannot make use of any of Ant's other classes.
*
* This is a surprisingly brittle piece of code, and has had lots of bugs filed against it.
* {@link <a href="http://issues.apache.org/bugzilla/show_bug.cgi?id=42275">running ant off a network share can cause Ant to fail</a>}
* {@link <a href="http://issues.apache.org/bugzilla/show_bug.cgi?id=8031">use File.toURI().toURL().toExternalForm()</a>}
* {@link <a href="http://issues.apache.org/bugzilla/show_bug.cgi?id=42222">Locator implementation not encoding URI strings properly: spaces in paths</a>}
* It also breaks Eclipse 3.3 Betas
* {@link <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=183283">Exception if installation path has spaces</a>}
*
* Be very careful when making changes to this class, as a break will upset a lot of people.
* @since Ant 1.6
*/
// CheckStyle:LineLengthCheck ON - urls are long!
public final class Locator {
private static final int NIBBLE = 4;
private static final int NIBBLE_MASK = 0xF;
private static final int ASCII_SIZE = 128;
private static final int BYTE_SIZE = 256;
private static final int WORD = 16;
private static final int SPACE = 0x20;
private static final int DEL = 0x7F;
/**
* encoding used to represent URIs
*/
public static final String URI_ENCODING = "UTF-8";
// stolen from org.apache.xerces.impl.XMLEntityManager#getUserDir()
// of the Xerces-J team
// which ASCII characters need to be escaped
private static boolean[] gNeedEscaping = new boolean[ASCII_SIZE];
// the first hex character if a character needs to be escaped
private static char[] gAfterEscaping1 = new char[ASCII_SIZE];
// the second hex character if a character needs to be escaped
private static char[] gAfterEscaping2 = new char[ASCII_SIZE];
private static char[] gHexChs = {'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
/** Error string used when an invalid uri is seen */
public static final String ERROR_NOT_FILE_URI
= "Can only handle valid file: URIs, not ";
// initialize the above 3 arrays
static {
for (int i = 0; i < SPACE; i++) {
gNeedEscaping[i] = true;
gAfterEscaping1[i] = gHexChs[i >> NIBBLE];
gAfterEscaping2[i] = gHexChs[i & NIBBLE_MASK];
}
gNeedEscaping[DEL] = true;
gAfterEscaping1[DEL] = '7';
gAfterEscaping2[DEL] = 'F';
char[] escChs = {' ', '<', '>', '#', '%', '"', '{', '}',
'|', '\\', '^', '~', '[', ']', '`'};
int len = escChs.length;
char ch;
for (int i = 0; i < len; i++) {
ch = escChs[i];
gNeedEscaping[ch] = true;
gAfterEscaping1[ch] = gHexChs[ch >> NIBBLE];
gAfterEscaping2[ch] = gHexChs[ch & NIBBLE_MASK];
}
}
/**
* Not instantiable
*/
private Locator() {
}
/**
* Find the directory or jar file the class has been loaded from.
*
* @param c the class whose location is required.
* @return the file or jar with the class or null if we cannot
* determine the location.
*
* @since Ant 1.6
*/
public static File getClassSource(Class<?> c) {
String classResource = c.getName().replace('.', '/') + ".class";
return getResourceSource(c.getClassLoader(), classResource);
}
/**
* Find the directory or jar a given resource has been loaded from.
*
* @param c the classloader to be consulted for the source.
* @param resource the resource whose location is required.
*
* @return the file with the resource source or null if
* we cannot determine the location.
*
* @since Ant 1.6
*/
public static File getResourceSource(ClassLoader c, String resource) {
if (c == null) {
c = Locator.class.getClassLoader();
}
URL url = null;
if (c == null) {
url = ClassLoader.getSystemResource(resource);
} else {
url = c.getResource(resource);
}
if (url != null) {
String u = url.toString();
try {
if (u.startsWith("jar:file:")) {
return new File(fromJarURI(u));
} else if (u.startsWith("file:")) {
int tail = u.indexOf(resource);
String dirName = u.substring(0, tail);
return new File(fromURI(dirName));
}
} catch (IllegalArgumentException e) {
//unable to determine the URI for reasons unknown.
return null;
}
}
return null;
}
/**
* Constructs a file path from a <code>file:</code> URI.
*
* <p>Will be an absolute path if the given URI is absolute.</p>
*
* <p>Prior to Java 1.4,<!-- TODO is JDK version actually relevant? -->
* swallows '%' that are not followed by two characters.</p>
*
* See <a href="http://www.w3.org/TR/xml11/#dt-sysid">dt-sysid</a>
* which makes some mention of how
* characters not supported by URI Reference syntax should be escaped.
*
* @param uri the URI designating a file in the local filesystem.
* @return the local file system path for the file.
* @throws IllegalArgumentException if the URI is malformed or not a legal file: URL
* @since Ant 1.6
*/
public static String fromURI(String uri) {
return fromURIJava13(uri);
// #buzilla8031: first try Java 1.4.
// TODO should use java.net.URI now that we can rely on 1.4...
// but check for UNC-related regressions, e.g. #42275
// (and remember that \\server\share\file -> file:////server/share/file
// rather than -> file://server/share/file as it should;
// fixed only in JDK 7's java.nio.file.Path.toUri)
// return fromUriJava14(uri);
}
/**
* Java1.4+ code to extract the path from the URI.
* @param uri
* @return null if a conversion was not possible
*/
/* currently unused:
private static String fromUriJava14(String uri) {
// Also check for properly formed URIs. Ant formerly recommended using
// nonsense URIs such as "file:./foo.xml" in XML includes. You shouldn't
// do that (just "foo.xml" is correct) but for compatibility we special-case
// things when the path is not absolute, and fall back to the old parsing behavior.
if (uri.startsWith("file:/")) {
try {
File f = new File(URI.create(encodeURI(uri)));
//bug #42227 forgot to decode before returning
return decodeUri(f.getAbsolutePath());
} catch (IllegalArgumentException e) {
// Bad URI, pass this on.
// no, this is downgraded to a warning after various
// JRE bugs surfaced. Hand off
// to our built in code on a failure
//throw new IllegalArgumentException(
// "Bad URI " + uri + ":" + e.getMessage(), e);
e.printStackTrace();
} catch (Exception e) {
// Unexpected exception? Should not happen.
e.printStackTrace();
}
}
return null;
}
*/
/**
* @param uri uri to expand
* @return the decoded URI
* @since Ant1.7.1
*/
private static String fromURIJava13(String uri) {
// Fallback method for Java 1.3 or earlier.
URL url = null;
try {
url = new URL(uri);
} catch (MalformedURLException emYouEarlEx) {
// Ignore malformed exception
}
if (url == null || !("file".equals(url.getProtocol()))) {
throw new IllegalArgumentException(ERROR_NOT_FILE_URI + uri);
}
StringBuffer buf = new StringBuffer(url.getHost());
if (buf.length() > 0) {
buf.insert(0, File.separatorChar).insert(0, File.separatorChar);
}
String file = url.getFile();
int queryPos = file.indexOf('?');
buf.append((queryPos < 0) ? file : file.substring(0, queryPos));
uri = buf.toString().replace('/', File.separatorChar);
if (File.pathSeparatorChar == ';' && uri.startsWith("\\") && uri.length() > 2
&& Character.isLetter(uri.charAt(1)) && uri.lastIndexOf(':') > -1) {
uri = uri.substring(1);
}
String path = null;
try {
path = decodeUri(uri);
//consider adding the current directory. This is not done when
//the path is a UNC name
String cwd = System.getProperty("user.dir");
int posi = cwd.indexOf(':');
boolean pathStartsWithFileSeparator = path.startsWith(File.separator);
boolean pathStartsWithUNC = path.startsWith("" + File.separator + File.separator);
if ((posi > 0) && pathStartsWithFileSeparator && !pathStartsWithUNC) {
path = cwd.substring(0, posi + 1) + path;
}
} catch (UnsupportedEncodingException exc) {
// not sure whether this is clean, but this method is
// declared not to throw exceptions.
throw new IllegalStateException(
"Could not convert URI " + uri + " to path: "
+ exc.getMessage());
}
return path;
}
/**
* Crack a JAR URI.
* This method is public for testing; we may delete it without any warning -it is not part of Ant's stable API.
* @param uri uri to expand; contains jar: somewhere in it
* @return the decoded URI
* @since Ant1.7.1
*/
public static String fromJarURI(String uri) {
int pling = uri.indexOf("!/");
String jarName = uri.substring("jar:".length(), pling);
return fromURI(jarName);
}
/**
* Decodes an Uri with % characters.
* The URI is escaped
* @param uri String with the uri possibly containing % characters.
* @return The decoded Uri
* @throws UnsupportedEncodingException if UTF-8 is not available
* @since Ant 1.7
*/
public static String decodeUri(String uri) throws UnsupportedEncodingException {
if (uri.indexOf('%') == -1) {
return uri;
}
ByteArrayOutputStream sb = new ByteArrayOutputStream(uri.length());
CharacterIterator iter = new StringCharacterIterator(uri);
for (char c = iter.first(); c != CharacterIterator.DONE;
c = iter.next()) {
if (c == '%') {
char c1 = iter.next();
if (c1 != CharacterIterator.DONE) {
int i1 = Character.digit(c1, WORD);
char c2 = iter.next();
if (c2 != CharacterIterator.DONE) {
int i2 = Character.digit(c2, WORD);
sb.write((char) ((i1 << NIBBLE) + i2));
}
}
} else if (c >= 0x0000 && c < 0x0080) {
sb.write(c);
} else { // #50543
byte[] bytes = String.valueOf(c).getBytes(URI_ENCODING);
sb.write(bytes, 0, bytes.length);
}
}
return sb.toString(URI_ENCODING);
}
/**
* Encodes an Uri with % characters.
* The URI is escaped
* @param path String to encode.
* @return The encoded string, according to URI norms
* @throws UnsupportedEncodingException if UTF-8 is not available
* @since Ant 1.7
*/
public static String encodeURI(String path) throws UnsupportedEncodingException {
int i = 0;
int len = path.length();
int ch = 0;
StringBuffer sb = null;
for (; i < len; i++) {
ch = path.charAt(i);
// if it's not an ASCII character, break here, and use UTF-8 encoding
if (ch >= ASCII_SIZE) {
break;
}
if (gNeedEscaping[ch]) {
if (sb == null) {
sb = new StringBuffer(path.substring(0, i));
}
sb.append('%');
sb.append(gAfterEscaping1[ch]);
sb.append(gAfterEscaping2[ch]);
// record the fact that it's escaped
} else if (sb != null) {
sb.append((char) ch);
}
}
// we saw some non-ascii character
if (i < len) {
if (sb == null) {
sb = new StringBuffer(path.substring(0, i));
}
// get UTF-8 bytes for the remaining sub-string
byte[] bytes = null;
byte b;
bytes = path.substring(i).getBytes(URI_ENCODING);
len = bytes.length;
// for each byte
for (i = 0; i < len; i++) {
b = bytes[i];
// for non-ascii character: make it positive, then escape
if (b < 0) {
ch = b + BYTE_SIZE;
sb.append('%');
sb.append(gHexChs[ch >> NIBBLE]);
sb.append(gHexChs[ch & NIBBLE_MASK]);
} else if (gNeedEscaping[b]) {
sb.append('%');
sb.append(gAfterEscaping1[b]);
sb.append(gAfterEscaping2[b]);
} else {
sb.append((char) b);
}
}
}
return sb == null ? path : sb.toString();
}
/**
* Convert a File to a URL.
* File.toURL() does not encode characters like #.
* File.toURI() has been introduced in java 1.4, so
* Ant cannot use it (except by reflection) <!-- TODO no longer true -->
* FileUtils.toURI() cannot be used by Locator.java
* Implemented this way.
* File.toURL() adds file: and changes '\' to '/' for dos OSes
* encodeURI converts characters like ' ' and '#' to %DD
* @param file the file to convert
* @return URL the converted File
* @throws MalformedURLException on error
* @deprecated since 1.9, use {@link FileUtils#getFileURL(File)}
*/
@Deprecated
public static URL fileToURL(File file)
throws MalformedURLException {
return new URL(file.toURI().toASCIIString());
}
/**
* Get the File necessary to load the Sun compiler tools. If the classes
* are available to this class, then no additional URL is required and
* null is returned. This may be because the classes are explicitly in the
* class path or provided by the JVM directly.
*
* @return the tools jar as a File if required, null otherwise.
*/
public static File getToolsJar() {
// firstly check if the tools jar is already in the classpath
boolean toolsJarAvailable = false;
try {
// just check whether this throws an exception
Class.forName("com.sun.tools.javac.Main");
toolsJarAvailable = true;
} catch (Exception e) {
try {
Class.forName("sun.tools.javac.Main");
toolsJarAvailable = true;
} catch (Exception e2) {
// ignore
}
}
if (toolsJarAvailable) {
return null;
}
// couldn't find compiler - try to find tools.jar
// based on java.home setting
String libToolsJar
= File.separator + "lib" + File.separator + "tools.jar";
String javaHome = System.getProperty("java.home");
File toolsJar = new File(javaHome + libToolsJar);
if (toolsJar.exists()) {
// Found in java.home as given
return toolsJar;
}
if (javaHome.toLowerCase(Locale.ENGLISH).endsWith(File.separator + "jre")) {
javaHome = javaHome.substring(
0, javaHome.length() - "/jre".length());
toolsJar = new File(javaHome + libToolsJar);
}
if (!toolsJar.exists()) {
System.out.println("Unable to locate tools.jar. "
+ "Expected to find it in " + toolsJar.getPath());
return null;
}
return toolsJar;
}
/**
* Get an array of URLs representing all of the jar files in the
* given location. If the location is a file, it is returned as the only
* element of the array. If the location is a directory, it is scanned for
* jar files.
*
* @param location the location to scan for Jars.
*
* @return an array of URLs for all jars in the given location.
*
* @exception MalformedURLException if the URLs for the jars cannot be
* formed.
*/
public static URL[] getLocationURLs(File location)
throws MalformedURLException {
return getLocationURLs(location, new String[]{".jar"});
}
/**
* Get an array of URLs representing all of the files of a given set of
* extensions in the given location. If the location is a file, it is
* returned as the only element of the array. If the location is a
* directory, it is scanned for matching files.
*
* @param location the location to scan for files.
* @param extensions an array of extension that are to match in the
* directory search.
*
* @return an array of URLs of matching files.
* @exception MalformedURLException if the URLs for the files cannot be
* formed.
*/
public static URL[] getLocationURLs(File location,
final String[] extensions)
throws MalformedURLException {
URL[] urls = new URL[0];
if (!location.exists()) {
return urls;
}
if (!location.isDirectory()) {
urls = new URL[1];
String path = location.getPath();
String littlePath = path.toLowerCase(Locale.ENGLISH);
for (int i = 0; i < extensions.length; ++i) {
if (littlePath.endsWith(extensions[i])) {
urls[0] = fileToURL(location);
break;
}
}
return urls;
}
File[] matches = location.listFiles(
new FilenameFilter() {
public boolean accept(File dir, String name) {
String littleName = name.toLowerCase(Locale.ENGLISH);
for (int i = 0; i < extensions.length; ++i) {
if (littleName.endsWith(extensions[i])) {
return true;
}
}
return false;
}
});
urls = new URL[matches.length];
for (int i = 0; i < matches.length; ++i) {
urls[i] = fileToURL(matches[i]);
}
return urls;
}
}

View File

@@ -1,6 +0,0 @@
/**
* This is a copy of classes within Apache Ant. The DirectoryScanner is needed by dependency-check. However, we did not want to
* make Ant a dependency. As such, a few files were copied and slightly modified to remove any references to the Ant Project
* class.
*/
package org.owasp.dependencycheck.org.apache.tools.ant.launch;

View File

@@ -1,6 +0,0 @@
/**
* This is a copy of classes within Apache Ant. The DirectoryScanner is needed by dependency-check. However, we did not want to
* make Ant a dependency. As such, a few files were copied and slightly modified to remove any references to the Ant Project
* class.
*/
package org.owasp.dependencycheck.org.apache.tools.ant;

View File

@@ -1,35 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*
*/
package org.owasp.dependencycheck.org.apache.tools.ant.taskdefs.condition;
import org.owasp.dependencycheck.org.apache.tools.ant.BuildException;
/**
* Interface for conditions to use inside the &lt;condition&gt; task.
*
*/
public interface Condition {
/**
* Is this condition true?
* @return true if the condition is true
* @exception BuildException if an error occurs
*/
boolean eval() throws BuildException;
}

View File

@@ -1,321 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*
*/
package org.owasp.dependencycheck.org.apache.tools.ant.taskdefs.condition;
import java.util.Locale;
import org.owasp.dependencycheck.org.apache.tools.ant.BuildException;
/**
* Condition that tests the OS type.
*
* @since Ant 1.4
*/
public class Os implements Condition {
private static final String OS_NAME =
System.getProperty("os.name").toLowerCase(Locale.ENGLISH);
private static final String OS_ARCH =
System.getProperty("os.arch").toLowerCase(Locale.ENGLISH);
private static final String OS_VERSION =
System.getProperty("os.version").toLowerCase(Locale.ENGLISH);
private static final String PATH_SEP =
System.getProperty("path.separator");
/**
* OS family to look for
*/
private String family;
/**
* Name of OS
*/
private String name;
/**
* version of OS
*/
private String version;
/**
* OS architecture
*/
private String arch;
/**
* OS family that can be tested for. {@value}
*/
public static final String FAMILY_WINDOWS = "windows";
/**
* OS family that can be tested for. {@value}
*/
public static final String FAMILY_9X = "win9x";
/**
* OS family that can be tested for. {@value}
*/
public static final String FAMILY_NT = "winnt";
/**
* OS family that can be tested for. {@value}
*/
public static final String FAMILY_OS2 = "os/2";
/**
* OS family that can be tested for. {@value}
*/
public static final String FAMILY_NETWARE = "netware";
/**
* OS family that can be tested for. {@value}
*/
public static final String FAMILY_DOS = "dos";
/**
* OS family that can be tested for. {@value}
*/
public static final String FAMILY_MAC = "mac";
/**
* OS family that can be tested for. {@value}
*/
public static final String FAMILY_TANDEM = "tandem";
/**
* OS family that can be tested for. {@value}
*/
public static final String FAMILY_UNIX = "unix";
/**
* OS family that can be tested for. {@value}
*/
public static final String FAMILY_VMS = "openvms";
/**
* OS family that can be tested for. {@value}
*/
public static final String FAMILY_ZOS = "z/os";
/** OS family that can be tested for. {@value} */
public static final String FAMILY_OS400 = "os/400";
/**
* OpenJDK is reported to call MacOS X "Darwin"
* @see https://issues.apache.org/bugzilla/show_bug.cgi?id=44889
* @see https://issues.apache.org/jira/browse/HADOOP-3318
*/
private static final String DARWIN = "darwin";
/**
* Default constructor
*
*/
public Os() {
//default
}
/**
* Constructor that sets the family attribute
* @param family a String value
*/
public Os(String family) {
setFamily(family);
}
/**
* Sets the desired OS family type
*
* @param f The OS family type desired<br>
* Possible values:<br>
* <ul>
* <li>dos</li>
* <li>mac</li>
* <li>netware</li>
* <li>os/2</li>
* <li>tandem</li>
* <li>unix</li>
* <li>windows</li>
* <li>win9x</li>
* <li>z/os</li>
* <li>os/400</li>
* </ul>
*/
public void setFamily(String f) {
family = f.toLowerCase(Locale.ENGLISH);
}
/**
* Sets the desired OS name
*
* @param name The OS name
*/
public void setName(String name) {
this.name = name.toLowerCase(Locale.ENGLISH);
}
/**
* Sets the desired OS architecture
*
* @param arch The OS architecture
*/
public void setArch(String arch) {
this.arch = arch.toLowerCase(Locale.ENGLISH);
}
/**
* Sets the desired OS version
*
* @param version The OS version
*/
public void setVersion(String version) {
this.version = version.toLowerCase(Locale.ENGLISH);
}
/**
* Determines if the OS on which Ant is executing matches the type of
* that set in setFamily.
* @return true if the os matches.
* @throws BuildException if there is an error.
* @see Os#setFamily(String)
*/
public boolean eval() throws BuildException {
return isOs(family, name, arch, version);
}
/**
* Determines if the OS on which Ant is executing matches the
* given OS family.
* @param family the family to check for
* @return true if the OS matches
* @since 1.5
*/
public static boolean isFamily(String family) {
return isOs(family, null, null, null);
}
/**
* Determines if the OS on which Ant is executing matches the
* given OS name.
*
* @param name the OS name to check for
* @return true if the OS matches
* @since 1.7
*/
public static boolean isName(String name) {
return isOs(null, name, null, null);
}
/**
* Determines if the OS on which Ant is executing matches the
* given OS architecture.
*
* @param arch the OS architecture to check for
* @return true if the OS matches
* @since 1.7
*/
public static boolean isArch(String arch) {
return isOs(null, null, arch, null);
}
/**
* Determines if the OS on which Ant is executing matches the
* given OS version.
*
* @param version the OS version to check for
* @return true if the OS matches
* @since 1.7
*/
public static boolean isVersion(String version) {
return isOs(null, null, null, version);
}
/**
* Determines if the OS on which Ant is executing matches the
* given OS family, name, architecture and version
*
* @param family The OS family
* @param name The OS name
* @param arch The OS architecture
* @param version The OS version
* @return true if the OS matches
* @since 1.7
*/
public static boolean isOs(String family, String name, String arch,
String version) {
boolean retValue = false;
if (family != null || name != null || arch != null
|| version != null) {
boolean isFamily = true;
boolean isName = true;
boolean isArch = true;
boolean isVersion = true;
if (family != null) {
//windows probing logic relies on the word 'windows' in
//the OS
boolean isWindows = OS_NAME.indexOf(FAMILY_WINDOWS) > -1;
boolean is9x = false;
boolean isNT = false;
if (isWindows) {
//there are only four 9x platforms that we look for
is9x = (OS_NAME.indexOf("95") >= 0
|| OS_NAME.indexOf("98") >= 0
|| OS_NAME.indexOf("me") >= 0
//wince isn't really 9x, but crippled enough to
//be a muchness. Ant doesnt run on CE, anyway.
|| OS_NAME.indexOf("ce") >= 0);
isNT = !is9x;
}
if (family.equals(FAMILY_WINDOWS)) {
isFamily = isWindows;
} else if (family.equals(FAMILY_9X)) {
isFamily = isWindows && is9x;
} else if (family.equals(FAMILY_NT)) {
isFamily = isWindows && isNT;
} else if (family.equals(FAMILY_OS2)) {
isFamily = OS_NAME.indexOf(FAMILY_OS2) > -1;
} else if (family.equals(FAMILY_NETWARE)) {
isFamily = OS_NAME.indexOf(FAMILY_NETWARE) > -1;
} else if (family.equals(FAMILY_DOS)) {
isFamily = PATH_SEP.equals(";") && !isFamily(FAMILY_NETWARE);
} else if (family.equals(FAMILY_MAC)) {
isFamily = OS_NAME.indexOf(FAMILY_MAC) > -1
|| OS_NAME.indexOf(DARWIN) > -1;
} else if (family.equals(FAMILY_TANDEM)) {
isFamily = OS_NAME.indexOf("nonstop_kernel") > -1;
} else if (family.equals(FAMILY_UNIX)) {
isFamily = PATH_SEP.equals(":")
&& !isFamily(FAMILY_VMS)
&& (!isFamily(FAMILY_MAC) || OS_NAME.endsWith("x")
|| OS_NAME.indexOf(DARWIN) > -1);
} else if (family.equals(FAMILY_ZOS)) {
isFamily = OS_NAME.indexOf(FAMILY_ZOS) > -1
|| OS_NAME.indexOf("os/390") > -1;
} else if (family.equals(FAMILY_OS400)) {
isFamily = OS_NAME.indexOf(FAMILY_OS400) > -1;
} else if (family.equals(FAMILY_VMS)) {
isFamily = OS_NAME.indexOf(FAMILY_VMS) > -1;
} else {
throw new BuildException(
"Don\'t know how to detect os family \""
+ family + "\"");
}
}
if (name != null) {
isName = name.equals(OS_NAME);
}
if (arch != null) {
isArch = arch.equals(OS_ARCH);
}
if (version != null) {
isVersion = version.equals(OS_VERSION);
}
retValue = isFamily && isName && isArch && isVersion;
}
return retValue;
}
}

View File

@@ -1,6 +0,0 @@
/**
* This is a copy of classes within Apache Ant. The DirectoryScanner is needed by dependency-check. However, we did not want to
* make Ant a dependency. As such, a few files were copied and slightly modified to remove any references to the Ant Project
* class.
*/
package org.owasp.dependencycheck.org.apache.tools.ant.taskdefs.condition;

View File

@@ -1,353 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*
*/
package org.owasp.dependencycheck.org.apache.tools.ant.types;
import org.owasp.dependencycheck.org.apache.tools.ant.BuildException;
import org.owasp.dependencycheck.org.apache.tools.ant.ProjectComponent;
/**
* Base class for those classes that can appear inside the build file as stand alone data types.
*
* <p>
* This class handles the common description attribute and provides a default implementation for reference handling and
* checking for circular references that is appropriate for types that can not be nested inside elements of the same
* type (i.e. &lt;patternset&gt; but not &lt;path&gt;).</p>
*
*/
public abstract class DataType extends ProjectComponent implements Cloneable {
// CheckStyle:VisibilityModifier OFF
/**
* Value to the refid attribute.
*
* @deprecated since 1.7. The user should not be directly referencing variable. Please use {@link #getRefid}
* instead.
*/
protected Reference ref;
/**
* Are we sure we don't hold circular references?
*
* <p>
* Subclasses are responsible for setting this value to false if we'd need to investigate this condition (usually
* because a child element has been added that is a subclass of DataType).</p>
*
* @deprecated since 1.7. The user should not be directly referencing variable. Please use {@link #setChecked} or
* {@link #isChecked} instead.
*/
protected boolean checked = true;
// CheckStyle:VisibilityModifier ON
/**
* Has the refid attribute of this element been set?
*
* @return true if the refid attribute has been set
*/
public boolean isReference() {
return ref != null;
}
/**
* Set the value of the refid attribute.
*
* <p>
* Subclasses may need to check whether any other attributes have been set as well or child elements have been
* created and thus override this method. if they do the must call <code>super.setRefid</code>.</p>
*
* @param ref the reference to use
*/
public void setRefid(final Reference ref) {
this.ref = ref;
checked = false;
}
// /**
// * Gets as descriptive as possible a name used for this datatype instance.
// *
// * @return <code>String</code> name.
// */
// protected String getDataTypeName() {
// return ComponentHelper.getElementName(getProject(), this, true);
// }
// /**
// * Convenience method.
// * @since Ant 1.7
// */
// protected void dieOnCircularReference() {
// dieOnCircularReference(getProject());
// }
//
// /**
// * Convenience method.
// * @param p the Ant Project instance against which to resolve references.
// * @since Ant 1.7
// */
// protected void dieOnCircularReference(Project p) {
// if (checked || !isReference()) {
// return;
// }
// dieOnCircularReference(new IdentityStack<Object>(this), p);
// }
//
// /**
// * Check to see whether any DataType we hold references to is
// * included in the Stack (which holds all DataType instances that
// * directly or indirectly reference this instance, including this
// * instance itself).
// *
// * <p>If one is included, throw a BuildException created by {@link
// * #circularReference circularReference}.</p>
// *
// * <p>This implementation is appropriate only for a DataType that
// * cannot hold other DataTypes as children.</p>
// *
// * <p>The general contract of this method is that it shouldn't do
// * anything if {@link #checked <code>checked</code>} is true and
// * set it to true on exit.</p>
// * @param stack the stack of references to check.
// * @param project the project to use to dereference the references.
// * @throws BuildException on error.
// */
// protected void dieOnCircularReference(final Stack<Object> stack,
// final Project project)
// throws BuildException {
//
// if (checked || !isReference()) {
// return;
// }
// Object o = ref.getReferencedObject(project);
//
// if (o instanceof DataType) {
// IdentityStack<Object> id = IdentityStack.getInstance(stack);
//
// if (id.contains(o)) {
// throw circularReference();
// } else {
// id.push(o);
// ((DataType) o).dieOnCircularReference(id, project);
// id.pop();
// }
// }
// checked = true;
// }
// /**
// * Allow DataTypes outside org.apache.tools.ant.types to indirectly call dieOnCircularReference on nested DataTypes.
// *
// * @param dt the DataType to check.
// * @param stk the stack of references to check.
// * @param p the project to use to dereference the references.
// * @throws BuildException on error.
// * @since Ant 1.7
// */
// public static void invokeCircularReferenceCheck(DataType dt, Stack<Object> stk,
// Project p) {
// dt.dieOnCircularReference(stk, p);
// }
//
// /**
// * Allow DataTypes outside org.apache.tools.ant.types to indirectly call dieOnCircularReference on nested DataTypes.
// *
// * <p>
// * Pushes dt on the stack, runs dieOnCircularReference and pops it again.</p>
// *
// * @param dt the DataType to check.
// * @param stk the stack of references to check.
// * @param p the project to use to dereference the references.
// * @throws BuildException on error.
// * @since Ant 1.8.0
// */
// public static void pushAndInvokeCircularReferenceCheck(DataType dt,
// Stack<Object> stk,
// Project p) {
// stk.push(dt);
// dt.dieOnCircularReference(stk, p);
// stk.pop();
// }
// /**
// * Performs the check for circular references and returns the referenced object.
// *
// * @return the dereferenced object.
// * @throws BuildException if the reference is invalid (circular ref, wrong class, etc).
// * @since Ant 1.7
// */
// protected Object getCheckedRef() {
// return getCheckedRef(getProject());
// }
//
// /**
// * Performs the check for circular references and returns the referenced object.
// *
// * @param p the Ant Project instance against which to resolve references.
// * @return the dereferenced object.
// * @throws BuildException if the reference is invalid (circular ref, wrong class, etc).
// * @since Ant 1.7
// */
// protected Object getCheckedRef(Project p) {
// return getCheckedRef(getClass(), getDataTypeName(), p);
// }
//
// /**
// * Performs the check for circular references and returns the referenced object.
// *
// * @param requiredClass the class that this reference should be a subclass of.
// * @param dataTypeName the name of the datatype that the reference should be (error message use only).
// * @return the dereferenced object.
// * @throws BuildException if the reference is invalid (circular ref, wrong class, etc).
// */
// protected <T> T getCheckedRef(final Class<T> requiredClass,
// final String dataTypeName) {
// return getCheckedRef(requiredClass, dataTypeName, getProject());
// }
//
// /**
// * Performs the check for circular references and returns the referenced object. This version allows the fallback
// * Project instance to be specified.
// *
// * @param requiredClass the class that this reference should be a subclass of.
// * @param dataTypeName the name of the datatype that the reference should be (error message use only).
// * @param project the fallback Project instance for dereferencing.
// * @return the dereferenced object.
// * @throws BuildException if the reference is invalid (circular ref, wrong class, etc), or if <code>project</code>
// * is <code>null</code>.
// * @since Ant 1.7
// */
// protected <T> T getCheckedRef(final Class<T> requiredClass,
// final String dataTypeName, final Project project) {
// if (project == null) {
// throw new BuildException("No Project specified");
// }
// dieOnCircularReference(project);
// Object o = ref.getReferencedObject(project);
// if (!(requiredClass.isAssignableFrom(o.getClass()))) {
// log("Class " + o.getClass() + " is not a subclass of " + requiredClass,
// Project.MSG_VERBOSE);
// String msg = ref.getRefId() + " doesn\'t denote a " + dataTypeName;
// throw new BuildException(msg);
// }
// @SuppressWarnings("unchecked")
// final T result = (T) o;
// return result;
// }
/**
* Creates an exception that indicates that refid has to be the only attribute if it is set.
*
* @return the exception to throw
*/
protected BuildException tooManyAttributes() {
return new BuildException("You must not specify more than one "
+ "attribute when using refid");
}
/**
* Creates an exception that indicates that this XML element must not have child elements if the refid attribute is
* set.
*
* @return the exception to throw
*/
protected BuildException noChildrenAllowed() {
return new BuildException("You must not specify nested elements "
+ "when using refid");
}
/**
* Creates an exception that indicates the user has generated a loop of data types referencing each other.
*
* @return the exception to throw
*/
protected BuildException circularReference() {
return new BuildException("This data type contains a circular "
+ "reference.");
}
/**
* The flag that is used to indicate that circular references have been checked.
*
* @return true if circular references have been checked
*/
protected boolean isChecked() {
return checked;
}
/**
* Set the flag that is used to indicate that circular references have been checked.
*
* @param checked if true, if circular references have been checked
*/
protected void setChecked(final boolean checked) {
this.checked = checked;
}
/**
* get the reference set on this object
*
* @return the reference or null
*/
public Reference getRefid() {
return ref;
}
/**
* check that it is ok to set attributes, i.e that no reference is defined
*
* @since Ant 1.6
* @throws BuildException if not allowed
*/
protected void checkAttributesAllowed() {
if (isReference()) {
throw tooManyAttributes();
}
}
/**
* check that it is ok to add children, i.e that no reference is defined
*
* @since Ant 1.6
* @throws BuildException if not allowed
*/
protected void checkChildrenAllowed() {
if (isReference()) {
throw noChildrenAllowed();
}
}
/**
* Basic DataType toString().
*
* @return this DataType formatted as a String.
*/
public String toString() {
String d = getDescription();
//return d == null ? getDataTypeName() : getDataTypeName() + " " + d;
return d == null ? "DataType" : d;
}
/**
* @since Ant 1.7
* @return a shallow copy of this DataType.
* @throws CloneNotSupportedException if there is a problem.
*/
public Object clone() throws CloneNotSupportedException {
DataType dt = (DataType) super.clone();
dt.setDescription(getDescription());
if (getRefid() != null) {
dt.setRefid(getRefid());
}
dt.setChecked(isChecked());
return dt;
}
}

View File

@@ -1,126 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*
*/
package org.owasp.dependencycheck.org.apache.tools.ant.types;
/**
* Class to hold a reference to another object in the project.
*
*/
public class Reference {
private String refid;
//private Project project;
/**
* Create a reference.
*
* @deprecated since 1.7. Please use {@link Reference#Reference(Project,String)} instead.
*/
public Reference() {
}
/**
* Create a reference to a named ID.
*
* @param id the name of this reference
* @deprecated since 1.7. Please use {@link Reference#Reference(Project,String)} instead.
*/
public Reference(String id) {
setRefId(id);
}
//
// /**
// * Create a reference to a named ID in a particular project.
// * @param p the project this reference is associated with
// * @param id the name of this reference
// * @since Ant 1.6.3
// */
// public Reference(Project p, String id) {
// setRefId(id);
// setProject(p);
// }
/**
* Set the reference id. Should not normally be necessary; use {@link Reference#Reference(Project, String)}.
*
* @param id the reference id to use
*/
public void setRefId(String id) {
refid = id;
}
/**
* Get the reference id of this reference.
*
* @return the reference id
*/
public String getRefId() {
return refid;
}
// /**
// * Set the associated project. Should not normally be necessary;
// * use {@link Reference#Reference(Project,String)}.
// * @param p the project to use
// * @since Ant 1.6.3
// */
// public void setProject(Project p) {
// this.project = p;
// }
//
// /**
// * Get the associated project, if any; may be null.
// * @return the associated project
// * @since Ant 1.6.3
// */
// public Project getProject() {
// return project;
// }
// /**
// * Resolve the reference, using the associated project if
// * it set, otherwise use the passed in project.
// * @param fallback the fallback project to use if the project attribute of
// * reference is not set.
// * @return the dereferenced object.
// * @throws BuildException if the reference cannot be dereferenced.
// */
// public Object getReferencedObject(Project fallback) throws BuildException {
// if (refid == null) {
// throw new BuildException("No reference specified");
// }
//
// Object o = project == null ? fallback.getReference(refid) : project.getReference(refid);
// if (o == null) {
// throw new BuildException("Reference " + refid + " not found.");
// }
// return o;
// }
// /**
// * Resolve the reference, looking in the associated project.
// * @see Project#getReference
// * @return the dereferenced object.
// * @throws BuildException if the project is null or the reference cannot be dereferenced
// * @since Ant 1.6.3
// */
// public Object getReferencedObject() throws BuildException {
// if (project == null) {
// throw new BuildException("No project set on reference to " + refid);
// }
// return getReferencedObject(project);
// }
}

View File

@@ -1,462 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*
*/
package org.owasp.dependencycheck.org.apache.tools.ant.types;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.util.Iterator;
import java.util.NoSuchElementException;
import org.owasp.dependencycheck.org.apache.tools.ant.types.resources.FileProvider;
/**
* Describes a "File-like" resource (File, ZipEntry, etc.).
*
* This class is meant to be used by classes needing to record path and date/time information about a file, a zip entry
* or some similar resource (URL, archive in a version control repository, ...).
*
* @since Ant 1.5.2
* @see org.apache.tools.ant.types.resources.Touchable
*/
public class Resource extends DataType implements Comparable<Resource>, ResourceCollection {
/**
* Constant unknown size
*/
public static final long UNKNOWN_SIZE = -1;
/**
* Constant unknown datetime for getLastModified
*/
public static final long UNKNOWN_DATETIME = 0L;
/**
* Magic number
*/
protected static final int MAGIC = getMagicNumber("Resource".getBytes());
private static final int NULL_NAME = getMagicNumber("null name".getBytes());
/**
* Create a "magic number" for use in hashCode calculations.
*
* @param seed byte[] to seed with.
* @return a magic number as int.
*/
protected static int getMagicNumber(byte[] seed) {
return new BigInteger(seed).intValue();
}
private String name = null;
private Boolean exists = null;
private Long lastmodified = null;
private Boolean directory = null;
private Long size = null;
/**
* Default constructor.
*/
public Resource() {
}
/**
* Only sets the name.
*
* <p>
* This is a dummy, used for not existing resources.</p>
*
* @param name relative path of the resource. Expects &quot;/&quot; to be used as the directory separator.
*/
public Resource(String name) {
this(name, false, 0, false);
}
/**
* Sets the name, lastmodified flag, and exists flag.
*
* @param name relative path of the resource. Expects &quot;/&quot; to be used as the directory separator.
* @param exists if true, this resource exists.
* @param lastmodified the last modification time of this resource.
*/
public Resource(String name, boolean exists, long lastmodified) {
this(name, exists, lastmodified, false);
}
/**
* Sets the name, lastmodified flag, exists flag, and directory flag.
*
* @param name relative path of the resource. Expects &quot;/&quot; to be used as the directory separator.
* @param exists if true the resource exists
* @param lastmodified the last modification time of the resource
* @param directory if true, this resource is a directory
*/
public Resource(String name, boolean exists, long lastmodified, boolean directory) {
this(name, exists, lastmodified, directory, UNKNOWN_SIZE);
}
/**
* Sets the name, lastmodified flag, exists flag, directory flag, and size.
*
* @param name relative path of the resource. Expects &quot;/&quot; to be used as the directory separator.
* @param exists if true the resource exists
* @param lastmodified the last modification time of the resource
* @param directory if true, this resource is a directory
* @param size the size of this resource.
*/
public Resource(String name, boolean exists, long lastmodified, boolean directory, long size) {
this.name = name;
setName(name);
setExists(exists);
setLastModified(lastmodified);
setDirectory(directory);
setSize(size);
}
/**
* Name attribute will contain the path of a file relative to the root directory of its fileset or the recorded path
* of a zip entry.
*
* <p>
* example for a file with fullpath /var/opt/adm/resource.txt in a file set with root dir /var/opt it will be
* adm/resource.txt.</p>
*
* <p>
* &quot;/&quot; will be used as the directory separator.</p>
*
* @return the name of this resource.
*/
public String getName() {
//return isReference() ? ((Resource) getCheckedRef()).getName() : name;
return name;
}
/**
* Set the name of this Resource.
*
* @param name relative path of the resource. Expects &quot;/&quot; to be used as the directory separator.
*/
public void setName(String name) {
checkAttributesAllowed();
this.name = name;
}
/**
* The exists attribute tells whether a resource exists.
*
* @return true if this resource exists.
*/
public boolean isExists() {
// if (isReference()) {
// return ((Resource) getCheckedRef()).isExists();
// }
//default true:
return exists == null || exists.booleanValue();
}
/**
* Set the exists attribute.
*
* @param exists if true, this resource exists.
*/
public void setExists(boolean exists) {
checkAttributesAllowed();
this.exists = exists ? Boolean.TRUE : Boolean.FALSE;
}
/**
* Tells the modification time in milliseconds since 01.01.1970 (the "epoch").
*
* @return the modification time, if that is meaningful (e.g. for a file resource which exists); 0 if the resource
* does not exist, to mirror the behavior of {@link java.io.File#lastModified}; or 0 if the notion of modification
* time is meaningless for this class of resource (e.g. an inline string)
*/
public long getLastModified() {
// if (isReference()) {
// return ((Resource) getCheckedRef()).getLastModified();
// }
if (!isExists() || lastmodified == null) {
return UNKNOWN_DATETIME;
}
long result = lastmodified.longValue();
return result < UNKNOWN_DATETIME ? UNKNOWN_DATETIME : result;
}
/**
* Set the last modification attribute.
*
* @param lastmodified the modification time in milliseconds since 01.01.1970.
*/
public void setLastModified(long lastmodified) {
checkAttributesAllowed();
this.lastmodified = new Long(lastmodified);
}
/**
* Tells if the resource is a directory.
*
* @return boolean flag indicating if the resource is a directory.
*/
public boolean isDirectory() {
// if (isReference()) {
// return ((Resource) getCheckedRef()).isDirectory();
// }
//default false:
return directory != null && directory.booleanValue();
}
/**
* Set the directory attribute.
*
* @param directory if true, this resource is a directory.
*/
public void setDirectory(boolean directory) {
checkAttributesAllowed();
this.directory = directory ? Boolean.TRUE : Boolean.FALSE;
}
/**
* Set the size of this Resource.
*
* @param size the size, as a long.
* @since Ant 1.6.3
*/
public void setSize(long size) {
checkAttributesAllowed();
this.size = new Long(size > UNKNOWN_SIZE ? size : UNKNOWN_SIZE);
}
/**
* Get the size of this Resource.
*
* @return the size, as a long, 0 if the Resource does not exist (for compatibility with java.io.File), or
* UNKNOWN_SIZE if not known.
* @since Ant 1.6.3
*/
public long getSize() {
// if (isReference()) {
// return ((Resource) getCheckedRef()).getSize();
// }
return isExists()
? (size != null ? size.longValue() : UNKNOWN_SIZE)
: 0L;
}
/**
* Clone this Resource.
*
* @return copy of this.
*/
public Object clone() {
try {
return super.clone();
} catch (CloneNotSupportedException e) {
throw new UnsupportedOperationException(
"CloneNotSupportedException for a Resource caught. "
+ "Derived classes must support cloning.");
}
}
/**
* Delegates to a comparison of names.
*
* @param other the object to compare to.
* @return a negative integer, zero, or a positive integer as this Resource is less than, equal to, or greater than
* the specified Resource.
* @since Ant 1.6
*/
public int compareTo(Resource other) {
// if (isReference()) {
// return ((Resource) getCheckedRef()).compareTo(other);
// }
return toString().compareTo(other.toString());
}
/**
* Implement basic Resource equality.
*
* @param other the object to check against.
* @return true if the specified Object is equal to this Resource.
* @since Ant 1.7
*/
public boolean equals(Object other) {
// if (isReference()) {
// return getCheckedRef().equals(other);
// }
return other != null && other.getClass().equals(getClass())
&& compareTo((Resource) other) == 0;
}
/**
* Get the hash code for this Resource.
*
* @return hash code as int.
* @since Ant 1.7
*/
public int hashCode() {
// if (isReference()) {
// return getCheckedRef().hashCode();
// }
String name = getName();
return MAGIC * (name == null ? NULL_NAME : name.hashCode());
}
/**
* Get an InputStream for the Resource.
*
* @return an InputStream containing this Resource's content.
* @throws IOException if unable to provide the content of this Resource as a stream.
* @throws UnsupportedOperationException if InputStreams are not supported for this Resource type.
* @since Ant 1.7
*/
public InputStream getInputStream() throws IOException {
// if (isReference()) {
// return ((Resource) getCheckedRef()).getInputStream();
// }
throw new UnsupportedOperationException();
}
/**
* Get an OutputStream for the Resource.
*
* @return an OutputStream to which content can be written.
* @throws IOException if unable to provide the content of this Resource as a stream.
* @throws UnsupportedOperationException if OutputStreams are not supported for this Resource type.
* @since Ant 1.7
*/
public OutputStream getOutputStream() throws IOException {
// if (isReference()) {
// return ((Resource) getCheckedRef()).getOutputStream();
// }
throw new UnsupportedOperationException();
}
/**
* Fulfill the ResourceCollection contract.
*
* @return an Iterator of Resources.
* @since Ant 1.7
*/
public Iterator<Resource> iterator() {
//return isReference() ? ((Resource) getCheckedRef()).iterator()
// : new Iterator<Resource>() {
return new Iterator<Resource>() {
private boolean done = false;
public boolean hasNext() {
return !done;
}
public Resource next() {
if (done) {
throw new NoSuchElementException();
}
done = true;
return Resource.this;
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
/**
* Fulfill the ResourceCollection contract.
*
* @return the size of this ResourceCollection.
* @since Ant 1.7
*/
public int size() {
//return isReference() ? ((Resource) getCheckedRef()).size() : 1;
return 1;
}
/**
* Fulfill the ResourceCollection contract.
*
* @return whether this Resource is a FileProvider.
* @since Ant 1.7
*/
public boolean isFilesystemOnly() {
// return (isReference() && ((Resource) getCheckedRef()).isFilesystemOnly())
// || this.as(FileProvider.class) != null;
return this.as(FileProvider.class) != null;
}
/**
* Get the string representation of this Resource.
*
* @return this Resource formatted as a String.
* @since Ant 1.7
*/
public String toString() {
// if (isReference()) {
// return getCheckedRef().toString();
// }
String n = getName();
return n == null ? "(anonymous)" : n;
}
/**
* Get a long String representation of this Resource. This typically should be the value of <code>toString()</code>
* prefixed by a type description.
*
* @return this Resource formatted as a long String.
* @since Ant 1.7
*/
public final String toLongString() {
// return isReference() ? ((Resource) getCheckedRef()).toLongString()
// : getDataTypeName() + " \"" + toString() + '"';
return toString();
}
/**
* Overrides the base version.
*
* @param r the Reference to set.
*/
public void setRefid(Reference r) {
if (name != null
|| exists != null
|| lastmodified != null
|| directory != null
|| size != null) {
throw tooManyAttributes();
}
super.setRefid(r);
}
/**
* Returns a view of this resource that implements the interface given as the argument or null if there is no such
* view.
*
* <p>
* This allows extension interfaces to be added to resources without growing the number of permutations of
* interfaces decorators/adapters need to implement.</p>
*
* <p>
* This implementation of the method will return the current instance itself if it can be assigned to the given
* class.</p>
*
* @since Ant 1.8.0
*/
public <T> T as(Class<T> clazz) {
return clazz.isAssignableFrom(getClass()) ? clazz.cast(this) : null;
}
}

View File

@@ -1,50 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*
*/
package org.owasp.dependencycheck.org.apache.tools.ant.types;
import java.util.Iterator;
import org.owasp.dependencycheck.org.apache.tools.ant.types.resources.FileProvider;
/**
* Interface describing a collection of Resources.
* @since Ant 1.7
*/
public interface ResourceCollection extends Iterable<Resource> {
/**
* Gets the contents of this collection.
* @return all resources in the collection
*/
Iterator<Resource> iterator();
/**
* Learn the number of contained Resources.
* @return number of elements as int.
*/
int size();
/**
* Indicate whether this ResourceCollection is composed entirely of
* Resources accessible via local filesystem conventions. If true,
* all resources returned from this collection should
* respond with a {@link FileProvider} when asked via {@link Resource#as}.
* @return whether this is a filesystem-only resource collection.
*/
boolean isFilesystemOnly();
}

View File

@@ -1,38 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*
*/
package org.owasp.dependencycheck.org.apache.tools.ant.types;
/**
* this interface should be implemented by classes (Scanners) needing
* to deliver information about resources.
*
* @since Ant 1.5.2
*/
public interface ResourceFactory {
/**
* Query a resource (file, zipentry, ...) by name
*
* @param name relative path of the resource about which
* information is sought. Expects &quot;/&quot; to be used as the
* directory separator.
* @return instance of Resource; the exists attribute of Resource
* will tell whether the sought resource exists
*/
Resource getResource(String name);
}

View File

@@ -1,6 +0,0 @@
/**
* This is a copy of classes within Apache Ant. The DirectoryScanner is needed by dependency-check. However, we did not want to
* make Ant a dependency. As such, a few files were copied and slightly modified to remove any references to the Ant Project
* class.
*/
package org.owasp.dependencycheck.org.apache.tools.ant.types;

View File

@@ -1,35 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*
*/
package org.owasp.dependencycheck.org.apache.tools.ant.types.resources;
import java.io.IOException;
import java.io.OutputStream;
/**
* Interface to be implemented by "appendable" resources.
* @since Ant 1.8
*/
public interface Appendable {
/**
* Get an appending OutputStream.
* @return OutputStream
* @throws IOException if anything goes wrong
*/
OutputStream getAppendOutputStream() throws IOException;
}

View File

@@ -1,36 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*
*/
package org.owasp.dependencycheck.org.apache.tools.ant.types.resources;
import java.io.File;
/**
* This is an interface that resources that can provide a file should implement.
* This is a refactoring of {@link FileResource}, to allow other resources
* to act as sources of files (and to make components that only support
* file-based resources from only support FileResource resources.
* @since Ant 1.8
*/
public interface FileProvider {
/**
* Get the file represented by this Resource.
* @return the file.
*/
File getFile();
}

Some files were not shown because too many files have changed in this diff Show More