id
int32 0
165k
| repo
stringlengths 7
58
| path
stringlengths 12
218
| func_name
stringlengths 3
140
| original_string
stringlengths 73
34.1k
| language
stringclasses 1
value | code
stringlengths 73
34.1k
| code_tokens
list | docstring
stringlengths 3
16k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 105
339
|
|---|---|---|---|---|---|---|---|---|---|---|---|
17,900
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/data/nvdcve/ConnectionFactory.java
|
ConnectionFactory.getConnection
|
public synchronized Connection getConnection() throws DatabaseException {
initialize();
Connection conn = null;
try {
conn = DriverManager.getConnection(connectionString, userName, password);
} catch (SQLException ex) {
LOGGER.debug("", ex);
throw new DatabaseException("Unable to connect to the database", ex);
}
return conn;
}
|
java
|
public synchronized Connection getConnection() throws DatabaseException {
initialize();
Connection conn = null;
try {
conn = DriverManager.getConnection(connectionString, userName, password);
} catch (SQLException ex) {
LOGGER.debug("", ex);
throw new DatabaseException("Unable to connect to the database", ex);
}
return conn;
}
|
[
"public",
"synchronized",
"Connection",
"getConnection",
"(",
")",
"throws",
"DatabaseException",
"{",
"initialize",
"(",
")",
";",
"Connection",
"conn",
"=",
"null",
";",
"try",
"{",
"conn",
"=",
"DriverManager",
".",
"getConnection",
"(",
"connectionString",
",",
"userName",
",",
"password",
")",
";",
"}",
"catch",
"(",
"SQLException",
"ex",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"\"",
",",
"ex",
")",
";",
"throw",
"new",
"DatabaseException",
"(",
"\"Unable to connect to the database\"",
",",
"ex",
")",
";",
"}",
"return",
"conn",
";",
"}"
] |
Constructs a new database connection object per the database
configuration.
@return a database connection object
@throws DatabaseException thrown if there is an exception loading the
database connection
|
[
"Constructs",
"a",
"new",
"database",
"connection",
"object",
"per",
"the",
"database",
"configuration",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/data/nvdcve/ConnectionFactory.java#L230-L240
|
17,901
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/data/nvdcve/ConnectionFactory.java
|
ConnectionFactory.h2DataFileExists
|
public static boolean h2DataFileExists(Settings configuration) throws IOException {
final File file = getH2DataFile(configuration);
return file.exists();
}
|
java
|
public static boolean h2DataFileExists(Settings configuration) throws IOException {
final File file = getH2DataFile(configuration);
return file.exists();
}
|
[
"public",
"static",
"boolean",
"h2DataFileExists",
"(",
"Settings",
"configuration",
")",
"throws",
"IOException",
"{",
"final",
"File",
"file",
"=",
"getH2DataFile",
"(",
"configuration",
")",
";",
"return",
"file",
".",
"exists",
"(",
")",
";",
"}"
] |
Determines if the H2 database file exists. If it does not exist then the
data structure will need to be created.
@param configuration the configured settings
@return true if the H2 database file does not exist; otherwise false
@throws IOException thrown if the data directory does not exist and
cannot be created
|
[
"Determines",
"if",
"the",
"H2",
"database",
"file",
"exists",
".",
"If",
"it",
"does",
"not",
"exist",
"then",
"the",
"data",
"structure",
"will",
"need",
"to",
"be",
"created",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/data/nvdcve/ConnectionFactory.java#L263-L266
|
17,902
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/data/nvdcve/ConnectionFactory.java
|
ConnectionFactory.getH2DataFile
|
public static File getH2DataFile(Settings configuration) throws IOException {
final File dir = configuration.getH2DataDirectory();
final String fileName = configuration.getString(Settings.KEYS.DB_FILE_NAME);
final File file = new File(dir, fileName);
return file;
}
|
java
|
public static File getH2DataFile(Settings configuration) throws IOException {
final File dir = configuration.getH2DataDirectory();
final String fileName = configuration.getString(Settings.KEYS.DB_FILE_NAME);
final File file = new File(dir, fileName);
return file;
}
|
[
"public",
"static",
"File",
"getH2DataFile",
"(",
"Settings",
"configuration",
")",
"throws",
"IOException",
"{",
"final",
"File",
"dir",
"=",
"configuration",
".",
"getH2DataDirectory",
"(",
")",
";",
"final",
"String",
"fileName",
"=",
"configuration",
".",
"getString",
"(",
"Settings",
".",
"KEYS",
".",
"DB_FILE_NAME",
")",
";",
"final",
"File",
"file",
"=",
"new",
"File",
"(",
"dir",
",",
"fileName",
")",
";",
"return",
"file",
";",
"}"
] |
Returns a reference to the H2 database file.
@param configuration the configured settings
@return the path to the H2 database file
@throws IOException thrown if there is an error
|
[
"Returns",
"a",
"reference",
"to",
"the",
"H2",
"database",
"file",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/data/nvdcve/ConnectionFactory.java#L275-L280
|
17,903
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/data/nvdcve/ConnectionFactory.java
|
ConnectionFactory.isH2Connection
|
public static boolean isH2Connection(Settings configuration) {
final String connStr;
try {
connStr = configuration.getConnectionString(
Settings.KEYS.DB_CONNECTION_STRING,
Settings.KEYS.DB_FILE_NAME);
} catch (IOException ex) {
LOGGER.debug("Unable to get connectionn string", ex);
return false;
}
return connStr.startsWith("jdbc:h2:file:");
}
|
java
|
public static boolean isH2Connection(Settings configuration) {
final String connStr;
try {
connStr = configuration.getConnectionString(
Settings.KEYS.DB_CONNECTION_STRING,
Settings.KEYS.DB_FILE_NAME);
} catch (IOException ex) {
LOGGER.debug("Unable to get connectionn string", ex);
return false;
}
return connStr.startsWith("jdbc:h2:file:");
}
|
[
"public",
"static",
"boolean",
"isH2Connection",
"(",
"Settings",
"configuration",
")",
"{",
"final",
"String",
"connStr",
";",
"try",
"{",
"connStr",
"=",
"configuration",
".",
"getConnectionString",
"(",
"Settings",
".",
"KEYS",
".",
"DB_CONNECTION_STRING",
",",
"Settings",
".",
"KEYS",
".",
"DB_FILE_NAME",
")",
";",
"}",
"catch",
"(",
"IOException",
"ex",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"Unable to get connectionn string\"",
",",
"ex",
")",
";",
"return",
"false",
";",
"}",
"return",
"connStr",
".",
"startsWith",
"(",
"\"jdbc:h2:file:\"",
")",
";",
"}"
] |
Determines if the connection string is for an H2 database.
@param configuration the configured settings
@return true if the connection string is for an H2 database
|
[
"Determines",
"if",
"the",
"connection",
"string",
"is",
"for",
"an",
"H2",
"database",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/data/nvdcve/ConnectionFactory.java#L297-L308
|
17,904
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/data/nvdcve/ConnectionFactory.java
|
ConnectionFactory.ensureSchemaVersion
|
private void ensureSchemaVersion(Connection conn) throws DatabaseException {
ResultSet rs = null;
PreparedStatement ps = null;
try {
//TODO convert this to use DatabaseProperties
ps = conn.prepareStatement("SELECT value FROM properties WHERE id = 'version'");
rs = ps.executeQuery();
if (rs.next()) {
final String dbSchemaVersion = settings.getString(Settings.KEYS.DB_VERSION);
final DependencyVersion appDbVersion = DependencyVersionUtil.parseVersion(dbSchemaVersion);
if (appDbVersion == null) {
throw new DatabaseException("Invalid application database schema");
}
final DependencyVersion db = DependencyVersionUtil.parseVersion(rs.getString(1));
if (db == null) {
throw new DatabaseException("Invalid database schema");
}
LOGGER.debug("DC Schema: {}", appDbVersion.toString());
LOGGER.debug("DB Schema: {}", db.toString());
if (appDbVersion.compareTo(db) > 0) {
updateSchema(conn, appDbVersion, db);
if (++callDepth < 10) {
ensureSchemaVersion(conn);
}
}
} else {
throw new DatabaseException("Database schema is missing");
}
} catch (SQLException ex) {
LOGGER.debug("", ex);
throw new DatabaseException("Unable to check the database schema version", ex);
} finally {
DBUtils.closeResultSet(rs);
DBUtils.closeStatement(ps);
}
}
|
java
|
private void ensureSchemaVersion(Connection conn) throws DatabaseException {
ResultSet rs = null;
PreparedStatement ps = null;
try {
//TODO convert this to use DatabaseProperties
ps = conn.prepareStatement("SELECT value FROM properties WHERE id = 'version'");
rs = ps.executeQuery();
if (rs.next()) {
final String dbSchemaVersion = settings.getString(Settings.KEYS.DB_VERSION);
final DependencyVersion appDbVersion = DependencyVersionUtil.parseVersion(dbSchemaVersion);
if (appDbVersion == null) {
throw new DatabaseException("Invalid application database schema");
}
final DependencyVersion db = DependencyVersionUtil.parseVersion(rs.getString(1));
if (db == null) {
throw new DatabaseException("Invalid database schema");
}
LOGGER.debug("DC Schema: {}", appDbVersion.toString());
LOGGER.debug("DB Schema: {}", db.toString());
if (appDbVersion.compareTo(db) > 0) {
updateSchema(conn, appDbVersion, db);
if (++callDepth < 10) {
ensureSchemaVersion(conn);
}
}
} else {
throw new DatabaseException("Database schema is missing");
}
} catch (SQLException ex) {
LOGGER.debug("", ex);
throw new DatabaseException("Unable to check the database schema version", ex);
} finally {
DBUtils.closeResultSet(rs);
DBUtils.closeStatement(ps);
}
}
|
[
"private",
"void",
"ensureSchemaVersion",
"(",
"Connection",
"conn",
")",
"throws",
"DatabaseException",
"{",
"ResultSet",
"rs",
"=",
"null",
";",
"PreparedStatement",
"ps",
"=",
"null",
";",
"try",
"{",
"//TODO convert this to use DatabaseProperties",
"ps",
"=",
"conn",
".",
"prepareStatement",
"(",
"\"SELECT value FROM properties WHERE id = 'version'\"",
")",
";",
"rs",
"=",
"ps",
".",
"executeQuery",
"(",
")",
";",
"if",
"(",
"rs",
".",
"next",
"(",
")",
")",
"{",
"final",
"String",
"dbSchemaVersion",
"=",
"settings",
".",
"getString",
"(",
"Settings",
".",
"KEYS",
".",
"DB_VERSION",
")",
";",
"final",
"DependencyVersion",
"appDbVersion",
"=",
"DependencyVersionUtil",
".",
"parseVersion",
"(",
"dbSchemaVersion",
")",
";",
"if",
"(",
"appDbVersion",
"==",
"null",
")",
"{",
"throw",
"new",
"DatabaseException",
"(",
"\"Invalid application database schema\"",
")",
";",
"}",
"final",
"DependencyVersion",
"db",
"=",
"DependencyVersionUtil",
".",
"parseVersion",
"(",
"rs",
".",
"getString",
"(",
"1",
")",
")",
";",
"if",
"(",
"db",
"==",
"null",
")",
"{",
"throw",
"new",
"DatabaseException",
"(",
"\"Invalid database schema\"",
")",
";",
"}",
"LOGGER",
".",
"debug",
"(",
"\"DC Schema: {}\"",
",",
"appDbVersion",
".",
"toString",
"(",
")",
")",
";",
"LOGGER",
".",
"debug",
"(",
"\"DB Schema: {}\"",
",",
"db",
".",
"toString",
"(",
")",
")",
";",
"if",
"(",
"appDbVersion",
".",
"compareTo",
"(",
"db",
")",
">",
"0",
")",
"{",
"updateSchema",
"(",
"conn",
",",
"appDbVersion",
",",
"db",
")",
";",
"if",
"(",
"++",
"callDepth",
"<",
"10",
")",
"{",
"ensureSchemaVersion",
"(",
"conn",
")",
";",
"}",
"}",
"}",
"else",
"{",
"throw",
"new",
"DatabaseException",
"(",
"\"Database schema is missing\"",
")",
";",
"}",
"}",
"catch",
"(",
"SQLException",
"ex",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"\"",
",",
"ex",
")",
";",
"throw",
"new",
"DatabaseException",
"(",
"\"Unable to check the database schema version\"",
",",
"ex",
")",
";",
"}",
"finally",
"{",
"DBUtils",
".",
"closeResultSet",
"(",
"rs",
")",
";",
"DBUtils",
".",
"closeStatement",
"(",
"ps",
")",
";",
"}",
"}"
] |
Uses the provided connection to check the specified schema version within
the database.
@param conn the database connection object
@throws DatabaseException thrown if the schema version is not compatible
with this version of dependency-check
|
[
"Uses",
"the",
"provided",
"connection",
"to",
"check",
"the",
"specified",
"schema",
"version",
"within",
"the",
"database",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/data/nvdcve/ConnectionFactory.java#L405-L440
|
17,905
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/analyzer/NexusAnalyzer.java
|
NexusAnalyzer.checkEnabled
|
private boolean checkEnabled() {
/* Enable this analyzer ONLY if the Nexus URL has been set to something
other than the default one (if it's the default one, we'll use the
central one) and it's enabled by the user.
*/
boolean retval = false;
try {
if (!DEFAULT_URL.equals(getSettings().getString(Settings.KEYS.ANALYZER_NEXUS_URL))
&& getSettings().getBoolean(Settings.KEYS.ANALYZER_NEXUS_ENABLED)) {
LOGGER.info("Enabling Nexus analyzer");
retval = true;
} else {
LOGGER.debug("Nexus analyzer disabled, using Central instead");
}
} catch (InvalidSettingException ise) {
LOGGER.warn("Invalid setting. Disabling Nexus analyzer");
}
return retval;
}
|
java
|
private boolean checkEnabled() {
/* Enable this analyzer ONLY if the Nexus URL has been set to something
other than the default one (if it's the default one, we'll use the
central one) and it's enabled by the user.
*/
boolean retval = false;
try {
if (!DEFAULT_URL.equals(getSettings().getString(Settings.KEYS.ANALYZER_NEXUS_URL))
&& getSettings().getBoolean(Settings.KEYS.ANALYZER_NEXUS_ENABLED)) {
LOGGER.info("Enabling Nexus analyzer");
retval = true;
} else {
LOGGER.debug("Nexus analyzer disabled, using Central instead");
}
} catch (InvalidSettingException ise) {
LOGGER.warn("Invalid setting. Disabling Nexus analyzer");
}
return retval;
}
|
[
"private",
"boolean",
"checkEnabled",
"(",
")",
"{",
"/* Enable this analyzer ONLY if the Nexus URL has been set to something\n other than the default one (if it's the default one, we'll use the\n central one) and it's enabled by the user.\n */",
"boolean",
"retval",
"=",
"false",
";",
"try",
"{",
"if",
"(",
"!",
"DEFAULT_URL",
".",
"equals",
"(",
"getSettings",
"(",
")",
".",
"getString",
"(",
"Settings",
".",
"KEYS",
".",
"ANALYZER_NEXUS_URL",
")",
")",
"&&",
"getSettings",
"(",
")",
".",
"getBoolean",
"(",
"Settings",
".",
"KEYS",
".",
"ANALYZER_NEXUS_ENABLED",
")",
")",
"{",
"LOGGER",
".",
"info",
"(",
"\"Enabling Nexus analyzer\"",
")",
";",
"retval",
"=",
"true",
";",
"}",
"else",
"{",
"LOGGER",
".",
"debug",
"(",
"\"Nexus analyzer disabled, using Central instead\"",
")",
";",
"}",
"}",
"catch",
"(",
"InvalidSettingException",
"ise",
")",
"{",
"LOGGER",
".",
"warn",
"(",
"\"Invalid setting. Disabling Nexus analyzer\"",
")",
";",
"}",
"return",
"retval",
";",
"}"
] |
Determines if this analyzer is enabled
@return <code>true</code> if the analyzer is enabled; otherwise
<code>false</code>
|
[
"Determines",
"if",
"this",
"analyzer",
"is",
"enabled"
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/analyzer/NexusAnalyzer.java#L125-L144
|
17,906
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/analyzer/NexusAnalyzer.java
|
NexusAnalyzer.useProxy
|
public boolean useProxy() {
try {
return getSettings().getString(Settings.KEYS.PROXY_SERVER) != null
&& getSettings().getBoolean(Settings.KEYS.ANALYZER_NEXUS_USES_PROXY);
} catch (InvalidSettingException ise) {
LOGGER.warn("Failed to parse proxy settings.", ise);
return false;
}
}
|
java
|
public boolean useProxy() {
try {
return getSettings().getString(Settings.KEYS.PROXY_SERVER) != null
&& getSettings().getBoolean(Settings.KEYS.ANALYZER_NEXUS_USES_PROXY);
} catch (InvalidSettingException ise) {
LOGGER.warn("Failed to parse proxy settings.", ise);
return false;
}
}
|
[
"public",
"boolean",
"useProxy",
"(",
")",
"{",
"try",
"{",
"return",
"getSettings",
"(",
")",
".",
"getString",
"(",
"Settings",
".",
"KEYS",
".",
"PROXY_SERVER",
")",
"!=",
"null",
"&&",
"getSettings",
"(",
")",
".",
"getBoolean",
"(",
"Settings",
".",
"KEYS",
".",
"ANALYZER_NEXUS_USES_PROXY",
")",
";",
"}",
"catch",
"(",
"InvalidSettingException",
"ise",
")",
"{",
"LOGGER",
".",
"warn",
"(",
"\"Failed to parse proxy settings.\"",
",",
"ise",
")",
";",
"return",
"false",
";",
"}",
"}"
] |
Determine if a proxy should be used for the Nexus Analyzer.
@return {@code true} if a proxy should be used
|
[
"Determine",
"if",
"a",
"proxy",
"should",
"be",
"used",
"for",
"the",
"Nexus",
"Analyzer",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/analyzer/NexusAnalyzer.java#L288-L296
|
17,907
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/data/update/RetireJSDataSource.java
|
RetireJSDataSource.update
|
@Override
public boolean update(Engine engine) throws UpdateException {
this.settings = engine.getSettings();
String url = null;
try {
final boolean autoupdate = settings.getBoolean(Settings.KEYS.AUTO_UPDATE, true);
final boolean enabled = settings.getBoolean(Settings.KEYS.ANALYZER_RETIREJS_ENABLED, true);
final File repoFile = new File(settings.getDataDirectory(), "jsrepository.json");
final boolean proceed = enabled && autoupdate && shouldUpdagte(repoFile);
if (proceed) {
LOGGER.debug("Begin RetireJS Update");
url = settings.getString(Settings.KEYS.ANALYZER_RETIREJS_REPO_JS_URL, DEFAULT_JS_URL);
initializeRetireJsRepo(settings, new URL(url));
}
} catch (InvalidSettingException ex) {
throw new UpdateException("Unable to determine if autoupdate is enabled", ex);
} catch (MalformedURLException ex) {
throw new UpdateException(String.format("Inavlid URL for RetireJS repository (%s)", url), ex);
} catch (IOException ex) {
throw new UpdateException("Unable to get the data directory", ex);
}
return false;
}
|
java
|
@Override
public boolean update(Engine engine) throws UpdateException {
this.settings = engine.getSettings();
String url = null;
try {
final boolean autoupdate = settings.getBoolean(Settings.KEYS.AUTO_UPDATE, true);
final boolean enabled = settings.getBoolean(Settings.KEYS.ANALYZER_RETIREJS_ENABLED, true);
final File repoFile = new File(settings.getDataDirectory(), "jsrepository.json");
final boolean proceed = enabled && autoupdate && shouldUpdagte(repoFile);
if (proceed) {
LOGGER.debug("Begin RetireJS Update");
url = settings.getString(Settings.KEYS.ANALYZER_RETIREJS_REPO_JS_URL, DEFAULT_JS_URL);
initializeRetireJsRepo(settings, new URL(url));
}
} catch (InvalidSettingException ex) {
throw new UpdateException("Unable to determine if autoupdate is enabled", ex);
} catch (MalformedURLException ex) {
throw new UpdateException(String.format("Inavlid URL for RetireJS repository (%s)", url), ex);
} catch (IOException ex) {
throw new UpdateException("Unable to get the data directory", ex);
}
return false;
}
|
[
"@",
"Override",
"public",
"boolean",
"update",
"(",
"Engine",
"engine",
")",
"throws",
"UpdateException",
"{",
"this",
".",
"settings",
"=",
"engine",
".",
"getSettings",
"(",
")",
";",
"String",
"url",
"=",
"null",
";",
"try",
"{",
"final",
"boolean",
"autoupdate",
"=",
"settings",
".",
"getBoolean",
"(",
"Settings",
".",
"KEYS",
".",
"AUTO_UPDATE",
",",
"true",
")",
";",
"final",
"boolean",
"enabled",
"=",
"settings",
".",
"getBoolean",
"(",
"Settings",
".",
"KEYS",
".",
"ANALYZER_RETIREJS_ENABLED",
",",
"true",
")",
";",
"final",
"File",
"repoFile",
"=",
"new",
"File",
"(",
"settings",
".",
"getDataDirectory",
"(",
")",
",",
"\"jsrepository.json\"",
")",
";",
"final",
"boolean",
"proceed",
"=",
"enabled",
"&&",
"autoupdate",
"&&",
"shouldUpdagte",
"(",
"repoFile",
")",
";",
"if",
"(",
"proceed",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"Begin RetireJS Update\"",
")",
";",
"url",
"=",
"settings",
".",
"getString",
"(",
"Settings",
".",
"KEYS",
".",
"ANALYZER_RETIREJS_REPO_JS_URL",
",",
"DEFAULT_JS_URL",
")",
";",
"initializeRetireJsRepo",
"(",
"settings",
",",
"new",
"URL",
"(",
"url",
")",
")",
";",
"}",
"}",
"catch",
"(",
"InvalidSettingException",
"ex",
")",
"{",
"throw",
"new",
"UpdateException",
"(",
"\"Unable to determine if autoupdate is enabled\"",
",",
"ex",
")",
";",
"}",
"catch",
"(",
"MalformedURLException",
"ex",
")",
"{",
"throw",
"new",
"UpdateException",
"(",
"String",
".",
"format",
"(",
"\"Inavlid URL for RetireJS repository (%s)\"",
",",
"url",
")",
",",
"ex",
")",
";",
"}",
"catch",
"(",
"IOException",
"ex",
")",
"{",
"throw",
"new",
"UpdateException",
"(",
"\"Unable to get the data directory\"",
",",
"ex",
")",
";",
"}",
"return",
"false",
";",
"}"
] |
Downloads the current RetireJS data source.
@return returns false as no updates are made to the database that would
require compaction
@throws UpdateException thrown if the update failed
|
[
"Downloads",
"the",
"current",
"RetireJS",
"data",
"source",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/data/update/RetireJSDataSource.java#L89-L111
|
17,908
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/data/update/RetireJSDataSource.java
|
RetireJSDataSource.shouldUpdagte
|
protected boolean shouldUpdagte(File repo) throws NumberFormatException {
boolean proceed = true;
if (repo != null && repo.isFile()) {
final int validForHours = settings.getInt(Settings.KEYS.ANALYZER_RETIREJS_REPO_VALID_FOR_HOURS, 0);
final long lastUpdatedOn = repo.lastModified();
final long now = System.currentTimeMillis();
LOGGER.debug("Last updated: {}", lastUpdatedOn);
LOGGER.debug("Now: {}", now);
final long msValid = validForHours * 60L * 60L * 1000L;
proceed = (now - lastUpdatedOn) > msValid;
if (!proceed) {
LOGGER.info("Skipping RetireJS update since last update was within {} hours.", validForHours);
}
}
return proceed;
}
|
java
|
protected boolean shouldUpdagte(File repo) throws NumberFormatException {
boolean proceed = true;
if (repo != null && repo.isFile()) {
final int validForHours = settings.getInt(Settings.KEYS.ANALYZER_RETIREJS_REPO_VALID_FOR_HOURS, 0);
final long lastUpdatedOn = repo.lastModified();
final long now = System.currentTimeMillis();
LOGGER.debug("Last updated: {}", lastUpdatedOn);
LOGGER.debug("Now: {}", now);
final long msValid = validForHours * 60L * 60L * 1000L;
proceed = (now - lastUpdatedOn) > msValid;
if (!proceed) {
LOGGER.info("Skipping RetireJS update since last update was within {} hours.", validForHours);
}
}
return proceed;
}
|
[
"protected",
"boolean",
"shouldUpdagte",
"(",
"File",
"repo",
")",
"throws",
"NumberFormatException",
"{",
"boolean",
"proceed",
"=",
"true",
";",
"if",
"(",
"repo",
"!=",
"null",
"&&",
"repo",
".",
"isFile",
"(",
")",
")",
"{",
"final",
"int",
"validForHours",
"=",
"settings",
".",
"getInt",
"(",
"Settings",
".",
"KEYS",
".",
"ANALYZER_RETIREJS_REPO_VALID_FOR_HOURS",
",",
"0",
")",
";",
"final",
"long",
"lastUpdatedOn",
"=",
"repo",
".",
"lastModified",
"(",
")",
";",
"final",
"long",
"now",
"=",
"System",
".",
"currentTimeMillis",
"(",
")",
";",
"LOGGER",
".",
"debug",
"(",
"\"Last updated: {}\"",
",",
"lastUpdatedOn",
")",
";",
"LOGGER",
".",
"debug",
"(",
"\"Now: {}\"",
",",
"now",
")",
";",
"final",
"long",
"msValid",
"=",
"validForHours",
"*",
"60L",
"*",
"60L",
"*",
"1000L",
";",
"proceed",
"=",
"(",
"now",
"-",
"lastUpdatedOn",
")",
">",
"msValid",
";",
"if",
"(",
"!",
"proceed",
")",
"{",
"LOGGER",
".",
"info",
"(",
"\"Skipping RetireJS update since last update was within {} hours.\"",
",",
"validForHours",
")",
";",
"}",
"}",
"return",
"proceed",
";",
"}"
] |
Determines if the we should update the RetireJS database.
@param repo the retire JS repository.
@return <code>true</code> if an updated to the RetireJS database should
be performed; otherwise <code>false</code>
@throws NumberFormatException thrown if an invalid value is contained in
the database properties
|
[
"Determines",
"if",
"the",
"we",
"should",
"update",
"the",
"RetireJS",
"database",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/data/update/RetireJSDataSource.java#L122-L137
|
17,909
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/data/update/RetireJSDataSource.java
|
RetireJSDataSource.initializeRetireJsRepo
|
private void initializeRetireJsRepo(Settings settings, URL repoUrl) throws UpdateException {
try {
final File dataDir = settings.getDataDirectory();
final File tmpDir = settings.getTempDirectory();
boolean useProxy = false;
if (null != settings.getString(Settings.KEYS.PROXY_SERVER)) {
useProxy = true;
LOGGER.debug("Using proxy");
}
LOGGER.debug("RetireJS Repo URL: {}", repoUrl.toExternalForm());
final URLConnectionFactory factory = new URLConnectionFactory(settings);
final HttpURLConnection conn = factory.createHttpURLConnection(repoUrl, useProxy);
final String filename = repoUrl.getFile().substring(repoUrl.getFile().lastIndexOf("/") + 1, repoUrl.getFile().length());
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
final File tmpFile = new File(tmpDir, filename);
final File repoFile = new File(dataDir, filename);
try (InputStream inputStream = conn.getInputStream();
FileOutputStream outputStream = new FileOutputStream(tmpFile)) {
IOUtils.copy(inputStream, outputStream);
}
//using move fails if target and destination are on different disks which does happen (see #1394 and #1404)
Files.copy(tmpFile.toPath(), repoFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
if (!tmpFile.delete()) {
tmpFile.deleteOnExit();
}
}
} catch (IOException e) {
throw new UpdateException("Failed to initialize the RetireJS repo", e);
}
}
|
java
|
private void initializeRetireJsRepo(Settings settings, URL repoUrl) throws UpdateException {
try {
final File dataDir = settings.getDataDirectory();
final File tmpDir = settings.getTempDirectory();
boolean useProxy = false;
if (null != settings.getString(Settings.KEYS.PROXY_SERVER)) {
useProxy = true;
LOGGER.debug("Using proxy");
}
LOGGER.debug("RetireJS Repo URL: {}", repoUrl.toExternalForm());
final URLConnectionFactory factory = new URLConnectionFactory(settings);
final HttpURLConnection conn = factory.createHttpURLConnection(repoUrl, useProxy);
final String filename = repoUrl.getFile().substring(repoUrl.getFile().lastIndexOf("/") + 1, repoUrl.getFile().length());
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
final File tmpFile = new File(tmpDir, filename);
final File repoFile = new File(dataDir, filename);
try (InputStream inputStream = conn.getInputStream();
FileOutputStream outputStream = new FileOutputStream(tmpFile)) {
IOUtils.copy(inputStream, outputStream);
}
//using move fails if target and destination are on different disks which does happen (see #1394 and #1404)
Files.copy(tmpFile.toPath(), repoFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
if (!tmpFile.delete()) {
tmpFile.deleteOnExit();
}
}
} catch (IOException e) {
throw new UpdateException("Failed to initialize the RetireJS repo", e);
}
}
|
[
"private",
"void",
"initializeRetireJsRepo",
"(",
"Settings",
"settings",
",",
"URL",
"repoUrl",
")",
"throws",
"UpdateException",
"{",
"try",
"{",
"final",
"File",
"dataDir",
"=",
"settings",
".",
"getDataDirectory",
"(",
")",
";",
"final",
"File",
"tmpDir",
"=",
"settings",
".",
"getTempDirectory",
"(",
")",
";",
"boolean",
"useProxy",
"=",
"false",
";",
"if",
"(",
"null",
"!=",
"settings",
".",
"getString",
"(",
"Settings",
".",
"KEYS",
".",
"PROXY_SERVER",
")",
")",
"{",
"useProxy",
"=",
"true",
";",
"LOGGER",
".",
"debug",
"(",
"\"Using proxy\"",
")",
";",
"}",
"LOGGER",
".",
"debug",
"(",
"\"RetireJS Repo URL: {}\"",
",",
"repoUrl",
".",
"toExternalForm",
"(",
")",
")",
";",
"final",
"URLConnectionFactory",
"factory",
"=",
"new",
"URLConnectionFactory",
"(",
"settings",
")",
";",
"final",
"HttpURLConnection",
"conn",
"=",
"factory",
".",
"createHttpURLConnection",
"(",
"repoUrl",
",",
"useProxy",
")",
";",
"final",
"String",
"filename",
"=",
"repoUrl",
".",
"getFile",
"(",
")",
".",
"substring",
"(",
"repoUrl",
".",
"getFile",
"(",
")",
".",
"lastIndexOf",
"(",
"\"/\"",
")",
"+",
"1",
",",
"repoUrl",
".",
"getFile",
"(",
")",
".",
"length",
"(",
")",
")",
";",
"if",
"(",
"conn",
".",
"getResponseCode",
"(",
")",
"==",
"HttpURLConnection",
".",
"HTTP_OK",
")",
"{",
"final",
"File",
"tmpFile",
"=",
"new",
"File",
"(",
"tmpDir",
",",
"filename",
")",
";",
"final",
"File",
"repoFile",
"=",
"new",
"File",
"(",
"dataDir",
",",
"filename",
")",
";",
"try",
"(",
"InputStream",
"inputStream",
"=",
"conn",
".",
"getInputStream",
"(",
")",
";",
"FileOutputStream",
"outputStream",
"=",
"new",
"FileOutputStream",
"(",
"tmpFile",
")",
")",
"{",
"IOUtils",
".",
"copy",
"(",
"inputStream",
",",
"outputStream",
")",
";",
"}",
"//using move fails if target and destination are on different disks which does happen (see #1394 and #1404)",
"Files",
".",
"copy",
"(",
"tmpFile",
".",
"toPath",
"(",
")",
",",
"repoFile",
".",
"toPath",
"(",
")",
",",
"StandardCopyOption",
".",
"REPLACE_EXISTING",
")",
";",
"if",
"(",
"!",
"tmpFile",
".",
"delete",
"(",
")",
")",
"{",
"tmpFile",
".",
"deleteOnExit",
"(",
")",
";",
"}",
"}",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"throw",
"new",
"UpdateException",
"(",
"\"Failed to initialize the RetireJS repo\"",
",",
"e",
")",
";",
"}",
"}"
] |
Initializes the local RetireJS repository
@param settings a reference to the dependency-check settings
@param repoUrl the URL to the RetireJS repo to use
@throws UpdateException thrown if there is an exception during
initialization
|
[
"Initializes",
"the",
"local",
"RetireJS",
"repository"
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/data/update/RetireJSDataSource.java#L147-L176
|
17,910
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/analyzer/AbstractAnalyzer.java
|
AbstractAnalyzer.prepare
|
@Override
public final void prepare(Engine engine) throws InitializationException {
if (isEnabled()) {
prepareAnalyzer(engine);
} else {
LOGGER.debug("{} has been disabled", getName());
}
}
|
java
|
@Override
public final void prepare(Engine engine) throws InitializationException {
if (isEnabled()) {
prepareAnalyzer(engine);
} else {
LOGGER.debug("{} has been disabled", getName());
}
}
|
[
"@",
"Override",
"public",
"final",
"void",
"prepare",
"(",
"Engine",
"engine",
")",
"throws",
"InitializationException",
"{",
"if",
"(",
"isEnabled",
"(",
")",
")",
"{",
"prepareAnalyzer",
"(",
"engine",
")",
";",
"}",
"else",
"{",
"LOGGER",
".",
"debug",
"(",
"\"{} has been disabled\"",
",",
"getName",
"(",
")",
")",
";",
"}",
"}"
] |
Initialize the abstract analyzer.
@param engine a reference to the dependency-check engine
@throws InitializationException thrown if there is an exception
|
[
"Initialize",
"the",
"abstract",
"analyzer",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/analyzer/AbstractAnalyzer.java#L104-L111
|
17,911
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/data/nvdcve/DriverShim.java
|
DriverShim.getParentLogger
|
@Override
public java.util.logging.Logger getParentLogger() throws SQLFeatureNotSupportedException {
//return driver.getParentLogger();
Method m = null;
try {
m = driver.getClass().getMethod("getParentLogger");
} catch (Throwable e) {
throw new SQLFeatureNotSupportedException();
}
if (m != null) {
try {
return (java.util.logging.Logger) m.invoke(m);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
LOGGER.trace("", ex);
}
}
throw new SQLFeatureNotSupportedException();
}
|
java
|
@Override
public java.util.logging.Logger getParentLogger() throws SQLFeatureNotSupportedException {
//return driver.getParentLogger();
Method m = null;
try {
m = driver.getClass().getMethod("getParentLogger");
} catch (Throwable e) {
throw new SQLFeatureNotSupportedException();
}
if (m != null) {
try {
return (java.util.logging.Logger) m.invoke(m);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
LOGGER.trace("", ex);
}
}
throw new SQLFeatureNotSupportedException();
}
|
[
"@",
"Override",
"public",
"java",
".",
"util",
".",
"logging",
".",
"Logger",
"getParentLogger",
"(",
")",
"throws",
"SQLFeatureNotSupportedException",
"{",
"//return driver.getParentLogger();",
"Method",
"m",
"=",
"null",
";",
"try",
"{",
"m",
"=",
"driver",
".",
"getClass",
"(",
")",
".",
"getMethod",
"(",
"\"getParentLogger\"",
")",
";",
"}",
"catch",
"(",
"Throwable",
"e",
")",
"{",
"throw",
"new",
"SQLFeatureNotSupportedException",
"(",
")",
";",
"}",
"if",
"(",
"m",
"!=",
"null",
")",
"{",
"try",
"{",
"return",
"(",
"java",
".",
"util",
".",
"logging",
".",
"Logger",
")",
"m",
".",
"invoke",
"(",
"m",
")",
";",
"}",
"catch",
"(",
"IllegalAccessException",
"|",
"IllegalArgumentException",
"|",
"InvocationTargetException",
"ex",
")",
"{",
"LOGGER",
".",
"trace",
"(",
"\"\"",
",",
"ex",
")",
";",
"}",
"}",
"throw",
"new",
"SQLFeatureNotSupportedException",
"(",
")",
";",
"}"
] |
Wraps the call to the underlying driver's getParentLogger method.
@return the parent's Logger
@throws SQLFeatureNotSupportedException thrown if the feature is not
supported
@see java.sql.Driver#getParentLogger()
|
[
"Wraps",
"the",
"call",
"to",
"the",
"underlying",
"driver",
"s",
"getParentLogger",
"method",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/data/nvdcve/DriverShim.java#L124-L141
|
17,912
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/utils/DBUtils.java
|
DBUtils.getGeneratedKey
|
public static int getGeneratedKey(PreparedStatement statement) throws DatabaseException {
ResultSet rs = null;
int id = 0;
try {
rs = statement.getGeneratedKeys();
if (!rs.next()) {
throw new DatabaseException("Unable to get primary key for inserted row");
}
id = rs.getInt(1);
} catch (SQLException ex) {
throw new DatabaseException("Unable to get primary key for inserted row");
} finally {
closeResultSet(rs);
}
return id;
}
|
java
|
public static int getGeneratedKey(PreparedStatement statement) throws DatabaseException {
ResultSet rs = null;
int id = 0;
try {
rs = statement.getGeneratedKeys();
if (!rs.next()) {
throw new DatabaseException("Unable to get primary key for inserted row");
}
id = rs.getInt(1);
} catch (SQLException ex) {
throw new DatabaseException("Unable to get primary key for inserted row");
} finally {
closeResultSet(rs);
}
return id;
}
|
[
"public",
"static",
"int",
"getGeneratedKey",
"(",
"PreparedStatement",
"statement",
")",
"throws",
"DatabaseException",
"{",
"ResultSet",
"rs",
"=",
"null",
";",
"int",
"id",
"=",
"0",
";",
"try",
"{",
"rs",
"=",
"statement",
".",
"getGeneratedKeys",
"(",
")",
";",
"if",
"(",
"!",
"rs",
".",
"next",
"(",
")",
")",
"{",
"throw",
"new",
"DatabaseException",
"(",
"\"Unable to get primary key for inserted row\"",
")",
";",
"}",
"id",
"=",
"rs",
".",
"getInt",
"(",
"1",
")",
";",
"}",
"catch",
"(",
"SQLException",
"ex",
")",
"{",
"throw",
"new",
"DatabaseException",
"(",
"\"Unable to get primary key for inserted row\"",
")",
";",
"}",
"finally",
"{",
"closeResultSet",
"(",
"rs",
")",
";",
"}",
"return",
"id",
";",
"}"
] |
Returns the generated integer primary key for a newly inserted row.
@param statement a prepared statement that just executed an insert
@return a primary key
@throws DatabaseException thrown if there is an exception obtaining the
key
|
[
"Returns",
"the",
"generated",
"integer",
"primary",
"key",
"for",
"a",
"newly",
"inserted",
"row",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/utils/DBUtils.java#L56-L71
|
17,913
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/utils/DBUtils.java
|
DBUtils.closeStatement
|
public static void closeStatement(Statement statement) {
try {
if (statement != null && !statement.isClosed()) {
statement.close();
}
} catch (SQLException ex) {
LOGGER.trace(statement.toString(), ex);
}
}
|
java
|
public static void closeStatement(Statement statement) {
try {
if (statement != null && !statement.isClosed()) {
statement.close();
}
} catch (SQLException ex) {
LOGGER.trace(statement.toString(), ex);
}
}
|
[
"public",
"static",
"void",
"closeStatement",
"(",
"Statement",
"statement",
")",
"{",
"try",
"{",
"if",
"(",
"statement",
"!=",
"null",
"&&",
"!",
"statement",
".",
"isClosed",
"(",
")",
")",
"{",
"statement",
".",
"close",
"(",
")",
";",
"}",
"}",
"catch",
"(",
"SQLException",
"ex",
")",
"{",
"LOGGER",
".",
"trace",
"(",
"statement",
".",
"toString",
"(",
")",
",",
"ex",
")",
";",
"}",
"}"
] |
Closes the given statement object ignoring any exceptions that occur.
@param statement a Statement object
|
[
"Closes",
"the",
"given",
"statement",
"object",
"ignoring",
"any",
"exceptions",
"that",
"occur",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/utils/DBUtils.java#L78-L87
|
17,914
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/utils/DBUtils.java
|
DBUtils.closeResultSet
|
public static void closeResultSet(ResultSet rs) {
try {
if (rs != null && !rs.isClosed()) {
rs.close();
}
} catch (SQLException ex) {
LOGGER.trace(rs.toString(), ex);
}
}
|
java
|
public static void closeResultSet(ResultSet rs) {
try {
if (rs != null && !rs.isClosed()) {
rs.close();
}
} catch (SQLException ex) {
LOGGER.trace(rs.toString(), ex);
}
}
|
[
"public",
"static",
"void",
"closeResultSet",
"(",
"ResultSet",
"rs",
")",
"{",
"try",
"{",
"if",
"(",
"rs",
"!=",
"null",
"&&",
"!",
"rs",
".",
"isClosed",
"(",
")",
")",
"{",
"rs",
".",
"close",
"(",
")",
";",
"}",
"}",
"catch",
"(",
"SQLException",
"ex",
")",
"{",
"LOGGER",
".",
"trace",
"(",
"rs",
".",
"toString",
"(",
")",
",",
"ex",
")",
";",
"}",
"}"
] |
Closes the result set capturing and ignoring any SQLExceptions that
occur.
@param rs a ResultSet to close
|
[
"Closes",
"the",
"result",
"set",
"capturing",
"and",
"ignoring",
"any",
"SQLExceptions",
"that",
"occur",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/utils/DBUtils.java#L95-L103
|
17,915
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/reporting/EscapeTool.java
|
EscapeTool.url
|
public String url(String text) {
if (text == null || text.isEmpty()) {
return text;
}
try {
return URLEncoder.encode(text, UTF_8);
} catch (UnsupportedEncodingException ex) {
LOGGER.warn("UTF-8 is not supported?");
LOGGER.info("", ex);
}
return "";
}
|
java
|
public String url(String text) {
if (text == null || text.isEmpty()) {
return text;
}
try {
return URLEncoder.encode(text, UTF_8);
} catch (UnsupportedEncodingException ex) {
LOGGER.warn("UTF-8 is not supported?");
LOGGER.info("", ex);
}
return "";
}
|
[
"public",
"String",
"url",
"(",
"String",
"text",
")",
"{",
"if",
"(",
"text",
"==",
"null",
"||",
"text",
".",
"isEmpty",
"(",
")",
")",
"{",
"return",
"text",
";",
"}",
"try",
"{",
"return",
"URLEncoder",
".",
"encode",
"(",
"text",
",",
"UTF_8",
")",
";",
"}",
"catch",
"(",
"UnsupportedEncodingException",
"ex",
")",
"{",
"LOGGER",
".",
"warn",
"(",
"\"UTF-8 is not supported?\"",
")",
";",
"LOGGER",
".",
"info",
"(",
"\"\"",
",",
"ex",
")",
";",
"}",
"return",
"\"\"",
";",
"}"
] |
URL Encodes the provided text.
@param text the text to encode
@return the URL encoded text
|
[
"URL",
"Encodes",
"the",
"provided",
"text",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/reporting/EscapeTool.java#L51-L62
|
17,916
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/reporting/EscapeTool.java
|
EscapeTool.html
|
public String html(String text) {
if (text == null || text.isEmpty()) {
return text;
}
return StringEscapeUtils.escapeHtml4(text);
}
|
java
|
public String html(String text) {
if (text == null || text.isEmpty()) {
return text;
}
return StringEscapeUtils.escapeHtml4(text);
}
|
[
"public",
"String",
"html",
"(",
"String",
"text",
")",
"{",
"if",
"(",
"text",
"==",
"null",
"||",
"text",
".",
"isEmpty",
"(",
")",
")",
"{",
"return",
"text",
";",
"}",
"return",
"StringEscapeUtils",
".",
"escapeHtml4",
"(",
"text",
")",
";",
"}"
] |
HTML Encodes the provided text.
@param text the text to encode
@return the HTML encoded text
|
[
"HTML",
"Encodes",
"the",
"provided",
"text",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/reporting/EscapeTool.java#L70-L75
|
17,917
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/reporting/EscapeTool.java
|
EscapeTool.xml
|
public String xml(String text) {
if (text == null || text.isEmpty()) {
return text;
}
return StringEscapeUtils.escapeXml11(text);
}
|
java
|
public String xml(String text) {
if (text == null || text.isEmpty()) {
return text;
}
return StringEscapeUtils.escapeXml11(text);
}
|
[
"public",
"String",
"xml",
"(",
"String",
"text",
")",
"{",
"if",
"(",
"text",
"==",
"null",
"||",
"text",
".",
"isEmpty",
"(",
")",
")",
"{",
"return",
"text",
";",
"}",
"return",
"StringEscapeUtils",
".",
"escapeXml11",
"(",
"text",
")",
";",
"}"
] |
XML Encodes the provided text.
@param text the text to encode
@return the XML encoded text
|
[
"XML",
"Encodes",
"the",
"provided",
"text",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/reporting/EscapeTool.java#L83-L88
|
17,918
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/reporting/EscapeTool.java
|
EscapeTool.json
|
public String json(String text) {
if (text == null || text.isEmpty()) {
return text;
}
return StringEscapeUtils.escapeJson(text);
}
|
java
|
public String json(String text) {
if (text == null || text.isEmpty()) {
return text;
}
return StringEscapeUtils.escapeJson(text);
}
|
[
"public",
"String",
"json",
"(",
"String",
"text",
")",
"{",
"if",
"(",
"text",
"==",
"null",
"||",
"text",
".",
"isEmpty",
"(",
")",
")",
"{",
"return",
"text",
";",
"}",
"return",
"StringEscapeUtils",
".",
"escapeJson",
"(",
"text",
")",
";",
"}"
] |
JSON Encodes the provided text.
@param text the text to encode
@return the JSON encoded text
|
[
"JSON",
"Encodes",
"the",
"provided",
"text",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/reporting/EscapeTool.java#L96-L101
|
17,919
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/reporting/EscapeTool.java
|
EscapeTool.javascript
|
public String javascript(String text) {
if (text == null || text.isEmpty()) {
return text;
}
return StringEscapeUtils.escapeEcmaScript(text);
}
|
java
|
public String javascript(String text) {
if (text == null || text.isEmpty()) {
return text;
}
return StringEscapeUtils.escapeEcmaScript(text);
}
|
[
"public",
"String",
"javascript",
"(",
"String",
"text",
")",
"{",
"if",
"(",
"text",
"==",
"null",
"||",
"text",
".",
"isEmpty",
"(",
")",
")",
"{",
"return",
"text",
";",
"}",
"return",
"StringEscapeUtils",
".",
"escapeEcmaScript",
"(",
"text",
")",
";",
"}"
] |
JavaScript encodes the provided text.
@param text the text to encode
@return the JavaScript encoded text
|
[
"JavaScript",
"encodes",
"the",
"provided",
"text",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/reporting/EscapeTool.java#L109-L114
|
17,920
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/reporting/EscapeTool.java
|
EscapeTool.csvIdentifiers
|
public String csvIdentifiers(Set<Identifier> ids) {
if (ids == null || ids.isEmpty()) {
return "\"\"";
}
boolean addComma = false;
final StringBuilder sb = new StringBuilder();
for (Identifier id : ids) {
if (addComma) {
sb.append(", ");
} else {
addComma = true;
}
sb.append(id.getValue());
}
if (sb.length() == 0) {
return "\"\"";
}
return StringEscapeUtils.escapeCsv(sb.toString());
}
|
java
|
public String csvIdentifiers(Set<Identifier> ids) {
if (ids == null || ids.isEmpty()) {
return "\"\"";
}
boolean addComma = false;
final StringBuilder sb = new StringBuilder();
for (Identifier id : ids) {
if (addComma) {
sb.append(", ");
} else {
addComma = true;
}
sb.append(id.getValue());
}
if (sb.length() == 0) {
return "\"\"";
}
return StringEscapeUtils.escapeCsv(sb.toString());
}
|
[
"public",
"String",
"csvIdentifiers",
"(",
"Set",
"<",
"Identifier",
">",
"ids",
")",
"{",
"if",
"(",
"ids",
"==",
"null",
"||",
"ids",
".",
"isEmpty",
"(",
")",
")",
"{",
"return",
"\"\\\"\\\"\"",
";",
"}",
"boolean",
"addComma",
"=",
"false",
";",
"final",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"for",
"(",
"Identifier",
"id",
":",
"ids",
")",
"{",
"if",
"(",
"addComma",
")",
"{",
"sb",
".",
"append",
"(",
"\", \"",
")",
";",
"}",
"else",
"{",
"addComma",
"=",
"true",
";",
"}",
"sb",
".",
"append",
"(",
"id",
".",
"getValue",
"(",
")",
")",
";",
"}",
"if",
"(",
"sb",
".",
"length",
"(",
")",
"==",
"0",
")",
"{",
"return",
"\"\\\"\\\"\"",
";",
"}",
"return",
"StringEscapeUtils",
".",
"escapeCsv",
"(",
"sb",
".",
"toString",
"(",
")",
")",
";",
"}"
] |
Takes a set of Identifiers, filters them to none CPE, and formats them
for display in a CSV.
@param ids the set of identifiers
@return the formatted list of none CPE identifiers
|
[
"Takes",
"a",
"set",
"of",
"Identifiers",
"filters",
"them",
"to",
"none",
"CPE",
"and",
"formats",
"them",
"for",
"display",
"in",
"a",
"CSV",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/reporting/EscapeTool.java#L142-L160
|
17,921
|
jeremylong/DependencyCheck
|
maven/src/main/java/org/owasp/dependencycheck/maven/AggregateMojo.java
|
AggregateMojo.scanDependencies
|
@Override
protected ExceptionCollection scanDependencies(final Engine engine) throws MojoExecutionException {
ExceptionCollection exCol = scanArtifacts(getProject(), engine, true);
for (MavenProject childProject : getDescendants(this.getProject())) {
final ExceptionCollection ex = scanArtifacts(childProject, engine, true);
if (ex != null) {
if (exCol == null) {
exCol = ex;
}
exCol.getExceptions().addAll(ex.getExceptions());
if (ex.isFatal()) {
exCol.setFatal(true);
final String msg = String.format("Fatal exception(s) analyzing %s", childProject.getName());
if (this.isFailOnError()) {
throw new MojoExecutionException(msg, exCol);
}
getLog().error(msg);
if (getLog().isDebugEnabled()) {
getLog().debug(exCol);
}
}
}
}
return exCol;
}
|
java
|
@Override
protected ExceptionCollection scanDependencies(final Engine engine) throws MojoExecutionException {
ExceptionCollection exCol = scanArtifacts(getProject(), engine, true);
for (MavenProject childProject : getDescendants(this.getProject())) {
final ExceptionCollection ex = scanArtifacts(childProject, engine, true);
if (ex != null) {
if (exCol == null) {
exCol = ex;
}
exCol.getExceptions().addAll(ex.getExceptions());
if (ex.isFatal()) {
exCol.setFatal(true);
final String msg = String.format("Fatal exception(s) analyzing %s", childProject.getName());
if (this.isFailOnError()) {
throw new MojoExecutionException(msg, exCol);
}
getLog().error(msg);
if (getLog().isDebugEnabled()) {
getLog().debug(exCol);
}
}
}
}
return exCol;
}
|
[
"@",
"Override",
"protected",
"ExceptionCollection",
"scanDependencies",
"(",
"final",
"Engine",
"engine",
")",
"throws",
"MojoExecutionException",
"{",
"ExceptionCollection",
"exCol",
"=",
"scanArtifacts",
"(",
"getProject",
"(",
")",
",",
"engine",
",",
"true",
")",
";",
"for",
"(",
"MavenProject",
"childProject",
":",
"getDescendants",
"(",
"this",
".",
"getProject",
"(",
")",
")",
")",
"{",
"final",
"ExceptionCollection",
"ex",
"=",
"scanArtifacts",
"(",
"childProject",
",",
"engine",
",",
"true",
")",
";",
"if",
"(",
"ex",
"!=",
"null",
")",
"{",
"if",
"(",
"exCol",
"==",
"null",
")",
"{",
"exCol",
"=",
"ex",
";",
"}",
"exCol",
".",
"getExceptions",
"(",
")",
".",
"addAll",
"(",
"ex",
".",
"getExceptions",
"(",
")",
")",
";",
"if",
"(",
"ex",
".",
"isFatal",
"(",
")",
")",
"{",
"exCol",
".",
"setFatal",
"(",
"true",
")",
";",
"final",
"String",
"msg",
"=",
"String",
".",
"format",
"(",
"\"Fatal exception(s) analyzing %s\"",
",",
"childProject",
".",
"getName",
"(",
")",
")",
";",
"if",
"(",
"this",
".",
"isFailOnError",
"(",
")",
")",
"{",
"throw",
"new",
"MojoExecutionException",
"(",
"msg",
",",
"exCol",
")",
";",
"}",
"getLog",
"(",
")",
".",
"error",
"(",
"msg",
")",
";",
"if",
"(",
"getLog",
"(",
")",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"getLog",
"(",
")",
".",
"debug",
"(",
"exCol",
")",
";",
"}",
"}",
"}",
"}",
"return",
"exCol",
";",
"}"
] |
Scans the dependencies of the projects in aggregate.
@param engine the engine used to perform the scanning
@return a collection of exceptions
@throws MojoExecutionException thrown if a fatal exception occurs
|
[
"Scans",
"the",
"dependencies",
"of",
"the",
"projects",
"in",
"aggregate",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/maven/src/main/java/org/owasp/dependencycheck/maven/AggregateMojo.java#L65-L89
|
17,922
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/analyzer/ArchiveAnalyzer.java
|
ArchiveAnalyzer.closeAnalyzer
|
@Override
public void closeAnalyzer() throws Exception {
if (tempFileLocation != null && tempFileLocation.exists()) {
LOGGER.debug("Attempting to delete temporary files from `{}`", tempFileLocation.toString());
final boolean success = FileUtils.delete(tempFileLocation);
if (!success && tempFileLocation.exists()) {
final String[] l = tempFileLocation.list();
if (l != null && l.length > 0) {
LOGGER.warn("Failed to delete the Archive Analyzer's temporary files from `{}`, "
+ "see the log for more details", tempFileLocation.toString());
}
}
}
}
|
java
|
@Override
public void closeAnalyzer() throws Exception {
if (tempFileLocation != null && tempFileLocation.exists()) {
LOGGER.debug("Attempting to delete temporary files from `{}`", tempFileLocation.toString());
final boolean success = FileUtils.delete(tempFileLocation);
if (!success && tempFileLocation.exists()) {
final String[] l = tempFileLocation.list();
if (l != null && l.length > 0) {
LOGGER.warn("Failed to delete the Archive Analyzer's temporary files from `{}`, "
+ "see the log for more details", tempFileLocation.toString());
}
}
}
}
|
[
"@",
"Override",
"public",
"void",
"closeAnalyzer",
"(",
")",
"throws",
"Exception",
"{",
"if",
"(",
"tempFileLocation",
"!=",
"null",
"&&",
"tempFileLocation",
".",
"exists",
"(",
")",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"Attempting to delete temporary files from `{}`\"",
",",
"tempFileLocation",
".",
"toString",
"(",
")",
")",
";",
"final",
"boolean",
"success",
"=",
"FileUtils",
".",
"delete",
"(",
"tempFileLocation",
")",
";",
"if",
"(",
"!",
"success",
"&&",
"tempFileLocation",
".",
"exists",
"(",
")",
")",
"{",
"final",
"String",
"[",
"]",
"l",
"=",
"tempFileLocation",
".",
"list",
"(",
")",
";",
"if",
"(",
"l",
"!=",
"null",
"&&",
"l",
".",
"length",
">",
"0",
")",
"{",
"LOGGER",
".",
"warn",
"(",
"\"Failed to delete the Archive Analyzer's temporary files from `{}`, \"",
"+",
"\"see the log for more details\"",
",",
"tempFileLocation",
".",
"toString",
"(",
")",
")",
";",
"}",
"}",
"}",
"}"
] |
The close method deletes any temporary files and directories created
during analysis.
@throws Exception thrown if there is an exception deleting temporary
files
|
[
"The",
"close",
"method",
"deletes",
"any",
"temporary",
"files",
"and",
"directories",
"created",
"during",
"analysis",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/analyzer/ArchiveAnalyzer.java#L207-L220
|
17,923
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/analyzer/ArchiveAnalyzer.java
|
ArchiveAnalyzer.extractAndAnalyze
|
private void extractAndAnalyze(Dependency dependency, Engine engine, int scanDepth) throws AnalysisException {
final File f = new File(dependency.getActualFilePath());
final File tmpDir = getNextTempDirectory();
extractFiles(f, tmpDir, engine);
//make a copy
final List<Dependency> dependencySet = findMoreDependencies(engine, tmpDir);
if (dependencySet != null && !dependencySet.isEmpty()) {
for (Dependency d : dependencySet) {
if (d.getFilePath().startsWith(tmpDir.getAbsolutePath())) {
//fix the dependency's display name and path
final String displayPath = String.format("%s%s",
dependency.getFilePath(),
d.getActualFilePath().substring(tmpDir.getAbsolutePath().length()));
final String displayName = String.format("%s: %s",
dependency.getFileName(),
d.getFileName());
d.setFilePath(displayPath);
d.setFileName(displayName);
d.addAllProjectReferences(dependency.getProjectReferences());
//TODO - can we get more evidence from the parent? EAR contains module name, etc.
//analyze the dependency (i.e. extract files) if it is a supported type.
if (this.accept(d.getActualFile()) && scanDepth < maxScanDepth) {
extractAndAnalyze(d, engine, scanDepth + 1);
}
} else {
dependencySet.stream().filter((sub) -> sub.getFilePath().startsWith(tmpDir.getAbsolutePath())).forEach((sub) -> {
final String displayPath = String.format("%s%s",
dependency.getFilePath(),
sub.getActualFilePath().substring(tmpDir.getAbsolutePath().length()));
final String displayName = String.format("%s: %s",
dependency.getFileName(),
sub.getFileName());
sub.setFilePath(displayPath);
sub.setFileName(displayName);
});
}
}
}
|
java
|
private void extractAndAnalyze(Dependency dependency, Engine engine, int scanDepth) throws AnalysisException {
final File f = new File(dependency.getActualFilePath());
final File tmpDir = getNextTempDirectory();
extractFiles(f, tmpDir, engine);
//make a copy
final List<Dependency> dependencySet = findMoreDependencies(engine, tmpDir);
if (dependencySet != null && !dependencySet.isEmpty()) {
for (Dependency d : dependencySet) {
if (d.getFilePath().startsWith(tmpDir.getAbsolutePath())) {
//fix the dependency's display name and path
final String displayPath = String.format("%s%s",
dependency.getFilePath(),
d.getActualFilePath().substring(tmpDir.getAbsolutePath().length()));
final String displayName = String.format("%s: %s",
dependency.getFileName(),
d.getFileName());
d.setFilePath(displayPath);
d.setFileName(displayName);
d.addAllProjectReferences(dependency.getProjectReferences());
//TODO - can we get more evidence from the parent? EAR contains module name, etc.
//analyze the dependency (i.e. extract files) if it is a supported type.
if (this.accept(d.getActualFile()) && scanDepth < maxScanDepth) {
extractAndAnalyze(d, engine, scanDepth + 1);
}
} else {
dependencySet.stream().filter((sub) -> sub.getFilePath().startsWith(tmpDir.getAbsolutePath())).forEach((sub) -> {
final String displayPath = String.format("%s%s",
dependency.getFilePath(),
sub.getActualFilePath().substring(tmpDir.getAbsolutePath().length()));
final String displayName = String.format("%s: %s",
dependency.getFileName(),
sub.getFileName());
sub.setFilePath(displayPath);
sub.setFileName(displayName);
});
}
}
}
|
[
"private",
"void",
"extractAndAnalyze",
"(",
"Dependency",
"dependency",
",",
"Engine",
"engine",
",",
"int",
"scanDepth",
")",
"throws",
"AnalysisException",
"{",
"final",
"File",
"f",
"=",
"new",
"File",
"(",
"dependency",
".",
"getActualFilePath",
"(",
")",
")",
";",
"final",
"File",
"tmpDir",
"=",
"getNextTempDirectory",
"(",
")",
";",
"extractFiles",
"(",
"f",
",",
"tmpDir",
",",
"engine",
")",
";",
"//make a copy",
"final",
"List",
"<",
"Dependency",
">",
"dependencySet",
"=",
"findMoreDependencies",
"(",
"engine",
",",
"tmpDir",
")",
";",
"if",
"(",
"dependencySet",
"!=",
"null",
"&&",
"!",
"dependencySet",
".",
"isEmpty",
"(",
")",
")",
"{",
"for",
"(",
"Dependency",
"d",
":",
"dependencySet",
")",
"{",
"if",
"(",
"d",
".",
"getFilePath",
"(",
")",
".",
"startsWith",
"(",
"tmpDir",
".",
"getAbsolutePath",
"(",
")",
")",
")",
"{",
"//fix the dependency's display name and path",
"final",
"String",
"displayPath",
"=",
"String",
".",
"format",
"(",
"\"%s%s\"",
",",
"dependency",
".",
"getFilePath",
"(",
")",
",",
"d",
".",
"getActualFilePath",
"(",
")",
".",
"substring",
"(",
"tmpDir",
".",
"getAbsolutePath",
"(",
")",
".",
"length",
"(",
")",
")",
")",
";",
"final",
"String",
"displayName",
"=",
"String",
".",
"format",
"(",
"\"%s: %s\"",
",",
"dependency",
".",
"getFileName",
"(",
")",
",",
"d",
".",
"getFileName",
"(",
")",
")",
";",
"d",
".",
"setFilePath",
"(",
"displayPath",
")",
";",
"d",
".",
"setFileName",
"(",
"displayName",
")",
";",
"d",
".",
"addAllProjectReferences",
"(",
"dependency",
".",
"getProjectReferences",
"(",
")",
")",
";",
"//TODO - can we get more evidence from the parent? EAR contains module name, etc.",
"//analyze the dependency (i.e. extract files) if it is a supported type.",
"if",
"(",
"this",
".",
"accept",
"(",
"d",
".",
"getActualFile",
"(",
")",
")",
"&&",
"scanDepth",
"<",
"maxScanDepth",
")",
"{",
"extractAndAnalyze",
"(",
"d",
",",
"engine",
",",
"scanDepth",
"+",
"1",
")",
";",
"}",
"}",
"else",
"{",
"dependencySet",
".",
"stream",
"(",
")",
".",
"filter",
"(",
"(",
"sub",
")",
"-",
">",
"sub",
".",
"getFilePath",
"(",
")",
".",
"startsWith",
"(",
"tmpDir",
".",
"getAbsolutePath",
"(",
")",
")",
")",
".",
"forEach",
"(",
"(",
"sub",
")",
"-",
">",
"{",
"final",
"String",
"displayPath",
"=",
"String",
".",
"format",
"(",
"\"%s%s\"",
",",
"dependency",
".",
"getFilePath",
"(",
")",
",",
"sub",
".",
"getActualFilePath",
"(",
")",
".",
"substring",
"(",
"tmpDir",
".",
"getAbsolutePath",
"(",
")",
".",
"length",
"(",
")",
")",
")",
"",
";",
"final",
"String",
"displayName",
"=",
"String",
".",
"format",
"(",
"\"%s: %s\"",
",",
"dependency",
".",
"getFileName",
"(",
")",
",",
"sub",
".",
"getFileName",
"(",
")",
")",
";",
"sub",
".",
"setFilePath",
"(",
"displayPath",
")",
";",
"sub",
".",
"setFileName",
"(",
"displayName",
")",
";",
"}",
")",
";",
"}",
"}",
"}"
] |
Extracts the contents of the archive dependency and scans for additional
dependencies.
@param dependency the dependency being analyzed
@param engine the engine doing the analysis
@param scanDepth the current scan depth; extracctAndAnalyze is recursive
and will, be default, only go 3 levels deep
@throws AnalysisException thrown if there is a problem analyzing the
dependencies
|
[
"Extracts",
"the",
"contents",
"of",
"the",
"archive",
"dependency",
"and",
"scans",
"for",
"additional",
"dependencies",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/analyzer/ArchiveAnalyzer.java#L248-L288
|
17,924
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/analyzer/PythonDistributionAnalyzer.java
|
PythonDistributionAnalyzer.collectMetadataFromArchiveFormat
|
private void collectMetadataFromArchiveFormat(Dependency dependency,
FilenameFilter folderFilter, FilenameFilter metadataFilter)
throws AnalysisException {
final File temp = getNextTempDirectory();
LOGGER.debug("{} exists? {}", temp, temp.exists());
try {
ExtractionUtil.extractFilesUsingFilter(
new File(dependency.getActualFilePath()), temp,
metadataFilter);
} catch (ExtractionException ex) {
throw new AnalysisException(ex);
}
File matchingFile = getMatchingFile(temp, folderFilter);
if (matchingFile != null) {
matchingFile = getMatchingFile(matchingFile, metadataFilter);
if (matchingFile != null) {
collectWheelMetadata(dependency, matchingFile);
}
}
}
|
java
|
private void collectMetadataFromArchiveFormat(Dependency dependency,
FilenameFilter folderFilter, FilenameFilter metadataFilter)
throws AnalysisException {
final File temp = getNextTempDirectory();
LOGGER.debug("{} exists? {}", temp, temp.exists());
try {
ExtractionUtil.extractFilesUsingFilter(
new File(dependency.getActualFilePath()), temp,
metadataFilter);
} catch (ExtractionException ex) {
throw new AnalysisException(ex);
}
File matchingFile = getMatchingFile(temp, folderFilter);
if (matchingFile != null) {
matchingFile = getMatchingFile(matchingFile, metadataFilter);
if (matchingFile != null) {
collectWheelMetadata(dependency, matchingFile);
}
}
}
|
[
"private",
"void",
"collectMetadataFromArchiveFormat",
"(",
"Dependency",
"dependency",
",",
"FilenameFilter",
"folderFilter",
",",
"FilenameFilter",
"metadataFilter",
")",
"throws",
"AnalysisException",
"{",
"final",
"File",
"temp",
"=",
"getNextTempDirectory",
"(",
")",
";",
"LOGGER",
".",
"debug",
"(",
"\"{} exists? {}\"",
",",
"temp",
",",
"temp",
".",
"exists",
"(",
")",
")",
";",
"try",
"{",
"ExtractionUtil",
".",
"extractFilesUsingFilter",
"(",
"new",
"File",
"(",
"dependency",
".",
"getActualFilePath",
"(",
")",
")",
",",
"temp",
",",
"metadataFilter",
")",
";",
"}",
"catch",
"(",
"ExtractionException",
"ex",
")",
"{",
"throw",
"new",
"AnalysisException",
"(",
"ex",
")",
";",
"}",
"File",
"matchingFile",
"=",
"getMatchingFile",
"(",
"temp",
",",
"folderFilter",
")",
";",
"if",
"(",
"matchingFile",
"!=",
"null",
")",
"{",
"matchingFile",
"=",
"getMatchingFile",
"(",
"matchingFile",
",",
"metadataFilter",
")",
";",
"if",
"(",
"matchingFile",
"!=",
"null",
")",
"{",
"collectWheelMetadata",
"(",
"dependency",
",",
"matchingFile",
")",
";",
"}",
"}",
"}"
] |
Collects the meta data from an archive.
@param dependency the archive being scanned
@param folderFilter the filter to apply to the folder
@param metadataFilter the filter to apply to the meta data
@throws AnalysisException thrown when there is a problem analyzing the
dependency
|
[
"Collects",
"the",
"meta",
"data",
"from",
"an",
"archive",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/analyzer/PythonDistributionAnalyzer.java#L215-L235
|
17,925
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/analyzer/PythonDistributionAnalyzer.java
|
PythonDistributionAnalyzer.prepareFileTypeAnalyzer
|
@Override
protected void prepareFileTypeAnalyzer(Engine engine) throws InitializationException {
try {
final File baseDir = getSettings().getTempDirectory();
tempFileLocation = File.createTempFile("check", "tmp", baseDir);
if (!tempFileLocation.delete()) {
setEnabled(false);
final String msg = String.format(
"Unable to delete temporary file '%s'.",
tempFileLocation.getAbsolutePath());
throw new InitializationException(msg);
}
if (!tempFileLocation.mkdirs()) {
setEnabled(false);
final String msg = String.format(
"Unable to create directory '%s'.",
tempFileLocation.getAbsolutePath());
throw new InitializationException(msg);
}
} catch (IOException ex) {
setEnabled(false);
throw new InitializationException("Unable to create a temporary file", ex);
}
}
|
java
|
@Override
protected void prepareFileTypeAnalyzer(Engine engine) throws InitializationException {
try {
final File baseDir = getSettings().getTempDirectory();
tempFileLocation = File.createTempFile("check", "tmp", baseDir);
if (!tempFileLocation.delete()) {
setEnabled(false);
final String msg = String.format(
"Unable to delete temporary file '%s'.",
tempFileLocation.getAbsolutePath());
throw new InitializationException(msg);
}
if (!tempFileLocation.mkdirs()) {
setEnabled(false);
final String msg = String.format(
"Unable to create directory '%s'.",
tempFileLocation.getAbsolutePath());
throw new InitializationException(msg);
}
} catch (IOException ex) {
setEnabled(false);
throw new InitializationException("Unable to create a temporary file", ex);
}
}
|
[
"@",
"Override",
"protected",
"void",
"prepareFileTypeAnalyzer",
"(",
"Engine",
"engine",
")",
"throws",
"InitializationException",
"{",
"try",
"{",
"final",
"File",
"baseDir",
"=",
"getSettings",
"(",
")",
".",
"getTempDirectory",
"(",
")",
";",
"tempFileLocation",
"=",
"File",
".",
"createTempFile",
"(",
"\"check\"",
",",
"\"tmp\"",
",",
"baseDir",
")",
";",
"if",
"(",
"!",
"tempFileLocation",
".",
"delete",
"(",
")",
")",
"{",
"setEnabled",
"(",
"false",
")",
";",
"final",
"String",
"msg",
"=",
"String",
".",
"format",
"(",
"\"Unable to delete temporary file '%s'.\"",
",",
"tempFileLocation",
".",
"getAbsolutePath",
"(",
")",
")",
";",
"throw",
"new",
"InitializationException",
"(",
"msg",
")",
";",
"}",
"if",
"(",
"!",
"tempFileLocation",
".",
"mkdirs",
"(",
")",
")",
"{",
"setEnabled",
"(",
"false",
")",
";",
"final",
"String",
"msg",
"=",
"String",
".",
"format",
"(",
"\"Unable to create directory '%s'.\"",
",",
"tempFileLocation",
".",
"getAbsolutePath",
"(",
")",
")",
";",
"throw",
"new",
"InitializationException",
"(",
"msg",
")",
";",
"}",
"}",
"catch",
"(",
"IOException",
"ex",
")",
"{",
"setEnabled",
"(",
"false",
")",
";",
"throw",
"new",
"InitializationException",
"(",
"\"Unable to create a temporary file\"",
",",
"ex",
")",
";",
"}",
"}"
] |
Makes sure a usable temporary directory is available.
@param engine a reference to the dependency-check engine
@throws InitializationException an AnalyzeException is thrown when the
temp directory cannot be created
|
[
"Makes",
"sure",
"a",
"usable",
"temporary",
"directory",
"is",
"available",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/analyzer/PythonDistributionAnalyzer.java#L244-L267
|
17,926
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/analyzer/PythonDistributionAnalyzer.java
|
PythonDistributionAnalyzer.collectWheelMetadata
|
private static void collectWheelMetadata(Dependency dependency, File file) {
final InternetHeaders headers = getManifestProperties(file);
addPropertyToEvidence(dependency, EvidenceType.VERSION, Confidence.HIGHEST, headers, "Version");
addPropertyToEvidence(dependency, EvidenceType.PRODUCT, Confidence.HIGHEST, headers, "Name");
addPropertyToEvidence(dependency, EvidenceType.PRODUCT, Confidence.MEDIUM, headers, "Name");
final String name = headers.getHeader("Name", null);
final String version = headers.getHeader("Version", null);
final String packagePath = String.format("%s:%s", name, version);
dependency.setName(name);
dependency.setVersion(version);
dependency.setPackagePath(packagePath);
dependency.setDisplayFileName(packagePath);
final String url = headers.getHeader("Home-page", null);
if (StringUtils.isNotBlank(url)) {
if (UrlStringUtils.isUrl(url)) {
dependency.addEvidence(EvidenceType.VENDOR, METADATA, "vendor", url, Confidence.MEDIUM);
}
}
addPropertyToEvidence(dependency, EvidenceType.VENDOR, Confidence.LOW, headers, "Author");
final String summary = headers.getHeader("Summary", null);
if (StringUtils.isNotBlank(summary)) {
JarAnalyzer.addDescription(dependency, summary, METADATA, "summary");
}
try {
final PackageURL purl = PackageURLBuilder.aPackageURL().withType("pypi")
.withName(name).withVersion(version).build();
dependency.addSoftwareIdentifier(new PurlIdentifier(purl, Confidence.HIGHEST));
} catch (MalformedPackageURLException ex) {
LOGGER.debug("Unable to build package url for python", ex);
final GenericIdentifier id = new GenericIdentifier("generic:" + name + "@" + version, Confidence.HIGHEST);
dependency.addSoftwareIdentifier(id);
}
}
|
java
|
private static void collectWheelMetadata(Dependency dependency, File file) {
final InternetHeaders headers = getManifestProperties(file);
addPropertyToEvidence(dependency, EvidenceType.VERSION, Confidence.HIGHEST, headers, "Version");
addPropertyToEvidence(dependency, EvidenceType.PRODUCT, Confidence.HIGHEST, headers, "Name");
addPropertyToEvidence(dependency, EvidenceType.PRODUCT, Confidence.MEDIUM, headers, "Name");
final String name = headers.getHeader("Name", null);
final String version = headers.getHeader("Version", null);
final String packagePath = String.format("%s:%s", name, version);
dependency.setName(name);
dependency.setVersion(version);
dependency.setPackagePath(packagePath);
dependency.setDisplayFileName(packagePath);
final String url = headers.getHeader("Home-page", null);
if (StringUtils.isNotBlank(url)) {
if (UrlStringUtils.isUrl(url)) {
dependency.addEvidence(EvidenceType.VENDOR, METADATA, "vendor", url, Confidence.MEDIUM);
}
}
addPropertyToEvidence(dependency, EvidenceType.VENDOR, Confidence.LOW, headers, "Author");
final String summary = headers.getHeader("Summary", null);
if (StringUtils.isNotBlank(summary)) {
JarAnalyzer.addDescription(dependency, summary, METADATA, "summary");
}
try {
final PackageURL purl = PackageURLBuilder.aPackageURL().withType("pypi")
.withName(name).withVersion(version).build();
dependency.addSoftwareIdentifier(new PurlIdentifier(purl, Confidence.HIGHEST));
} catch (MalformedPackageURLException ex) {
LOGGER.debug("Unable to build package url for python", ex);
final GenericIdentifier id = new GenericIdentifier("generic:" + name + "@" + version, Confidence.HIGHEST);
dependency.addSoftwareIdentifier(id);
}
}
|
[
"private",
"static",
"void",
"collectWheelMetadata",
"(",
"Dependency",
"dependency",
",",
"File",
"file",
")",
"{",
"final",
"InternetHeaders",
"headers",
"=",
"getManifestProperties",
"(",
"file",
")",
";",
"addPropertyToEvidence",
"(",
"dependency",
",",
"EvidenceType",
".",
"VERSION",
",",
"Confidence",
".",
"HIGHEST",
",",
"headers",
",",
"\"Version\"",
")",
";",
"addPropertyToEvidence",
"(",
"dependency",
",",
"EvidenceType",
".",
"PRODUCT",
",",
"Confidence",
".",
"HIGHEST",
",",
"headers",
",",
"\"Name\"",
")",
";",
"addPropertyToEvidence",
"(",
"dependency",
",",
"EvidenceType",
".",
"PRODUCT",
",",
"Confidence",
".",
"MEDIUM",
",",
"headers",
",",
"\"Name\"",
")",
";",
"final",
"String",
"name",
"=",
"headers",
".",
"getHeader",
"(",
"\"Name\"",
",",
"null",
")",
";",
"final",
"String",
"version",
"=",
"headers",
".",
"getHeader",
"(",
"\"Version\"",
",",
"null",
")",
";",
"final",
"String",
"packagePath",
"=",
"String",
".",
"format",
"(",
"\"%s:%s\"",
",",
"name",
",",
"version",
")",
";",
"dependency",
".",
"setName",
"(",
"name",
")",
";",
"dependency",
".",
"setVersion",
"(",
"version",
")",
";",
"dependency",
".",
"setPackagePath",
"(",
"packagePath",
")",
";",
"dependency",
".",
"setDisplayFileName",
"(",
"packagePath",
")",
";",
"final",
"String",
"url",
"=",
"headers",
".",
"getHeader",
"(",
"\"Home-page\"",
",",
"null",
")",
";",
"if",
"(",
"StringUtils",
".",
"isNotBlank",
"(",
"url",
")",
")",
"{",
"if",
"(",
"UrlStringUtils",
".",
"isUrl",
"(",
"url",
")",
")",
"{",
"dependency",
".",
"addEvidence",
"(",
"EvidenceType",
".",
"VENDOR",
",",
"METADATA",
",",
"\"vendor\"",
",",
"url",
",",
"Confidence",
".",
"MEDIUM",
")",
";",
"}",
"}",
"addPropertyToEvidence",
"(",
"dependency",
",",
"EvidenceType",
".",
"VENDOR",
",",
"Confidence",
".",
"LOW",
",",
"headers",
",",
"\"Author\"",
")",
";",
"final",
"String",
"summary",
"=",
"headers",
".",
"getHeader",
"(",
"\"Summary\"",
",",
"null",
")",
";",
"if",
"(",
"StringUtils",
".",
"isNotBlank",
"(",
"summary",
")",
")",
"{",
"JarAnalyzer",
".",
"addDescription",
"(",
"dependency",
",",
"summary",
",",
"METADATA",
",",
"\"summary\"",
")",
";",
"}",
"try",
"{",
"final",
"PackageURL",
"purl",
"=",
"PackageURLBuilder",
".",
"aPackageURL",
"(",
")",
".",
"withType",
"(",
"\"pypi\"",
")",
".",
"withName",
"(",
"name",
")",
".",
"withVersion",
"(",
"version",
")",
".",
"build",
"(",
")",
";",
"dependency",
".",
"addSoftwareIdentifier",
"(",
"new",
"PurlIdentifier",
"(",
"purl",
",",
"Confidence",
".",
"HIGHEST",
")",
")",
";",
"}",
"catch",
"(",
"MalformedPackageURLException",
"ex",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"Unable to build package url for python\"",
",",
"ex",
")",
";",
"final",
"GenericIdentifier",
"id",
"=",
"new",
"GenericIdentifier",
"(",
"\"generic:\"",
"+",
"name",
"+",
"\"@\"",
"+",
"version",
",",
"Confidence",
".",
"HIGHEST",
")",
";",
"dependency",
".",
"addSoftwareIdentifier",
"(",
"id",
")",
";",
"}",
"}"
] |
Gathers evidence from the METADATA file.
@param dependency the dependency being analyzed
@param file a reference to the manifest/properties file
|
[
"Gathers",
"evidence",
"from",
"the",
"METADATA",
"file",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/analyzer/PythonDistributionAnalyzer.java#L292-L326
|
17,927
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/analyzer/PythonDistributionAnalyzer.java
|
PythonDistributionAnalyzer.addPropertyToEvidence
|
private static void addPropertyToEvidence(Dependency dependency, EvidenceType type, Confidence confidence,
InternetHeaders headers, String property) {
final String value = headers.getHeader(property, null);
LOGGER.debug("Property: {}, Value: {}", property, value);
if (StringUtils.isNotBlank(value)) {
dependency.addEvidence(type, METADATA, property, value, confidence);
}
}
|
java
|
private static void addPropertyToEvidence(Dependency dependency, EvidenceType type, Confidence confidence,
InternetHeaders headers, String property) {
final String value = headers.getHeader(property, null);
LOGGER.debug("Property: {}, Value: {}", property, value);
if (StringUtils.isNotBlank(value)) {
dependency.addEvidence(type, METADATA, property, value, confidence);
}
}
|
[
"private",
"static",
"void",
"addPropertyToEvidence",
"(",
"Dependency",
"dependency",
",",
"EvidenceType",
"type",
",",
"Confidence",
"confidence",
",",
"InternetHeaders",
"headers",
",",
"String",
"property",
")",
"{",
"final",
"String",
"value",
"=",
"headers",
".",
"getHeader",
"(",
"property",
",",
"null",
")",
";",
"LOGGER",
".",
"debug",
"(",
"\"Property: {}, Value: {}\"",
",",
"property",
",",
"value",
")",
";",
"if",
"(",
"StringUtils",
".",
"isNotBlank",
"(",
"value",
")",
")",
"{",
"dependency",
".",
"addEvidence",
"(",
"type",
",",
"METADATA",
",",
"property",
",",
"value",
",",
"confidence",
")",
";",
"}",
"}"
] |
Adds a value to the evidence collection.
@param dependency the dependency being analyzed
@param type the type of evidence to add
@param confidence the confidence in the evidence being added
@param headers the properties collection
@param property the property name
|
[
"Adds",
"a",
"value",
"to",
"the",
"evidence",
"collection",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/analyzer/PythonDistributionAnalyzer.java#L337-L344
|
17,928
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/analyzer/PythonDistributionAnalyzer.java
|
PythonDistributionAnalyzer.getMatchingFile
|
private static File getMatchingFile(File folder, FilenameFilter filter) {
File result = null;
final File[] matches = folder.listFiles(filter);
if (null != matches && 1 == matches.length) {
result = matches[0];
}
return result;
}
|
java
|
private static File getMatchingFile(File folder, FilenameFilter filter) {
File result = null;
final File[] matches = folder.listFiles(filter);
if (null != matches && 1 == matches.length) {
result = matches[0];
}
return result;
}
|
[
"private",
"static",
"File",
"getMatchingFile",
"(",
"File",
"folder",
",",
"FilenameFilter",
"filter",
")",
"{",
"File",
"result",
"=",
"null",
";",
"final",
"File",
"[",
"]",
"matches",
"=",
"folder",
".",
"listFiles",
"(",
"filter",
")",
";",
"if",
"(",
"null",
"!=",
"matches",
"&&",
"1",
"==",
"matches",
".",
"length",
")",
"{",
"result",
"=",
"matches",
"[",
"0",
"]",
";",
"}",
"return",
"result",
";",
"}"
] |
Returns a list of files that match the given filter, this does not
recursively scan the directory.
@param folder the folder to filter
@param filter the filter to apply to the files in the directory
@return the list of Files in the directory that match the provided filter
|
[
"Returns",
"a",
"list",
"of",
"files",
"that",
"match",
"the",
"given",
"filter",
"this",
"does",
"not",
"recursively",
"scan",
"the",
"directory",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/analyzer/PythonDistributionAnalyzer.java#L354-L361
|
17,929
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/analyzer/PythonDistributionAnalyzer.java
|
PythonDistributionAnalyzer.getManifestProperties
|
private static InternetHeaders getManifestProperties(File manifest) {
final InternetHeaders result = new InternetHeaders();
if (null == manifest) {
LOGGER.debug("Manifest file not found.");
} else {
try (InputStream in = new BufferedInputStream(new FileInputStream(manifest))) {
result.load(in);
} catch (MessagingException | FileNotFoundException e) {
LOGGER.warn(e.getMessage(), e);
} catch (IOException ex) {
LOGGER.warn(ex.getMessage(), ex);
}
}
return result;
}
|
java
|
private static InternetHeaders getManifestProperties(File manifest) {
final InternetHeaders result = new InternetHeaders();
if (null == manifest) {
LOGGER.debug("Manifest file not found.");
} else {
try (InputStream in = new BufferedInputStream(new FileInputStream(manifest))) {
result.load(in);
} catch (MessagingException | FileNotFoundException e) {
LOGGER.warn(e.getMessage(), e);
} catch (IOException ex) {
LOGGER.warn(ex.getMessage(), ex);
}
}
return result;
}
|
[
"private",
"static",
"InternetHeaders",
"getManifestProperties",
"(",
"File",
"manifest",
")",
"{",
"final",
"InternetHeaders",
"result",
"=",
"new",
"InternetHeaders",
"(",
")",
";",
"if",
"(",
"null",
"==",
"manifest",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"Manifest file not found.\"",
")",
";",
"}",
"else",
"{",
"try",
"(",
"InputStream",
"in",
"=",
"new",
"BufferedInputStream",
"(",
"new",
"FileInputStream",
"(",
"manifest",
")",
")",
")",
"{",
"result",
".",
"load",
"(",
"in",
")",
";",
"}",
"catch",
"(",
"MessagingException",
"|",
"FileNotFoundException",
"e",
")",
"{",
"LOGGER",
".",
"warn",
"(",
"e",
".",
"getMessage",
"(",
")",
",",
"e",
")",
";",
"}",
"catch",
"(",
"IOException",
"ex",
")",
"{",
"LOGGER",
".",
"warn",
"(",
"ex",
".",
"getMessage",
"(",
")",
",",
"ex",
")",
";",
"}",
"}",
"return",
"result",
";",
"}"
] |
Reads the manifest entries from the provided file.
@param manifest the manifest
@return the manifest entries
|
[
"Reads",
"the",
"manifest",
"entries",
"from",
"the",
"provided",
"file",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/analyzer/PythonDistributionAnalyzer.java#L369-L383
|
17,930
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/analyzer/PythonDistributionAnalyzer.java
|
PythonDistributionAnalyzer.getNextTempDirectory
|
private File getNextTempDirectory() throws AnalysisException {
File directory;
// getting an exception for some directories not being able to be
// created; might be because the directory already exists?
do {
final int dirCount = DIR_COUNT.incrementAndGet();
directory = new File(tempFileLocation, String.valueOf(dirCount));
} while (directory.exists());
if (!directory.mkdirs()) {
throw new AnalysisException(String.format(
"Unable to create temp directory '%s'.",
directory.getAbsolutePath()));
}
return directory;
}
|
java
|
private File getNextTempDirectory() throws AnalysisException {
File directory;
// getting an exception for some directories not being able to be
// created; might be because the directory already exists?
do {
final int dirCount = DIR_COUNT.incrementAndGet();
directory = new File(tempFileLocation, String.valueOf(dirCount));
} while (directory.exists());
if (!directory.mkdirs()) {
throw new AnalysisException(String.format(
"Unable to create temp directory '%s'.",
directory.getAbsolutePath()));
}
return directory;
}
|
[
"private",
"File",
"getNextTempDirectory",
"(",
")",
"throws",
"AnalysisException",
"{",
"File",
"directory",
";",
"// getting an exception for some directories not being able to be",
"// created; might be because the directory already exists?",
"do",
"{",
"final",
"int",
"dirCount",
"=",
"DIR_COUNT",
".",
"incrementAndGet",
"(",
")",
";",
"directory",
"=",
"new",
"File",
"(",
"tempFileLocation",
",",
"String",
".",
"valueOf",
"(",
"dirCount",
")",
")",
";",
"}",
"while",
"(",
"directory",
".",
"exists",
"(",
")",
")",
";",
"if",
"(",
"!",
"directory",
".",
"mkdirs",
"(",
")",
")",
"{",
"throw",
"new",
"AnalysisException",
"(",
"String",
".",
"format",
"(",
"\"Unable to create temp directory '%s'.\"",
",",
"directory",
".",
"getAbsolutePath",
"(",
")",
")",
")",
";",
"}",
"return",
"directory",
";",
"}"
] |
Retrieves the next temporary destination directory for extracting an
archive.
@return a directory
@throws AnalysisException thrown if unable to create temporary directory
|
[
"Retrieves",
"the",
"next",
"temporary",
"destination",
"directory",
"for",
"extracting",
"an",
"archive",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/analyzer/PythonDistributionAnalyzer.java#L392-L407
|
17,931
|
jeremylong/DependencyCheck
|
ant/src/main/java/org/owasp/dependencycheck/taskdefs/Purge.java
|
Purge.execute
|
@Override
public void execute() throws BuildException {
populateSettings();
final File db;
try {
db = new File(getSettings().getDataDirectory(), getSettings().getString(Settings.KEYS.DB_FILE_NAME, "odc.mv.db"));
if (db.exists()) {
if (db.delete()) {
log("Database file purged; local copy of the NVD has been removed", Project.MSG_INFO);
} else {
final String msg = String.format("Unable to delete '%s'; please delete the file manually", db.getAbsolutePath());
if (this.failOnError) {
throw new BuildException(msg);
}
log(msg, Project.MSG_ERR);
}
} else {
final String msg = String.format("Unable to purge database; the database file does not exist: %s", db.getAbsolutePath());
if (this.failOnError) {
throw new BuildException(msg);
}
log(msg, Project.MSG_ERR);
}
} catch (IOException ex) {
final String msg = "Unable to delete the database";
if (this.failOnError) {
throw new BuildException(msg);
}
log(msg, Project.MSG_ERR);
} finally {
settings.cleanup(true);
}
}
|
java
|
@Override
public void execute() throws BuildException {
populateSettings();
final File db;
try {
db = new File(getSettings().getDataDirectory(), getSettings().getString(Settings.KEYS.DB_FILE_NAME, "odc.mv.db"));
if (db.exists()) {
if (db.delete()) {
log("Database file purged; local copy of the NVD has been removed", Project.MSG_INFO);
} else {
final String msg = String.format("Unable to delete '%s'; please delete the file manually", db.getAbsolutePath());
if (this.failOnError) {
throw new BuildException(msg);
}
log(msg, Project.MSG_ERR);
}
} else {
final String msg = String.format("Unable to purge database; the database file does not exist: %s", db.getAbsolutePath());
if (this.failOnError) {
throw new BuildException(msg);
}
log(msg, Project.MSG_ERR);
}
} catch (IOException ex) {
final String msg = "Unable to delete the database";
if (this.failOnError) {
throw new BuildException(msg);
}
log(msg, Project.MSG_ERR);
} finally {
settings.cleanup(true);
}
}
|
[
"@",
"Override",
"public",
"void",
"execute",
"(",
")",
"throws",
"BuildException",
"{",
"populateSettings",
"(",
")",
";",
"final",
"File",
"db",
";",
"try",
"{",
"db",
"=",
"new",
"File",
"(",
"getSettings",
"(",
")",
".",
"getDataDirectory",
"(",
")",
",",
"getSettings",
"(",
")",
".",
"getString",
"(",
"Settings",
".",
"KEYS",
".",
"DB_FILE_NAME",
",",
"\"odc.mv.db\"",
")",
")",
";",
"if",
"(",
"db",
".",
"exists",
"(",
")",
")",
"{",
"if",
"(",
"db",
".",
"delete",
"(",
")",
")",
"{",
"log",
"(",
"\"Database file purged; local copy of the NVD has been removed\"",
",",
"Project",
".",
"MSG_INFO",
")",
";",
"}",
"else",
"{",
"final",
"String",
"msg",
"=",
"String",
".",
"format",
"(",
"\"Unable to delete '%s'; please delete the file manually\"",
",",
"db",
".",
"getAbsolutePath",
"(",
")",
")",
";",
"if",
"(",
"this",
".",
"failOnError",
")",
"{",
"throw",
"new",
"BuildException",
"(",
"msg",
")",
";",
"}",
"log",
"(",
"msg",
",",
"Project",
".",
"MSG_ERR",
")",
";",
"}",
"}",
"else",
"{",
"final",
"String",
"msg",
"=",
"String",
".",
"format",
"(",
"\"Unable to purge database; the database file does not exist: %s\"",
",",
"db",
".",
"getAbsolutePath",
"(",
")",
")",
";",
"if",
"(",
"this",
".",
"failOnError",
")",
"{",
"throw",
"new",
"BuildException",
"(",
"msg",
")",
";",
"}",
"log",
"(",
"msg",
",",
"Project",
".",
"MSG_ERR",
")",
";",
"}",
"}",
"catch",
"(",
"IOException",
"ex",
")",
"{",
"final",
"String",
"msg",
"=",
"\"Unable to delete the database\"",
";",
"if",
"(",
"this",
".",
"failOnError",
")",
"{",
"throw",
"new",
"BuildException",
"(",
"msg",
")",
";",
"}",
"log",
"(",
"msg",
",",
"Project",
".",
"MSG_ERR",
")",
";",
"}",
"finally",
"{",
"settings",
".",
"cleanup",
"(",
"true",
")",
";",
"}",
"}"
] |
Executes the dependency-check purge to delete the existing local copy of
the NVD CVE data.
@throws BuildException thrown if there is a problem deleting the file(s)
|
[
"Executes",
"the",
"dependency",
"-",
"check",
"purge",
"to",
"delete",
"the",
"existing",
"local",
"copy",
"of",
"the",
"NVD",
"CVE",
"data",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/ant/src/main/java/org/owasp/dependencycheck/taskdefs/Purge.java#L112-L144
|
17,932
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/xml/suppression/PropertyType.java
|
PropertyType.matches
|
public boolean matches(String text) {
if (text == null) {
return false;
}
if (this.regex) {
final Pattern rx;
if (this.caseSensitive) {
rx = Pattern.compile(this.value);
} else {
rx = Pattern.compile(this.value, Pattern.CASE_INSENSITIVE);
}
return rx.matcher(text).matches();
} else {
if (this.caseSensitive) {
return value.equals(text);
} else {
return value.equalsIgnoreCase(text);
}
}
}
|
java
|
public boolean matches(String text) {
if (text == null) {
return false;
}
if (this.regex) {
final Pattern rx;
if (this.caseSensitive) {
rx = Pattern.compile(this.value);
} else {
rx = Pattern.compile(this.value, Pattern.CASE_INSENSITIVE);
}
return rx.matcher(text).matches();
} else {
if (this.caseSensitive) {
return value.equals(text);
} else {
return value.equalsIgnoreCase(text);
}
}
}
|
[
"public",
"boolean",
"matches",
"(",
"String",
"text",
")",
"{",
"if",
"(",
"text",
"==",
"null",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"this",
".",
"regex",
")",
"{",
"final",
"Pattern",
"rx",
";",
"if",
"(",
"this",
".",
"caseSensitive",
")",
"{",
"rx",
"=",
"Pattern",
".",
"compile",
"(",
"this",
".",
"value",
")",
";",
"}",
"else",
"{",
"rx",
"=",
"Pattern",
".",
"compile",
"(",
"this",
".",
"value",
",",
"Pattern",
".",
"CASE_INSENSITIVE",
")",
";",
"}",
"return",
"rx",
".",
"matcher",
"(",
"text",
")",
".",
"matches",
"(",
")",
";",
"}",
"else",
"{",
"if",
"(",
"this",
".",
"caseSensitive",
")",
"{",
"return",
"value",
".",
"equals",
"(",
"text",
")",
";",
"}",
"else",
"{",
"return",
"value",
".",
"equalsIgnoreCase",
"(",
"text",
")",
";",
"}",
"}",
"}"
] |
Uses the object's properties to determine if the supplied string matches
the value of this property.
@param text the String to validate
@return whether the text supplied is matched by the value of the property
|
[
"Uses",
"the",
"object",
"s",
"properties",
"to",
"determine",
"if",
"the",
"supplied",
"string",
"matches",
"the",
"value",
"of",
"this",
"property",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/xml/suppression/PropertyType.java#L114-L133
|
17,933
|
jeremylong/DependencyCheck
|
ant/src/main/java/org/owasp/dependencycheck/taskdefs/Check.java
|
Check.getPath
|
private synchronized Resources getPath() {
if (path == null) {
path = new Resources(getProject());
path.setCache(true);
}
return path;
}
|
java
|
private synchronized Resources getPath() {
if (path == null) {
path = new Resources(getProject());
path.setCache(true);
}
return path;
}
|
[
"private",
"synchronized",
"Resources",
"getPath",
"(",
")",
"{",
"if",
"(",
"path",
"==",
"null",
")",
"{",
"path",
"=",
"new",
"Resources",
"(",
"getProject",
"(",
")",
")",
";",
"path",
".",
"setCache",
"(",
"true",
")",
";",
"}",
"return",
"path",
";",
"}"
] |
Returns the path. If the path has not been initialized yet, this class is
synchronized, and will instantiate the path object.
@return the path
|
[
"Returns",
"the",
"path",
".",
"If",
"the",
"path",
"has",
"not",
"been",
"initialized",
"yet",
"this",
"class",
"is",
"synchronized",
"and",
"will",
"instantiate",
"the",
"path",
"object",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/ant/src/main/java/org/owasp/dependencycheck/taskdefs/Check.java#L313-L319
|
17,934
|
jeremylong/DependencyCheck
|
ant/src/main/java/org/owasp/dependencycheck/taskdefs/Check.java
|
Check.dealWithReferences
|
private void dealWithReferences() throws BuildException {
if (isReference()) {
final Object o = refId.getReferencedObject(getProject());
if (!(o instanceof ResourceCollection)) {
throw new BuildException("refId '" + refId.getRefId()
+ "' does not refer to a resource collection.");
}
getPath().add((ResourceCollection) o);
}
}
|
java
|
private void dealWithReferences() throws BuildException {
if (isReference()) {
final Object o = refId.getReferencedObject(getProject());
if (!(o instanceof ResourceCollection)) {
throw new BuildException("refId '" + refId.getRefId()
+ "' does not refer to a resource collection.");
}
getPath().add((ResourceCollection) o);
}
}
|
[
"private",
"void",
"dealWithReferences",
"(",
")",
"throws",
"BuildException",
"{",
"if",
"(",
"isReference",
"(",
")",
")",
"{",
"final",
"Object",
"o",
"=",
"refId",
".",
"getReferencedObject",
"(",
"getProject",
"(",
")",
")",
";",
"if",
"(",
"!",
"(",
"o",
"instanceof",
"ResourceCollection",
")",
")",
"{",
"throw",
"new",
"BuildException",
"(",
"\"refId '\"",
"+",
"refId",
".",
"getRefId",
"(",
")",
"+",
"\"' does not refer to a resource collection.\"",
")",
";",
"}",
"getPath",
"(",
")",
".",
"add",
"(",
"(",
"ResourceCollection",
")",
"o",
")",
";",
"}",
"}"
] |
If this is a reference, this method will add the referenced resource
collection to the collection of paths.
@throws BuildException if the reference is not to a resource collection
|
[
"If",
"this",
"is",
"a",
"reference",
"this",
"method",
"will",
"add",
"the",
"referenced",
"resource",
"collection",
"to",
"the",
"collection",
"of",
"paths",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/ant/src/main/java/org/owasp/dependencycheck/taskdefs/Check.java#L349-L358
|
17,935
|
jeremylong/DependencyCheck
|
ant/src/main/java/org/owasp/dependencycheck/taskdefs/Check.java
|
Check.setNspAnalyzerEnabled
|
@Deprecated
public void setNspAnalyzerEnabled(Boolean nodeAnalyzerEnabled) {
log("The NspAnalyzerEnabled configuration has been deprecated and replaced by NodeAuditAnalyzerEnabled", Project.MSG_ERR);
log("The NspAnalyzerEnabled configuration will be removed in the next major release");
this.nodeAnalyzerEnabled = nodeAnalyzerEnabled;
}
|
java
|
@Deprecated
public void setNspAnalyzerEnabled(Boolean nodeAnalyzerEnabled) {
log("The NspAnalyzerEnabled configuration has been deprecated and replaced by NodeAuditAnalyzerEnabled", Project.MSG_ERR);
log("The NspAnalyzerEnabled configuration will be removed in the next major release");
this.nodeAnalyzerEnabled = nodeAnalyzerEnabled;
}
|
[
"@",
"Deprecated",
"public",
"void",
"setNspAnalyzerEnabled",
"(",
"Boolean",
"nodeAnalyzerEnabled",
")",
"{",
"log",
"(",
"\"The NspAnalyzerEnabled configuration has been deprecated and replaced by NodeAuditAnalyzerEnabled\"",
",",
"Project",
".",
"MSG_ERR",
")",
";",
"log",
"(",
"\"The NspAnalyzerEnabled configuration will be removed in the next major release\"",
")",
";",
"this",
".",
"nodeAnalyzerEnabled",
"=",
"nodeAnalyzerEnabled",
";",
"}"
] |
Set the value of nodeAnalyzerEnabled.
@param nodeAnalyzerEnabled new value of nodeAnalyzerEnabled
@deprecated As of release 3.3.3, replaced by
{@link #setNodeAuditAnalyzerEnabled(java.lang.Boolean)}
|
[
"Set",
"the",
"value",
"of",
"nodeAnalyzerEnabled",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/ant/src/main/java/org/owasp/dependencycheck/taskdefs/Check.java#L831-L836
|
17,936
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/utils/H2DBLock.java
|
H2DBLock.lock
|
public void lock() throws H2DBLockException {
try {
final File dir = settings.getDataDirectory();
lockFile = new File(dir, "odc.update.lock");
checkState();
int ctr = 0;
do {
try {
if (!lockFile.exists() && lockFile.createNewFile()) {
file = new RandomAccessFile(lockFile, "rw");
lock = file.getChannel().lock();
file.writeBytes(magic);
file.getChannel().force(true);
Thread.sleep(20);
file.seek(0);
final String current = file.readLine();
if (current != null && !current.equals(magic)) {
lock.close();
lock = null;
LOGGER.debug("Another process obtained a lock first ({})", Thread.currentThread().getName());
} else {
addShutdownHook();
final Timestamp timestamp = new Timestamp(System.currentTimeMillis());
LOGGER.debug("Lock file created ({}) {} @ {}", Thread.currentThread().getName(), magic, timestamp.toString());
}
}
} catch (IOException | InterruptedException ex) {
LOGGER.trace("Expected error as another thread has likely locked the file", ex);
} finally {
if (lock == null && file != null) {
try {
file.close();
file = null;
} catch (IOException ex) {
LOGGER.trace("Unable to close the lock file", ex);
}
}
}
if (lock == null || !lock.isValid()) {
try {
final Timestamp timestamp = new Timestamp(System.currentTimeMillis());
LOGGER.debug("Sleeping thread {} ({}) for {} seconds because an exclusive lock on the database could not be obtained ({})",
Thread.currentThread().getName(), magic, SLEEP_DURATION / 1000, timestamp.toString());
Thread.sleep(SLEEP_DURATION);
} catch (InterruptedException ex) {
LOGGER.debug("sleep was interrupted.", ex);
Thread.currentThread().interrupt();
}
}
} while (++ctr < MAX_SLEEP_COUNT && (lock == null || !lock.isValid()));
if (lock == null || !lock.isValid()) {
throw new H2DBLockException("Unable to obtain the update lock, skipping the database update. Skippinig the database update.");
}
} catch (IOException ex) {
throw new H2DBLockException(ex.getMessage(), ex);
}
}
|
java
|
public void lock() throws H2DBLockException {
try {
final File dir = settings.getDataDirectory();
lockFile = new File(dir, "odc.update.lock");
checkState();
int ctr = 0;
do {
try {
if (!lockFile.exists() && lockFile.createNewFile()) {
file = new RandomAccessFile(lockFile, "rw");
lock = file.getChannel().lock();
file.writeBytes(magic);
file.getChannel().force(true);
Thread.sleep(20);
file.seek(0);
final String current = file.readLine();
if (current != null && !current.equals(magic)) {
lock.close();
lock = null;
LOGGER.debug("Another process obtained a lock first ({})", Thread.currentThread().getName());
} else {
addShutdownHook();
final Timestamp timestamp = new Timestamp(System.currentTimeMillis());
LOGGER.debug("Lock file created ({}) {} @ {}", Thread.currentThread().getName(), magic, timestamp.toString());
}
}
} catch (IOException | InterruptedException ex) {
LOGGER.trace("Expected error as another thread has likely locked the file", ex);
} finally {
if (lock == null && file != null) {
try {
file.close();
file = null;
} catch (IOException ex) {
LOGGER.trace("Unable to close the lock file", ex);
}
}
}
if (lock == null || !lock.isValid()) {
try {
final Timestamp timestamp = new Timestamp(System.currentTimeMillis());
LOGGER.debug("Sleeping thread {} ({}) for {} seconds because an exclusive lock on the database could not be obtained ({})",
Thread.currentThread().getName(), magic, SLEEP_DURATION / 1000, timestamp.toString());
Thread.sleep(SLEEP_DURATION);
} catch (InterruptedException ex) {
LOGGER.debug("sleep was interrupted.", ex);
Thread.currentThread().interrupt();
}
}
} while (++ctr < MAX_SLEEP_COUNT && (lock == null || !lock.isValid()));
if (lock == null || !lock.isValid()) {
throw new H2DBLockException("Unable to obtain the update lock, skipping the database update. Skippinig the database update.");
}
} catch (IOException ex) {
throw new H2DBLockException(ex.getMessage(), ex);
}
}
|
[
"public",
"void",
"lock",
"(",
")",
"throws",
"H2DBLockException",
"{",
"try",
"{",
"final",
"File",
"dir",
"=",
"settings",
".",
"getDataDirectory",
"(",
")",
";",
"lockFile",
"=",
"new",
"File",
"(",
"dir",
",",
"\"odc.update.lock\"",
")",
";",
"checkState",
"(",
")",
";",
"int",
"ctr",
"=",
"0",
";",
"do",
"{",
"try",
"{",
"if",
"(",
"!",
"lockFile",
".",
"exists",
"(",
")",
"&&",
"lockFile",
".",
"createNewFile",
"(",
")",
")",
"{",
"file",
"=",
"new",
"RandomAccessFile",
"(",
"lockFile",
",",
"\"rw\"",
")",
";",
"lock",
"=",
"file",
".",
"getChannel",
"(",
")",
".",
"lock",
"(",
")",
";",
"file",
".",
"writeBytes",
"(",
"magic",
")",
";",
"file",
".",
"getChannel",
"(",
")",
".",
"force",
"(",
"true",
")",
";",
"Thread",
".",
"sleep",
"(",
"20",
")",
";",
"file",
".",
"seek",
"(",
"0",
")",
";",
"final",
"String",
"current",
"=",
"file",
".",
"readLine",
"(",
")",
";",
"if",
"(",
"current",
"!=",
"null",
"&&",
"!",
"current",
".",
"equals",
"(",
"magic",
")",
")",
"{",
"lock",
".",
"close",
"(",
")",
";",
"lock",
"=",
"null",
";",
"LOGGER",
".",
"debug",
"(",
"\"Another process obtained a lock first ({})\"",
",",
"Thread",
".",
"currentThread",
"(",
")",
".",
"getName",
"(",
")",
")",
";",
"}",
"else",
"{",
"addShutdownHook",
"(",
")",
";",
"final",
"Timestamp",
"timestamp",
"=",
"new",
"Timestamp",
"(",
"System",
".",
"currentTimeMillis",
"(",
")",
")",
";",
"LOGGER",
".",
"debug",
"(",
"\"Lock file created ({}) {} @ {}\"",
",",
"Thread",
".",
"currentThread",
"(",
")",
".",
"getName",
"(",
")",
",",
"magic",
",",
"timestamp",
".",
"toString",
"(",
")",
")",
";",
"}",
"}",
"}",
"catch",
"(",
"IOException",
"|",
"InterruptedException",
"ex",
")",
"{",
"LOGGER",
".",
"trace",
"(",
"\"Expected error as another thread has likely locked the file\"",
",",
"ex",
")",
";",
"}",
"finally",
"{",
"if",
"(",
"lock",
"==",
"null",
"&&",
"file",
"!=",
"null",
")",
"{",
"try",
"{",
"file",
".",
"close",
"(",
")",
";",
"file",
"=",
"null",
";",
"}",
"catch",
"(",
"IOException",
"ex",
")",
"{",
"LOGGER",
".",
"trace",
"(",
"\"Unable to close the lock file\"",
",",
"ex",
")",
";",
"}",
"}",
"}",
"if",
"(",
"lock",
"==",
"null",
"||",
"!",
"lock",
".",
"isValid",
"(",
")",
")",
"{",
"try",
"{",
"final",
"Timestamp",
"timestamp",
"=",
"new",
"Timestamp",
"(",
"System",
".",
"currentTimeMillis",
"(",
")",
")",
";",
"LOGGER",
".",
"debug",
"(",
"\"Sleeping thread {} ({}) for {} seconds because an exclusive lock on the database could not be obtained ({})\"",
",",
"Thread",
".",
"currentThread",
"(",
")",
".",
"getName",
"(",
")",
",",
"magic",
",",
"SLEEP_DURATION",
"/",
"1000",
",",
"timestamp",
".",
"toString",
"(",
")",
")",
";",
"Thread",
".",
"sleep",
"(",
"SLEEP_DURATION",
")",
";",
"}",
"catch",
"(",
"InterruptedException",
"ex",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"sleep was interrupted.\"",
",",
"ex",
")",
";",
"Thread",
".",
"currentThread",
"(",
")",
".",
"interrupt",
"(",
")",
";",
"}",
"}",
"}",
"while",
"(",
"++",
"ctr",
"<",
"MAX_SLEEP_COUNT",
"&&",
"(",
"lock",
"==",
"null",
"||",
"!",
"lock",
".",
"isValid",
"(",
")",
")",
")",
";",
"if",
"(",
"lock",
"==",
"null",
"||",
"!",
"lock",
".",
"isValid",
"(",
")",
")",
"{",
"throw",
"new",
"H2DBLockException",
"(",
"\"Unable to obtain the update lock, skipping the database update. Skippinig the database update.\"",
")",
";",
"}",
"}",
"catch",
"(",
"IOException",
"ex",
")",
"{",
"throw",
"new",
"H2DBLockException",
"(",
"ex",
".",
"getMessage",
"(",
")",
",",
"ex",
")",
";",
"}",
"}"
] |
Obtains a lock on the H2 database.
@throws H2DBLockException thrown if a lock could not be obtained
|
[
"Obtains",
"a",
"lock",
"on",
"the",
"H2",
"database",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/utils/H2DBLock.java#L107-L163
|
17,937
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/utils/H2DBLock.java
|
H2DBLock.checkState
|
private void checkState() throws H2DBLockException {
if (!lockFile.getParentFile().isDirectory() && !lockFile.mkdir()) {
throw new H2DBLockException("Unable to create path to data directory.");
}
if (lockFile.isFile()) {
//TODO - this 30 minute check needs to be configurable.
if (getFileAge(lockFile) > 30) {
LOGGER.debug("An old db update lock file was found: {}", lockFile.getAbsolutePath());
if (!lockFile.delete()) {
LOGGER.warn("An old db update lock file was found but the system was unable to delete "
+ "the file. Consider manually deleting {}", lockFile.getAbsolutePath());
}
} else {
LOGGER.info("Lock file found `{}`", lockFile);
LOGGER.info("Existing update in progress; waiting for update to complete");
}
}
}
|
java
|
private void checkState() throws H2DBLockException {
if (!lockFile.getParentFile().isDirectory() && !lockFile.mkdir()) {
throw new H2DBLockException("Unable to create path to data directory.");
}
if (lockFile.isFile()) {
//TODO - this 30 minute check needs to be configurable.
if (getFileAge(lockFile) > 30) {
LOGGER.debug("An old db update lock file was found: {}", lockFile.getAbsolutePath());
if (!lockFile.delete()) {
LOGGER.warn("An old db update lock file was found but the system was unable to delete "
+ "the file. Consider manually deleting {}", lockFile.getAbsolutePath());
}
} else {
LOGGER.info("Lock file found `{}`", lockFile);
LOGGER.info("Existing update in progress; waiting for update to complete");
}
}
}
|
[
"private",
"void",
"checkState",
"(",
")",
"throws",
"H2DBLockException",
"{",
"if",
"(",
"!",
"lockFile",
".",
"getParentFile",
"(",
")",
".",
"isDirectory",
"(",
")",
"&&",
"!",
"lockFile",
".",
"mkdir",
"(",
")",
")",
"{",
"throw",
"new",
"H2DBLockException",
"(",
"\"Unable to create path to data directory.\"",
")",
";",
"}",
"if",
"(",
"lockFile",
".",
"isFile",
"(",
")",
")",
"{",
"//TODO - this 30 minute check needs to be configurable.",
"if",
"(",
"getFileAge",
"(",
"lockFile",
")",
">",
"30",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"An old db update lock file was found: {}\"",
",",
"lockFile",
".",
"getAbsolutePath",
"(",
")",
")",
";",
"if",
"(",
"!",
"lockFile",
".",
"delete",
"(",
")",
")",
"{",
"LOGGER",
".",
"warn",
"(",
"\"An old db update lock file was found but the system was unable to delete \"",
"+",
"\"the file. Consider manually deleting {}\"",
",",
"lockFile",
".",
"getAbsolutePath",
"(",
")",
")",
";",
"}",
"}",
"else",
"{",
"LOGGER",
".",
"info",
"(",
"\"Lock file found `{}`\"",
",",
"lockFile",
")",
";",
"LOGGER",
".",
"info",
"(",
"\"Existing update in progress; waiting for update to complete\"",
")",
";",
"}",
"}",
"}"
] |
Checks the state of the custom h2 lock file and under some conditions
will attempt to remove the lock file.
@throws H2DBLockException thrown if the lock directory does not exist and
cannot be created
|
[
"Checks",
"the",
"state",
"of",
"the",
"custom",
"h2",
"lock",
"file",
"and",
"under",
"some",
"conditions",
"will",
"attempt",
"to",
"remove",
"the",
"lock",
"file",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/utils/H2DBLock.java#L172-L189
|
17,938
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/utils/H2DBLock.java
|
H2DBLock.release
|
public void release() {
if (lock != null) {
try {
lock.release();
lock = null;
} catch (IOException ex) {
LOGGER.debug("Failed to release lock", ex);
}
}
if (file != null) {
try {
file.close();
file = null;
} catch (IOException ex) {
LOGGER.debug("Unable to delete lock file", ex);
}
}
if (lockFile != null && lockFile.isFile()) {
final String msg = readLockFile();
if (msg != null && msg.equals(magic) && !lockFile.delete()) {
LOGGER.error("Lock file '{}' was unable to be deleted. Please manually delete this file.", lockFile.toString());
lockFile.deleteOnExit();
}
}
lockFile = null;
removeShutdownHook();
final Timestamp timestamp = new Timestamp(System.currentTimeMillis());
LOGGER.debug("Lock released ({}) {} @ {}", Thread.currentThread().getName(), magic, timestamp.toString());
}
|
java
|
public void release() {
if (lock != null) {
try {
lock.release();
lock = null;
} catch (IOException ex) {
LOGGER.debug("Failed to release lock", ex);
}
}
if (file != null) {
try {
file.close();
file = null;
} catch (IOException ex) {
LOGGER.debug("Unable to delete lock file", ex);
}
}
if (lockFile != null && lockFile.isFile()) {
final String msg = readLockFile();
if (msg != null && msg.equals(magic) && !lockFile.delete()) {
LOGGER.error("Lock file '{}' was unable to be deleted. Please manually delete this file.", lockFile.toString());
lockFile.deleteOnExit();
}
}
lockFile = null;
removeShutdownHook();
final Timestamp timestamp = new Timestamp(System.currentTimeMillis());
LOGGER.debug("Lock released ({}) {} @ {}", Thread.currentThread().getName(), magic, timestamp.toString());
}
|
[
"public",
"void",
"release",
"(",
")",
"{",
"if",
"(",
"lock",
"!=",
"null",
")",
"{",
"try",
"{",
"lock",
".",
"release",
"(",
")",
";",
"lock",
"=",
"null",
";",
"}",
"catch",
"(",
"IOException",
"ex",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"Failed to release lock\"",
",",
"ex",
")",
";",
"}",
"}",
"if",
"(",
"file",
"!=",
"null",
")",
"{",
"try",
"{",
"file",
".",
"close",
"(",
")",
";",
"file",
"=",
"null",
";",
"}",
"catch",
"(",
"IOException",
"ex",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"Unable to delete lock file\"",
",",
"ex",
")",
";",
"}",
"}",
"if",
"(",
"lockFile",
"!=",
"null",
"&&",
"lockFile",
".",
"isFile",
"(",
")",
")",
"{",
"final",
"String",
"msg",
"=",
"readLockFile",
"(",
")",
";",
"if",
"(",
"msg",
"!=",
"null",
"&&",
"msg",
".",
"equals",
"(",
"magic",
")",
"&&",
"!",
"lockFile",
".",
"delete",
"(",
")",
")",
"{",
"LOGGER",
".",
"error",
"(",
"\"Lock file '{}' was unable to be deleted. Please manually delete this file.\"",
",",
"lockFile",
".",
"toString",
"(",
")",
")",
";",
"lockFile",
".",
"deleteOnExit",
"(",
")",
";",
"}",
"}",
"lockFile",
"=",
"null",
";",
"removeShutdownHook",
"(",
")",
";",
"final",
"Timestamp",
"timestamp",
"=",
"new",
"Timestamp",
"(",
"System",
".",
"currentTimeMillis",
"(",
")",
")",
";",
"LOGGER",
".",
"debug",
"(",
"\"Lock released ({}) {} @ {}\"",
",",
"Thread",
".",
"currentThread",
"(",
")",
".",
"getName",
"(",
")",
",",
"magic",
",",
"timestamp",
".",
"toString",
"(",
")",
")",
";",
"}"
] |
Releases the lock on the H2 database.
|
[
"Releases",
"the",
"lock",
"on",
"the",
"H2",
"database",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/utils/H2DBLock.java#L194-L222
|
17,939
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/utils/H2DBLock.java
|
H2DBLock.readLockFile
|
private String readLockFile() {
String msg = null;
try (RandomAccessFile f = new RandomAccessFile(lockFile, "rw")) {
msg = f.readLine();
} catch (IOException ex) {
LOGGER.debug(String.format("Error reading lock file: %s", lockFile), ex);
}
return msg;
}
|
java
|
private String readLockFile() {
String msg = null;
try (RandomAccessFile f = new RandomAccessFile(lockFile, "rw")) {
msg = f.readLine();
} catch (IOException ex) {
LOGGER.debug(String.format("Error reading lock file: %s", lockFile), ex);
}
return msg;
}
|
[
"private",
"String",
"readLockFile",
"(",
")",
"{",
"String",
"msg",
"=",
"null",
";",
"try",
"(",
"RandomAccessFile",
"f",
"=",
"new",
"RandomAccessFile",
"(",
"lockFile",
",",
"\"rw\"",
")",
")",
"{",
"msg",
"=",
"f",
".",
"readLine",
"(",
")",
";",
"}",
"catch",
"(",
"IOException",
"ex",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"String",
".",
"format",
"(",
"\"Error reading lock file: %s\"",
",",
"lockFile",
")",
",",
"ex",
")",
";",
"}",
"return",
"msg",
";",
"}"
] |
Reads the first line from the lock file and returns the results as a
string.
@return the first line from the lock file; or null if the contents could
not be read
|
[
"Reads",
"the",
"first",
"line",
"from",
"the",
"lock",
"file",
"and",
"returns",
"the",
"results",
"as",
"a",
"string",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/utils/H2DBLock.java#L231-L239
|
17,940
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/utils/H2DBLock.java
|
H2DBLock.getFileAge
|
private double getFileAge(File file) {
final Date d = new Date();
final long modified = file.lastModified();
final double time = (d.getTime() - modified) / 1000.0 / 60.0;
LOGGER.debug("Lock file age is {} minutes", time);
return time;
}
|
java
|
private double getFileAge(File file) {
final Date d = new Date();
final long modified = file.lastModified();
final double time = (d.getTime() - modified) / 1000.0 / 60.0;
LOGGER.debug("Lock file age is {} minutes", time);
return time;
}
|
[
"private",
"double",
"getFileAge",
"(",
"File",
"file",
")",
"{",
"final",
"Date",
"d",
"=",
"new",
"Date",
"(",
")",
";",
"final",
"long",
"modified",
"=",
"file",
".",
"lastModified",
"(",
")",
";",
"final",
"double",
"time",
"=",
"(",
"d",
".",
"getTime",
"(",
")",
"-",
"modified",
")",
"/",
"1000.0",
"/",
"60.0",
";",
"LOGGER",
".",
"debug",
"(",
"\"Lock file age is {} minutes\"",
",",
"time",
")",
";",
"return",
"time",
";",
"}"
] |
Returns the age of the file in minutes.
@param file the file to calculate the age
@return the age of the file
|
[
"Returns",
"the",
"age",
"of",
"the",
"file",
"in",
"minutes",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/utils/H2DBLock.java#L247-L253
|
17,941
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/data/nexus/MavenArtifact.java
|
MavenArtifact.derivePomUrl
|
public static String derivePomUrl(String artifactId, String version, String artifactUrl) {
return artifactUrl.substring(0, artifactUrl.lastIndexOf('/')) + '/' + artifactId + '-' + version + ".pom";
}
|
java
|
public static String derivePomUrl(String artifactId, String version, String artifactUrl) {
return artifactUrl.substring(0, artifactUrl.lastIndexOf('/')) + '/' + artifactId + '-' + version + ".pom";
}
|
[
"public",
"static",
"String",
"derivePomUrl",
"(",
"String",
"artifactId",
",",
"String",
"version",
",",
"String",
"artifactUrl",
")",
"{",
"return",
"artifactUrl",
".",
"substring",
"(",
"0",
",",
"artifactUrl",
".",
"lastIndexOf",
"(",
"'",
"'",
")",
")",
"+",
"'",
"'",
"+",
"artifactId",
"+",
"'",
"'",
"+",
"version",
"+",
"\".pom\"",
";",
"}"
] |
Tries to determine the URL to the pom.xml.
@param artifactId the artifact id
@param version the version
@param artifactUrl the artifact URL
@return the string representation of the URL
|
[
"Tries",
"to",
"determine",
"the",
"URL",
"to",
"the",
"pom",
".",
"xml",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/data/nexus/MavenArtifact.java#L145-L147
|
17,942
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/dependency/EvidenceCollection.java
|
EvidenceCollection.getIterator
|
public synchronized Iterable<Evidence> getIterator(EvidenceType type, Confidence confidence) {
if (null != confidence && null != type) {
final Set<Evidence> list;
switch (type) {
case VENDOR:
list = Collections.unmodifiableSet(new HashSet<>(vendors));
break;
case PRODUCT:
list = Collections.unmodifiableSet(new HashSet<>(products));
break;
case VERSION:
list = Collections.unmodifiableSet(new HashSet<>(versions));
break;
default:
return null;
}
switch (confidence) {
case HIGHEST:
return EvidenceCollection.HIGHEST_CONFIDENCE.filter(list);
case HIGH:
return EvidenceCollection.HIGH_CONFIDENCE.filter(list);
case MEDIUM:
return EvidenceCollection.MEDIUM_CONFIDENCE.filter(list);
default:
return EvidenceCollection.LOW_CONFIDENCE.filter(list);
}
}
return null;
}
|
java
|
public synchronized Iterable<Evidence> getIterator(EvidenceType type, Confidence confidence) {
if (null != confidence && null != type) {
final Set<Evidence> list;
switch (type) {
case VENDOR:
list = Collections.unmodifiableSet(new HashSet<>(vendors));
break;
case PRODUCT:
list = Collections.unmodifiableSet(new HashSet<>(products));
break;
case VERSION:
list = Collections.unmodifiableSet(new HashSet<>(versions));
break;
default:
return null;
}
switch (confidence) {
case HIGHEST:
return EvidenceCollection.HIGHEST_CONFIDENCE.filter(list);
case HIGH:
return EvidenceCollection.HIGH_CONFIDENCE.filter(list);
case MEDIUM:
return EvidenceCollection.MEDIUM_CONFIDENCE.filter(list);
default:
return EvidenceCollection.LOW_CONFIDENCE.filter(list);
}
}
return null;
}
|
[
"public",
"synchronized",
"Iterable",
"<",
"Evidence",
">",
"getIterator",
"(",
"EvidenceType",
"type",
",",
"Confidence",
"confidence",
")",
"{",
"if",
"(",
"null",
"!=",
"confidence",
"&&",
"null",
"!=",
"type",
")",
"{",
"final",
"Set",
"<",
"Evidence",
">",
"list",
";",
"switch",
"(",
"type",
")",
"{",
"case",
"VENDOR",
":",
"list",
"=",
"Collections",
".",
"unmodifiableSet",
"(",
"new",
"HashSet",
"<>",
"(",
"vendors",
")",
")",
";",
"break",
";",
"case",
"PRODUCT",
":",
"list",
"=",
"Collections",
".",
"unmodifiableSet",
"(",
"new",
"HashSet",
"<>",
"(",
"products",
")",
")",
";",
"break",
";",
"case",
"VERSION",
":",
"list",
"=",
"Collections",
".",
"unmodifiableSet",
"(",
"new",
"HashSet",
"<>",
"(",
"versions",
")",
")",
";",
"break",
";",
"default",
":",
"return",
"null",
";",
"}",
"switch",
"(",
"confidence",
")",
"{",
"case",
"HIGHEST",
":",
"return",
"EvidenceCollection",
".",
"HIGHEST_CONFIDENCE",
".",
"filter",
"(",
"list",
")",
";",
"case",
"HIGH",
":",
"return",
"EvidenceCollection",
".",
"HIGH_CONFIDENCE",
".",
"filter",
"(",
"list",
")",
";",
"case",
"MEDIUM",
":",
"return",
"EvidenceCollection",
".",
"MEDIUM_CONFIDENCE",
".",
"filter",
"(",
"list",
")",
";",
"default",
":",
"return",
"EvidenceCollection",
".",
"LOW_CONFIDENCE",
".",
"filter",
"(",
"list",
")",
";",
"}",
"}",
"return",
"null",
";",
"}"
] |
Used to iterate over evidence of the specified type and confidence.
@param type the evidence type to iterate over
@param confidence the confidence level for the evidence to be iterated
over.
@return Iterable<Evidence> an iterable collection of evidence
|
[
"Used",
"to",
"iterate",
"over",
"evidence",
"of",
"the",
"specified",
"type",
"and",
"confidence",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/dependency/EvidenceCollection.java#L110-L140
|
17,943
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/dependency/EvidenceCollection.java
|
EvidenceCollection.addEvidence
|
public synchronized void addEvidence(EvidenceType type, Evidence e) {
if (null != type) {
switch (type) {
case VENDOR:
vendors.add(e);
break;
case PRODUCT:
products.add(e);
break;
case VERSION:
versions.add(e);
break;
default:
break;
}
}
}
|
java
|
public synchronized void addEvidence(EvidenceType type, Evidence e) {
if (null != type) {
switch (type) {
case VENDOR:
vendors.add(e);
break;
case PRODUCT:
products.add(e);
break;
case VERSION:
versions.add(e);
break;
default:
break;
}
}
}
|
[
"public",
"synchronized",
"void",
"addEvidence",
"(",
"EvidenceType",
"type",
",",
"Evidence",
"e",
")",
"{",
"if",
"(",
"null",
"!=",
"type",
")",
"{",
"switch",
"(",
"type",
")",
"{",
"case",
"VENDOR",
":",
"vendors",
".",
"add",
"(",
"e",
")",
";",
"break",
";",
"case",
"PRODUCT",
":",
"products",
".",
"add",
"(",
"e",
")",
";",
"break",
";",
"case",
"VERSION",
":",
"versions",
".",
"add",
"(",
"e",
")",
";",
"break",
";",
"default",
":",
"break",
";",
"}",
"}",
"}"
] |
Adds evidence to the collection.
@param type the type of evidence (vendor, product, version)
@param e Evidence
|
[
"Adds",
"evidence",
"to",
"the",
"collection",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/dependency/EvidenceCollection.java#L148-L164
|
17,944
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/dependency/EvidenceCollection.java
|
EvidenceCollection.removeEvidence
|
public synchronized void removeEvidence(EvidenceType type, Evidence e) {
if (null != type) {
switch (type) {
case VENDOR:
vendors.remove(e);
break;
case PRODUCT:
products.remove(e);
break;
case VERSION:
versions.remove(e);
break;
default:
break;
}
}
}
|
java
|
public synchronized void removeEvidence(EvidenceType type, Evidence e) {
if (null != type) {
switch (type) {
case VENDOR:
vendors.remove(e);
break;
case PRODUCT:
products.remove(e);
break;
case VERSION:
versions.remove(e);
break;
default:
break;
}
}
}
|
[
"public",
"synchronized",
"void",
"removeEvidence",
"(",
"EvidenceType",
"type",
",",
"Evidence",
"e",
")",
"{",
"if",
"(",
"null",
"!=",
"type",
")",
"{",
"switch",
"(",
"type",
")",
"{",
"case",
"VENDOR",
":",
"vendors",
".",
"remove",
"(",
"e",
")",
";",
"break",
";",
"case",
"PRODUCT",
":",
"products",
".",
"remove",
"(",
"e",
")",
";",
"break",
";",
"case",
"VERSION",
":",
"versions",
".",
"remove",
"(",
"e",
")",
";",
"break",
";",
"default",
":",
"break",
";",
"}",
"}",
"}"
] |
Removes evidence from the collection.
@param type the type of evidence (vendor, product, version)
@param e Evidence.
|
[
"Removes",
"evidence",
"from",
"the",
"collection",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/dependency/EvidenceCollection.java#L172-L188
|
17,945
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/dependency/EvidenceCollection.java
|
EvidenceCollection.addEvidence
|
public void addEvidence(EvidenceType type, String source, String name, String value, Confidence confidence) {
final Evidence e = new Evidence(source, name, value, confidence);
addEvidence(type, e);
}
|
java
|
public void addEvidence(EvidenceType type, String source, String name, String value, Confidence confidence) {
final Evidence e = new Evidence(source, name, value, confidence);
addEvidence(type, e);
}
|
[
"public",
"void",
"addEvidence",
"(",
"EvidenceType",
"type",
",",
"String",
"source",
",",
"String",
"name",
",",
"String",
"value",
",",
"Confidence",
"confidence",
")",
"{",
"final",
"Evidence",
"e",
"=",
"new",
"Evidence",
"(",
"source",
",",
"name",
",",
"value",
",",
"confidence",
")",
";",
"addEvidence",
"(",
"type",
",",
"e",
")",
";",
"}"
] |
Creates an Evidence object from the parameters and adds the resulting
object to the evidence collection.
@param type the type of evidence (vendor, product, version)
@param source the source of the Evidence.
@param name the name of the Evidence.
@param value the value of the Evidence.
@param confidence the confidence of the Evidence.
|
[
"Creates",
"an",
"Evidence",
"object",
"from",
"the",
"parameters",
"and",
"adds",
"the",
"resulting",
"object",
"to",
"the",
"evidence",
"collection",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/dependency/EvidenceCollection.java#L200-L203
|
17,946
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/dependency/EvidenceCollection.java
|
EvidenceCollection.getEvidence
|
public synchronized Set<Evidence> getEvidence(EvidenceType type) {
if (null != type) {
switch (type) {
case VENDOR:
return Collections.unmodifiableSet(new HashSet<>(vendors));
case PRODUCT:
return Collections.unmodifiableSet(new HashSet<>(products));
case VERSION:
return Collections.unmodifiableSet(new HashSet<>(versions));
default:
break;
}
}
return null;
}
|
java
|
public synchronized Set<Evidence> getEvidence(EvidenceType type) {
if (null != type) {
switch (type) {
case VENDOR:
return Collections.unmodifiableSet(new HashSet<>(vendors));
case PRODUCT:
return Collections.unmodifiableSet(new HashSet<>(products));
case VERSION:
return Collections.unmodifiableSet(new HashSet<>(versions));
default:
break;
}
}
return null;
}
|
[
"public",
"synchronized",
"Set",
"<",
"Evidence",
">",
"getEvidence",
"(",
"EvidenceType",
"type",
")",
"{",
"if",
"(",
"null",
"!=",
"type",
")",
"{",
"switch",
"(",
"type",
")",
"{",
"case",
"VENDOR",
":",
"return",
"Collections",
".",
"unmodifiableSet",
"(",
"new",
"HashSet",
"<>",
"(",
"vendors",
")",
")",
";",
"case",
"PRODUCT",
":",
"return",
"Collections",
".",
"unmodifiableSet",
"(",
"new",
"HashSet",
"<>",
"(",
"products",
")",
")",
";",
"case",
"VERSION",
":",
"return",
"Collections",
".",
"unmodifiableSet",
"(",
"new",
"HashSet",
"<>",
"(",
"versions",
")",
")",
";",
"default",
":",
"break",
";",
"}",
"}",
"return",
"null",
";",
"}"
] |
Returns the unmodifiable set of evidence of the given type.
@param type the type of evidence (vendor, product, version)
@return the unmodifiable set of evidence
|
[
"Returns",
"the",
"unmodifiable",
"set",
"of",
"evidence",
"of",
"the",
"given",
"type",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/dependency/EvidenceCollection.java#L271-L285
|
17,947
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/dependency/EvidenceCollection.java
|
EvidenceCollection.contains
|
public synchronized boolean contains(EvidenceType type, Evidence e) {
if (null != type) {
switch (type) {
case VENDOR:
return vendors.contains(e);
case PRODUCT:
return products.contains(e);
case VERSION:
return versions.contains(e);
default:
break;
}
}
return false;
}
|
java
|
public synchronized boolean contains(EvidenceType type, Evidence e) {
if (null != type) {
switch (type) {
case VENDOR:
return vendors.contains(e);
case PRODUCT:
return products.contains(e);
case VERSION:
return versions.contains(e);
default:
break;
}
}
return false;
}
|
[
"public",
"synchronized",
"boolean",
"contains",
"(",
"EvidenceType",
"type",
",",
"Evidence",
"e",
")",
"{",
"if",
"(",
"null",
"!=",
"type",
")",
"{",
"switch",
"(",
"type",
")",
"{",
"case",
"VENDOR",
":",
"return",
"vendors",
".",
"contains",
"(",
"e",
")",
";",
"case",
"PRODUCT",
":",
"return",
"products",
".",
"contains",
"(",
"e",
")",
";",
"case",
"VERSION",
":",
"return",
"versions",
".",
"contains",
"(",
"e",
")",
";",
"default",
":",
"break",
";",
"}",
"}",
"return",
"false",
";",
"}"
] |
Tests if the evidence collection contains the given evidence.
@param type the type of evidence (vendor, product, version)
@param e the evidence to search
@return true if the evidence is found; otherwise false
|
[
"Tests",
"if",
"the",
"evidence",
"collection",
"contains",
"the",
"given",
"evidence",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/dependency/EvidenceCollection.java#L294-L308
|
17,948
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/dependency/EvidenceCollection.java
|
EvidenceCollection.contains
|
public synchronized boolean contains(EvidenceType type, Confidence confidence) {
if (null == type) {
return false;
}
final Set<Evidence> col;
switch (type) {
case VENDOR:
col = vendors;
break;
case PRODUCT:
col = products;
break;
case VERSION:
col = versions;
break;
default:
return false;
}
for (Evidence e : col) {
if (e.getConfidence().equals(confidence)) {
return true;
}
}
return false;
}
|
java
|
public synchronized boolean contains(EvidenceType type, Confidence confidence) {
if (null == type) {
return false;
}
final Set<Evidence> col;
switch (type) {
case VENDOR:
col = vendors;
break;
case PRODUCT:
col = products;
break;
case VERSION:
col = versions;
break;
default:
return false;
}
for (Evidence e : col) {
if (e.getConfidence().equals(confidence)) {
return true;
}
}
return false;
}
|
[
"public",
"synchronized",
"boolean",
"contains",
"(",
"EvidenceType",
"type",
",",
"Confidence",
"confidence",
")",
"{",
"if",
"(",
"null",
"==",
"type",
")",
"{",
"return",
"false",
";",
"}",
"final",
"Set",
"<",
"Evidence",
">",
"col",
";",
"switch",
"(",
"type",
")",
"{",
"case",
"VENDOR",
":",
"col",
"=",
"vendors",
";",
"break",
";",
"case",
"PRODUCT",
":",
"col",
"=",
"products",
";",
"break",
";",
"case",
"VERSION",
":",
"col",
"=",
"versions",
";",
"break",
";",
"default",
":",
"return",
"false",
";",
"}",
"for",
"(",
"Evidence",
"e",
":",
"col",
")",
"{",
"if",
"(",
"e",
".",
"getConfidence",
"(",
")",
".",
"equals",
"(",
"confidence",
")",
")",
"{",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}"
] |
Returns whether or not the collection contains evidence of a specified
type and confidence.
@param type the type of evidence (vendor, product, version)
@param confidence A Confidence value.
@return boolean.
|
[
"Returns",
"whether",
"or",
"not",
"the",
"collection",
"contains",
"evidence",
"of",
"a",
"specified",
"type",
"and",
"confidence",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/dependency/EvidenceCollection.java#L318-L342
|
17,949
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/xml/pom/PomParser.java
|
PomParser.parse
|
public Model parse(File file) throws PomParseException {
try (FileInputStream fis = new FileInputStream(file)) {
return parse(fis);
} catch (IOException ex) {
LOGGER.debug("", ex);
throw new PomParseException(String.format("Unable to parse pom '%s'", file.toString()), ex);
}
}
|
java
|
public Model parse(File file) throws PomParseException {
try (FileInputStream fis = new FileInputStream(file)) {
return parse(fis);
} catch (IOException ex) {
LOGGER.debug("", ex);
throw new PomParseException(String.format("Unable to parse pom '%s'", file.toString()), ex);
}
}
|
[
"public",
"Model",
"parse",
"(",
"File",
"file",
")",
"throws",
"PomParseException",
"{",
"try",
"(",
"FileInputStream",
"fis",
"=",
"new",
"FileInputStream",
"(",
"file",
")",
")",
"{",
"return",
"parse",
"(",
"fis",
")",
";",
"}",
"catch",
"(",
"IOException",
"ex",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"\"",
",",
"ex",
")",
";",
"throw",
"new",
"PomParseException",
"(",
"String",
".",
"format",
"(",
"\"Unable to parse pom '%s'\"",
",",
"file",
".",
"toString",
"(",
")",
")",
",",
"ex",
")",
";",
"}",
"}"
] |
Parses the given xml file and returns a Model object containing only the
fields dependency-check requires.
@param file a pom.xml
@return a Model object containing only the fields dependency-check
requires
@throws PomParseException thrown if the xml file cannot be parsed
|
[
"Parses",
"the",
"given",
"xml",
"file",
"and",
"returns",
"a",
"Model",
"object",
"containing",
"only",
"the",
"fields",
"dependency",
"-",
"check",
"requires",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/xml/pom/PomParser.java#L64-L71
|
17,950
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/xml/pom/PomParser.java
|
PomParser.parse
|
public Model parse(InputStream inputStream) throws PomParseException {
try {
final PomHandler handler = new PomHandler();
final SAXParser saxParser = XmlUtils.buildSecureSaxParser();
final XMLReader xmlReader = saxParser.getXMLReader();
xmlReader.setContentHandler(handler);
final BOMInputStream bomStream = new BOMInputStream(new XmlInputStream(new PomProjectInputStream(inputStream)));
final ByteOrderMark bom = bomStream.getBOM();
final String defaultEncoding = StandardCharsets.UTF_8.name();
final String charsetName = bom == null ? defaultEncoding : bom.getCharsetName();
final Reader reader = new InputStreamReader(bomStream, charsetName);
final InputSource in = new InputSource(reader);
xmlReader.parse(in);
return handler.getModel();
} catch (ParserConfigurationException | SAXException | FileNotFoundException ex) {
LOGGER.debug("", ex);
throw new PomParseException(ex);
} catch (IOException ex) {
LOGGER.debug("", ex);
throw new PomParseException(ex);
}
}
|
java
|
public Model parse(InputStream inputStream) throws PomParseException {
try {
final PomHandler handler = new PomHandler();
final SAXParser saxParser = XmlUtils.buildSecureSaxParser();
final XMLReader xmlReader = saxParser.getXMLReader();
xmlReader.setContentHandler(handler);
final BOMInputStream bomStream = new BOMInputStream(new XmlInputStream(new PomProjectInputStream(inputStream)));
final ByteOrderMark bom = bomStream.getBOM();
final String defaultEncoding = StandardCharsets.UTF_8.name();
final String charsetName = bom == null ? defaultEncoding : bom.getCharsetName();
final Reader reader = new InputStreamReader(bomStream, charsetName);
final InputSource in = new InputSource(reader);
xmlReader.parse(in);
return handler.getModel();
} catch (ParserConfigurationException | SAXException | FileNotFoundException ex) {
LOGGER.debug("", ex);
throw new PomParseException(ex);
} catch (IOException ex) {
LOGGER.debug("", ex);
throw new PomParseException(ex);
}
}
|
[
"public",
"Model",
"parse",
"(",
"InputStream",
"inputStream",
")",
"throws",
"PomParseException",
"{",
"try",
"{",
"final",
"PomHandler",
"handler",
"=",
"new",
"PomHandler",
"(",
")",
";",
"final",
"SAXParser",
"saxParser",
"=",
"XmlUtils",
".",
"buildSecureSaxParser",
"(",
")",
";",
"final",
"XMLReader",
"xmlReader",
"=",
"saxParser",
".",
"getXMLReader",
"(",
")",
";",
"xmlReader",
".",
"setContentHandler",
"(",
"handler",
")",
";",
"final",
"BOMInputStream",
"bomStream",
"=",
"new",
"BOMInputStream",
"(",
"new",
"XmlInputStream",
"(",
"new",
"PomProjectInputStream",
"(",
"inputStream",
")",
")",
")",
";",
"final",
"ByteOrderMark",
"bom",
"=",
"bomStream",
".",
"getBOM",
"(",
")",
";",
"final",
"String",
"defaultEncoding",
"=",
"StandardCharsets",
".",
"UTF_8",
".",
"name",
"(",
")",
";",
"final",
"String",
"charsetName",
"=",
"bom",
"==",
"null",
"?",
"defaultEncoding",
":",
"bom",
".",
"getCharsetName",
"(",
")",
";",
"final",
"Reader",
"reader",
"=",
"new",
"InputStreamReader",
"(",
"bomStream",
",",
"charsetName",
")",
";",
"final",
"InputSource",
"in",
"=",
"new",
"InputSource",
"(",
"reader",
")",
";",
"xmlReader",
".",
"parse",
"(",
"in",
")",
";",
"return",
"handler",
".",
"getModel",
"(",
")",
";",
"}",
"catch",
"(",
"ParserConfigurationException",
"|",
"SAXException",
"|",
"FileNotFoundException",
"ex",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"\"",
",",
"ex",
")",
";",
"throw",
"new",
"PomParseException",
"(",
"ex",
")",
";",
"}",
"catch",
"(",
"IOException",
"ex",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"\"",
",",
"ex",
")",
";",
"throw",
"new",
"PomParseException",
"(",
"ex",
")",
";",
"}",
"}"
] |
Parses the given XML file and returns a Model object containing only the
fields dependency-check requires.
@param inputStream an InputStream containing suppression rues
@return a list of suppression rules
@throws PomParseException if the XML cannot be parsed
|
[
"Parses",
"the",
"given",
"XML",
"file",
"and",
"returns",
"a",
"Model",
"object",
"containing",
"only",
"the",
"fields",
"dependency",
"-",
"check",
"requires",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/xml/pom/PomParser.java#L81-L103
|
17,951
|
jeremylong/DependencyCheck
|
maven/src/main/java/org/owasp/dependencycheck/maven/PurgeMojo.java
|
PurgeMojo.runCheck
|
@Override
protected void runCheck() throws MojoExecutionException, MojoFailureException {
if (getConnectionString() != null && !getConnectionString().isEmpty()) {
final String msg = "Unable to purge the local NVD when using a non-default connection string";
if (this.isFailOnError()) {
throw new MojoFailureException(msg);
}
getLog().error(msg);
} else {
populateSettings();
final File db;
try {
db = new File(getSettings().getDataDirectory(), getSettings().getString(Settings.KEYS.DB_FILE_NAME, "odc.mv.db"));
if (db.exists()) {
if (db.delete()) {
getLog().info("Database file purged; local copy of the NVD has been removed");
} else {
final String msg = String.format("Unable to delete '%s'; please delete the file manually", db.getAbsolutePath());
if (this.isFailOnError()) {
throw new MojoFailureException(msg);
}
getLog().error(msg);
}
} else {
final String msg = String.format("Unable to purge database; the database file does not exist: %s", db.getAbsolutePath());
if (this.isFailOnError()) {
throw new MojoFailureException(msg);
}
getLog().error(msg);
}
} catch (IOException ex) {
final String msg = "Unable to delete the database";
if (this.isFailOnError()) {
throw new MojoExecutionException(msg, ex);
}
getLog().error(msg);
}
getSettings().cleanup();
}
}
|
java
|
@Override
protected void runCheck() throws MojoExecutionException, MojoFailureException {
if (getConnectionString() != null && !getConnectionString().isEmpty()) {
final String msg = "Unable to purge the local NVD when using a non-default connection string";
if (this.isFailOnError()) {
throw new MojoFailureException(msg);
}
getLog().error(msg);
} else {
populateSettings();
final File db;
try {
db = new File(getSettings().getDataDirectory(), getSettings().getString(Settings.KEYS.DB_FILE_NAME, "odc.mv.db"));
if (db.exists()) {
if (db.delete()) {
getLog().info("Database file purged; local copy of the NVD has been removed");
} else {
final String msg = String.format("Unable to delete '%s'; please delete the file manually", db.getAbsolutePath());
if (this.isFailOnError()) {
throw new MojoFailureException(msg);
}
getLog().error(msg);
}
} else {
final String msg = String.format("Unable to purge database; the database file does not exist: %s", db.getAbsolutePath());
if (this.isFailOnError()) {
throw new MojoFailureException(msg);
}
getLog().error(msg);
}
} catch (IOException ex) {
final String msg = "Unable to delete the database";
if (this.isFailOnError()) {
throw new MojoExecutionException(msg, ex);
}
getLog().error(msg);
}
getSettings().cleanup();
}
}
|
[
"@",
"Override",
"protected",
"void",
"runCheck",
"(",
")",
"throws",
"MojoExecutionException",
",",
"MojoFailureException",
"{",
"if",
"(",
"getConnectionString",
"(",
")",
"!=",
"null",
"&&",
"!",
"getConnectionString",
"(",
")",
".",
"isEmpty",
"(",
")",
")",
"{",
"final",
"String",
"msg",
"=",
"\"Unable to purge the local NVD when using a non-default connection string\"",
";",
"if",
"(",
"this",
".",
"isFailOnError",
"(",
")",
")",
"{",
"throw",
"new",
"MojoFailureException",
"(",
"msg",
")",
";",
"}",
"getLog",
"(",
")",
".",
"error",
"(",
"msg",
")",
";",
"}",
"else",
"{",
"populateSettings",
"(",
")",
";",
"final",
"File",
"db",
";",
"try",
"{",
"db",
"=",
"new",
"File",
"(",
"getSettings",
"(",
")",
".",
"getDataDirectory",
"(",
")",
",",
"getSettings",
"(",
")",
".",
"getString",
"(",
"Settings",
".",
"KEYS",
".",
"DB_FILE_NAME",
",",
"\"odc.mv.db\"",
")",
")",
";",
"if",
"(",
"db",
".",
"exists",
"(",
")",
")",
"{",
"if",
"(",
"db",
".",
"delete",
"(",
")",
")",
"{",
"getLog",
"(",
")",
".",
"info",
"(",
"\"Database file purged; local copy of the NVD has been removed\"",
")",
";",
"}",
"else",
"{",
"final",
"String",
"msg",
"=",
"String",
".",
"format",
"(",
"\"Unable to delete '%s'; please delete the file manually\"",
",",
"db",
".",
"getAbsolutePath",
"(",
")",
")",
";",
"if",
"(",
"this",
".",
"isFailOnError",
"(",
")",
")",
"{",
"throw",
"new",
"MojoFailureException",
"(",
"msg",
")",
";",
"}",
"getLog",
"(",
")",
".",
"error",
"(",
"msg",
")",
";",
"}",
"}",
"else",
"{",
"final",
"String",
"msg",
"=",
"String",
".",
"format",
"(",
"\"Unable to purge database; the database file does not exist: %s\"",
",",
"db",
".",
"getAbsolutePath",
"(",
")",
")",
";",
"if",
"(",
"this",
".",
"isFailOnError",
"(",
")",
")",
"{",
"throw",
"new",
"MojoFailureException",
"(",
"msg",
")",
";",
"}",
"getLog",
"(",
")",
".",
"error",
"(",
"msg",
")",
";",
"}",
"}",
"catch",
"(",
"IOException",
"ex",
")",
"{",
"final",
"String",
"msg",
"=",
"\"Unable to delete the database\"",
";",
"if",
"(",
"this",
".",
"isFailOnError",
"(",
")",
")",
"{",
"throw",
"new",
"MojoExecutionException",
"(",
"msg",
",",
"ex",
")",
";",
"}",
"getLog",
"(",
")",
".",
"error",
"(",
"msg",
")",
";",
"}",
"getSettings",
"(",
")",
".",
"cleanup",
"(",
")",
";",
"}",
"}"
] |
Purges the local copy of the NVD.
@throws MojoExecutionException thrown if there is an exception executing
the goal
@throws MojoFailureException thrown if dependency-check is configured to
fail the build
|
[
"Purges",
"the",
"local",
"copy",
"of",
"the",
"NVD",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/maven/src/main/java/org/owasp/dependencycheck/maven/PurgeMojo.java#L66-L106
|
17,952
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/xml/hints/EvidenceMatcher.java
|
EvidenceMatcher.matches
|
public boolean matches(Evidence evidence) {
return sourceMatches(evidence)
&& confidenceMatches(evidence)
&& name.equalsIgnoreCase(evidence.getName())
&& valueMatches(evidence);
}
|
java
|
public boolean matches(Evidence evidence) {
return sourceMatches(evidence)
&& confidenceMatches(evidence)
&& name.equalsIgnoreCase(evidence.getName())
&& valueMatches(evidence);
}
|
[
"public",
"boolean",
"matches",
"(",
"Evidence",
"evidence",
")",
"{",
"return",
"sourceMatches",
"(",
"evidence",
")",
"&&",
"confidenceMatches",
"(",
"evidence",
")",
"&&",
"name",
".",
"equalsIgnoreCase",
"(",
"evidence",
".",
"getName",
"(",
")",
")",
"&&",
"valueMatches",
"(",
"evidence",
")",
";",
"}"
] |
Tests whether the given Evidence matches this EvidenceMatcher.
@param evidence the evidence to match
@return whether the evidence matches this matcher
|
[
"Tests",
"whether",
"the",
"given",
"Evidence",
"matches",
"this",
"EvidenceMatcher",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/xml/hints/EvidenceMatcher.java#L91-L96
|
17,953
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/reporting/ReportTool.java
|
ReportTool.identifierToSuppressionId
|
public String identifierToSuppressionId(Identifier id) {
if (id instanceof PurlIdentifier) {
final PurlIdentifier purl = (PurlIdentifier) id;
return purl.toGav();
} else if (id instanceof CpeIdentifier) {
try {
final CpeIdentifier cpeId = (CpeIdentifier) id;
final Cpe cpe = cpeId.getCpe();
return String.format("cpe:/%s:%s:%s", Convert.wellFormedToCpeUri(cpe.getPart()),
Convert.wellFormedToCpeUri(cpe.getWellFormedVendor()),
Convert.wellFormedToCpeUri(cpe.getWellFormedProduct()));
} catch (CpeEncodingException ex) {
LOGGER.debug("Unable to convert to cpe URI", ex);
}
} else if (id instanceof GenericIdentifier) {
return id.getValue();
}
return null;
}
|
java
|
public String identifierToSuppressionId(Identifier id) {
if (id instanceof PurlIdentifier) {
final PurlIdentifier purl = (PurlIdentifier) id;
return purl.toGav();
} else if (id instanceof CpeIdentifier) {
try {
final CpeIdentifier cpeId = (CpeIdentifier) id;
final Cpe cpe = cpeId.getCpe();
return String.format("cpe:/%s:%s:%s", Convert.wellFormedToCpeUri(cpe.getPart()),
Convert.wellFormedToCpeUri(cpe.getWellFormedVendor()),
Convert.wellFormedToCpeUri(cpe.getWellFormedProduct()));
} catch (CpeEncodingException ex) {
LOGGER.debug("Unable to convert to cpe URI", ex);
}
} else if (id instanceof GenericIdentifier) {
return id.getValue();
}
return null;
}
|
[
"public",
"String",
"identifierToSuppressionId",
"(",
"Identifier",
"id",
")",
"{",
"if",
"(",
"id",
"instanceof",
"PurlIdentifier",
")",
"{",
"final",
"PurlIdentifier",
"purl",
"=",
"(",
"PurlIdentifier",
")",
"id",
";",
"return",
"purl",
".",
"toGav",
"(",
")",
";",
"}",
"else",
"if",
"(",
"id",
"instanceof",
"CpeIdentifier",
")",
"{",
"try",
"{",
"final",
"CpeIdentifier",
"cpeId",
"=",
"(",
"CpeIdentifier",
")",
"id",
";",
"final",
"Cpe",
"cpe",
"=",
"cpeId",
".",
"getCpe",
"(",
")",
";",
"return",
"String",
".",
"format",
"(",
"\"cpe:/%s:%s:%s\"",
",",
"Convert",
".",
"wellFormedToCpeUri",
"(",
"cpe",
".",
"getPart",
"(",
")",
")",
",",
"Convert",
".",
"wellFormedToCpeUri",
"(",
"cpe",
".",
"getWellFormedVendor",
"(",
")",
")",
",",
"Convert",
".",
"wellFormedToCpeUri",
"(",
"cpe",
".",
"getWellFormedProduct",
"(",
")",
")",
")",
";",
"}",
"catch",
"(",
"CpeEncodingException",
"ex",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"Unable to convert to cpe URI\"",
",",
"ex",
")",
";",
"}",
"}",
"else",
"if",
"(",
"id",
"instanceof",
"GenericIdentifier",
")",
"{",
"return",
"id",
".",
"getValue",
"(",
")",
";",
"}",
"return",
"null",
";",
"}"
] |
Converts an identifier into the Suppression string when possible.
@param id the Identifier to format
@return the formatted suppression string when possible; otherwise
<code>null</code>.
|
[
"Converts",
"an",
"identifier",
"into",
"the",
"Suppression",
"string",
"when",
"possible",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/reporting/ReportTool.java#L49-L67
|
17,954
|
jeremylong/DependencyCheck
|
utils/src/main/java/org/owasp/dependencycheck/utils/search/FileContentSearch.java
|
FileContentSearch.contains
|
public static boolean contains(File file, String pattern) throws IOException {
try (Scanner fileScanner = new Scanner(file, UTF_8)) {
final Pattern regex = Pattern.compile(pattern);
if (fileScanner.findWithinHorizon(regex, 0) != null) {
return true;
}
}
return false;
}
|
java
|
public static boolean contains(File file, String pattern) throws IOException {
try (Scanner fileScanner = new Scanner(file, UTF_8)) {
final Pattern regex = Pattern.compile(pattern);
if (fileScanner.findWithinHorizon(regex, 0) != null) {
return true;
}
}
return false;
}
|
[
"public",
"static",
"boolean",
"contains",
"(",
"File",
"file",
",",
"String",
"pattern",
")",
"throws",
"IOException",
"{",
"try",
"(",
"Scanner",
"fileScanner",
"=",
"new",
"Scanner",
"(",
"file",
",",
"UTF_8",
")",
")",
"{",
"final",
"Pattern",
"regex",
"=",
"Pattern",
".",
"compile",
"(",
"pattern",
")",
";",
"if",
"(",
"fileScanner",
".",
"findWithinHorizon",
"(",
"regex",
",",
"0",
")",
"!=",
"null",
")",
"{",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}"
] |
Determines if the given file contains the given regular expression.
@param file the file to test
@param pattern the pattern used to test the file
@return <code>true</code> if the regular expression matches the file
content; otherwise <code>false</code>
@throws java.io.IOException thrown if there is an error reading the file
|
[
"Determines",
"if",
"the",
"given",
"file",
"contains",
"the",
"given",
"regular",
"expression",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/utils/src/main/java/org/owasp/dependencycheck/utils/search/FileContentSearch.java#L52-L60
|
17,955
|
jeremylong/DependencyCheck
|
utils/src/main/java/org/owasp/dependencycheck/utils/search/FileContentSearch.java
|
FileContentSearch.contains
|
public static boolean contains(File file, String[] patterns) throws IOException {
final List<Pattern> regexes = new ArrayList<>();
for (String pattern : patterns) {
regexes.add(Pattern.compile(pattern));
}
try (Scanner fileScanner = new Scanner(file, UTF_8)) {
return regexes.stream().anyMatch((regex) -> (fileScanner.findWithinHorizon(regex, 0) != null));
}
}
|
java
|
public static boolean contains(File file, String[] patterns) throws IOException {
final List<Pattern> regexes = new ArrayList<>();
for (String pattern : patterns) {
regexes.add(Pattern.compile(pattern));
}
try (Scanner fileScanner = new Scanner(file, UTF_8)) {
return regexes.stream().anyMatch((regex) -> (fileScanner.findWithinHorizon(regex, 0) != null));
}
}
|
[
"public",
"static",
"boolean",
"contains",
"(",
"File",
"file",
",",
"String",
"[",
"]",
"patterns",
")",
"throws",
"IOException",
"{",
"final",
"List",
"<",
"Pattern",
">",
"regexes",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"for",
"(",
"String",
"pattern",
":",
"patterns",
")",
"{",
"regexes",
".",
"add",
"(",
"Pattern",
".",
"compile",
"(",
"pattern",
")",
")",
";",
"}",
"try",
"(",
"Scanner",
"fileScanner",
"=",
"new",
"Scanner",
"(",
"file",
",",
"UTF_8",
")",
")",
"{",
"return",
"regexes",
".",
"stream",
"(",
")",
".",
"anyMatch",
"(",
"(",
"regex",
")",
"-",
">",
"(",
"fileScanner",
".",
"findWithinHorizon",
"(",
"regex",
",",
"0",
")",
"!=",
"null",
")",
")",
";",
"}",
"}"
] |
Determines if the given file contains the given regular expressions.
@param file the file to test
@param patterns the array of patterns used to test the file
@return <code>true</code> if one of the regular expressions matches the
file content; otherwise <code>false</code>
@throws java.io.IOException thrown if there is an error reading the file
|
[
"Determines",
"if",
"the",
"given",
"file",
"contains",
"the",
"given",
"regular",
"expressions",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/utils/src/main/java/org/owasp/dependencycheck/utils/search/FileContentSearch.java#L71-L79
|
17,956
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/analyzer/FalsePositiveAnalyzer.java
|
FalsePositiveAnalyzer.removeBadSpringMatches
|
private void removeBadSpringMatches(Dependency dependency) {
String mustContain = null;
for (Identifier i : dependency.getSoftwareIdentifiers()) {
if (i.getValue() != null && i.getValue().startsWith("org.springframework.")) {
final int endPoint = i.getValue().indexOf(':', 19);
if (endPoint >= 0) {
mustContain = i.getValue().substring(19, endPoint).toLowerCase();
break;
}
}
}
if (mustContain != null) {
final Set<Identifier> removalSet = new HashSet<>();
for (Identifier i : dependency.getVulnerableSoftwareIdentifiers()) {
if (i.getValue() != null
&& i.getValue().startsWith("cpe:/a:springsource:")
&& !i.getValue().toLowerCase().contains(mustContain)) {
removalSet.add(i);
}
}
removalSet.forEach((i) -> {
dependency.removeVulnerableSoftwareIdentifier(i);
});
}
|
java
|
private void removeBadSpringMatches(Dependency dependency) {
String mustContain = null;
for (Identifier i : dependency.getSoftwareIdentifiers()) {
if (i.getValue() != null && i.getValue().startsWith("org.springframework.")) {
final int endPoint = i.getValue().indexOf(':', 19);
if (endPoint >= 0) {
mustContain = i.getValue().substring(19, endPoint).toLowerCase();
break;
}
}
}
if (mustContain != null) {
final Set<Identifier> removalSet = new HashSet<>();
for (Identifier i : dependency.getVulnerableSoftwareIdentifiers()) {
if (i.getValue() != null
&& i.getValue().startsWith("cpe:/a:springsource:")
&& !i.getValue().toLowerCase().contains(mustContain)) {
removalSet.add(i);
}
}
removalSet.forEach((i) -> {
dependency.removeVulnerableSoftwareIdentifier(i);
});
}
|
[
"private",
"void",
"removeBadSpringMatches",
"(",
"Dependency",
"dependency",
")",
"{",
"String",
"mustContain",
"=",
"null",
";",
"for",
"(",
"Identifier",
"i",
":",
"dependency",
".",
"getSoftwareIdentifiers",
"(",
")",
")",
"{",
"if",
"(",
"i",
".",
"getValue",
"(",
")",
"!=",
"null",
"&&",
"i",
".",
"getValue",
"(",
")",
".",
"startsWith",
"(",
"\"org.springframework.\"",
")",
")",
"{",
"final",
"int",
"endPoint",
"=",
"i",
".",
"getValue",
"(",
")",
".",
"indexOf",
"(",
"'",
"'",
",",
"19",
")",
";",
"if",
"(",
"endPoint",
">=",
"0",
")",
"{",
"mustContain",
"=",
"i",
".",
"getValue",
"(",
")",
".",
"substring",
"(",
"19",
",",
"endPoint",
")",
".",
"toLowerCase",
"(",
")",
";",
"break",
";",
"}",
"}",
"}",
"if",
"(",
"mustContain",
"!=",
"null",
")",
"{",
"final",
"Set",
"<",
"Identifier",
">",
"removalSet",
"=",
"new",
"HashSet",
"<>",
"(",
")",
";",
"for",
"(",
"Identifier",
"i",
":",
"dependency",
".",
"getVulnerableSoftwareIdentifiers",
"(",
")",
")",
"{",
"if",
"(",
"i",
".",
"getValue",
"(",
")",
"!=",
"null",
"&&",
"i",
".",
"getValue",
"(",
")",
".",
"startsWith",
"(",
"\"cpe:/a:springsource:\"",
")",
"&&",
"!",
"i",
".",
"getValue",
"(",
")",
".",
"toLowerCase",
"(",
")",
".",
"contains",
"(",
"mustContain",
")",
")",
"{",
"removalSet",
".",
"add",
"(",
"i",
")",
";",
"}",
"}",
"removalSet",
".",
"forEach",
"(",
"(",
"i",
")",
"-",
">",
"{",
"dependency",
".",
"removeVulnerableSoftwareIdentifier",
"(",
"i",
")",
"",
";",
"}",
")",
";",
"}"
] |
Removes inaccurate matches on springframework CPEs.
@param dependency the dependency to test for and remove known inaccurate
CPE matches
|
[
"Removes",
"inaccurate",
"matches",
"on",
"springframework",
"CPEs",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/analyzer/FalsePositiveAnalyzer.java#L153-L176
|
17,957
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/analyzer/NodePackageAnalyzer.java
|
NodePackageAnalyzer.prepareFileTypeAnalyzer
|
@Override
protected void prepareFileTypeAnalyzer(Engine engine) throws InitializationException {
if (engine.getMode() != Mode.EVIDENCE_COLLECTION) {
try {
final Settings settings = engine.getSettings();
final String[] tmp = settings.getArray(Settings.KEYS.ECOSYSTEM_SKIP_CPEANALYZER);
if (tmp != null) {
final List<String> skipEcosystems = Arrays.asList(tmp);
if (skipEcosystems.contains(DEPENDENCY_ECOSYSTEM)
&& !settings.getBoolean(Settings.KEYS.ANALYZER_NODE_AUDIT_ENABLED)) {
LOGGER.debug("NodePackageAnalyzer enabled without a corresponding vulnerability analyzer");
final String msg = "Invalid Configuration: enabling the Node Package Analyzer without "
+ "using the Node Audit Analyzer is not supported.";
throw new InitializationException(msg);
} else if (!skipEcosystems.contains(DEPENDENCY_ECOSYSTEM)) {
LOGGER.warn("Using the CPE Analyzer with Node.js can result in many false positives.");
}
}
} catch (InvalidSettingException ex) {
throw new InitializationException("Unable to read configuration settings", ex);
}
}
}
|
java
|
@Override
protected void prepareFileTypeAnalyzer(Engine engine) throws InitializationException {
if (engine.getMode() != Mode.EVIDENCE_COLLECTION) {
try {
final Settings settings = engine.getSettings();
final String[] tmp = settings.getArray(Settings.KEYS.ECOSYSTEM_SKIP_CPEANALYZER);
if (tmp != null) {
final List<String> skipEcosystems = Arrays.asList(tmp);
if (skipEcosystems.contains(DEPENDENCY_ECOSYSTEM)
&& !settings.getBoolean(Settings.KEYS.ANALYZER_NODE_AUDIT_ENABLED)) {
LOGGER.debug("NodePackageAnalyzer enabled without a corresponding vulnerability analyzer");
final String msg = "Invalid Configuration: enabling the Node Package Analyzer without "
+ "using the Node Audit Analyzer is not supported.";
throw new InitializationException(msg);
} else if (!skipEcosystems.contains(DEPENDENCY_ECOSYSTEM)) {
LOGGER.warn("Using the CPE Analyzer with Node.js can result in many false positives.");
}
}
} catch (InvalidSettingException ex) {
throw new InitializationException("Unable to read configuration settings", ex);
}
}
}
|
[
"@",
"Override",
"protected",
"void",
"prepareFileTypeAnalyzer",
"(",
"Engine",
"engine",
")",
"throws",
"InitializationException",
"{",
"if",
"(",
"engine",
".",
"getMode",
"(",
")",
"!=",
"Mode",
".",
"EVIDENCE_COLLECTION",
")",
"{",
"try",
"{",
"final",
"Settings",
"settings",
"=",
"engine",
".",
"getSettings",
"(",
")",
";",
"final",
"String",
"[",
"]",
"tmp",
"=",
"settings",
".",
"getArray",
"(",
"Settings",
".",
"KEYS",
".",
"ECOSYSTEM_SKIP_CPEANALYZER",
")",
";",
"if",
"(",
"tmp",
"!=",
"null",
")",
"{",
"final",
"List",
"<",
"String",
">",
"skipEcosystems",
"=",
"Arrays",
".",
"asList",
"(",
"tmp",
")",
";",
"if",
"(",
"skipEcosystems",
".",
"contains",
"(",
"DEPENDENCY_ECOSYSTEM",
")",
"&&",
"!",
"settings",
".",
"getBoolean",
"(",
"Settings",
".",
"KEYS",
".",
"ANALYZER_NODE_AUDIT_ENABLED",
")",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"NodePackageAnalyzer enabled without a corresponding vulnerability analyzer\"",
")",
";",
"final",
"String",
"msg",
"=",
"\"Invalid Configuration: enabling the Node Package Analyzer without \"",
"+",
"\"using the Node Audit Analyzer is not supported.\"",
";",
"throw",
"new",
"InitializationException",
"(",
"msg",
")",
";",
"}",
"else",
"if",
"(",
"!",
"skipEcosystems",
".",
"contains",
"(",
"DEPENDENCY_ECOSYSTEM",
")",
")",
"{",
"LOGGER",
".",
"warn",
"(",
"\"Using the CPE Analyzer with Node.js can result in many false positives.\"",
")",
";",
"}",
"}",
"}",
"catch",
"(",
"InvalidSettingException",
"ex",
")",
"{",
"throw",
"new",
"InitializationException",
"(",
"\"Unable to read configuration settings\"",
",",
"ex",
")",
";",
"}",
"}",
"}"
] |
Performs validation on the configuration to ensure that the correct
analyzers are in place.
@param engine the dependency-check engine
@throws InitializationException thrown if there is a configuration error
|
[
"Performs",
"validation",
"on",
"the",
"configuration",
"to",
"ensure",
"that",
"the",
"correct",
"analyzers",
"are",
"in",
"place",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/analyzer/NodePackageAnalyzer.java#L111-L133
|
17,958
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/analyzer/NodePackageAnalyzer.java
|
NodePackageAnalyzer.isNodeAuditEnabled
|
private boolean isNodeAuditEnabled(Engine engine) {
for (Analyzer a : engine.getAnalyzers()) {
if (a instanceof NodeAuditAnalyzer) {
return a.isEnabled();
}
}
return false;
}
|
java
|
private boolean isNodeAuditEnabled(Engine engine) {
for (Analyzer a : engine.getAnalyzers()) {
if (a instanceof NodeAuditAnalyzer) {
return a.isEnabled();
}
}
return false;
}
|
[
"private",
"boolean",
"isNodeAuditEnabled",
"(",
"Engine",
"engine",
")",
"{",
"for",
"(",
"Analyzer",
"a",
":",
"engine",
".",
"getAnalyzers",
"(",
")",
")",
"{",
"if",
"(",
"a",
"instanceof",
"NodeAuditAnalyzer",
")",
"{",
"return",
"a",
".",
"isEnabled",
"(",
")",
";",
"}",
"}",
"return",
"false",
";",
"}"
] |
Determines if the Node Audit analyzer is enabled.
@param engine a reference to the dependency-check engine
@return <code>true</code> if the Node Audit Analyzer is enabled;
otherwise <code>false</code>
|
[
"Determines",
"if",
"the",
"Node",
"Audit",
"analyzer",
"is",
"enabled",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/analyzer/NodePackageAnalyzer.java#L173-L180
|
17,959
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/dependency/naming/GenericIdentifier.java
|
GenericIdentifier.compareTo
|
@Override
public int compareTo(Identifier o) {
if (o == null) {
throw new IllegalArgumentException("Unable to compare a null identifier");
}
return new CompareToBuilder()
.append(this.value, o.toString())
.append(this.url, o.getUrl())
.append(this.confidence, o.getConfidence())
.toComparison();
}
|
java
|
@Override
public int compareTo(Identifier o) {
if (o == null) {
throw new IllegalArgumentException("Unable to compare a null identifier");
}
return new CompareToBuilder()
.append(this.value, o.toString())
.append(this.url, o.getUrl())
.append(this.confidence, o.getConfidence())
.toComparison();
}
|
[
"@",
"Override",
"public",
"int",
"compareTo",
"(",
"Identifier",
"o",
")",
"{",
"if",
"(",
"o",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Unable to compare a null identifier\"",
")",
";",
"}",
"return",
"new",
"CompareToBuilder",
"(",
")",
".",
"append",
"(",
"this",
".",
"value",
",",
"o",
".",
"toString",
"(",
")",
")",
".",
"append",
"(",
"this",
".",
"url",
",",
"o",
".",
"getUrl",
"(",
")",
")",
".",
"append",
"(",
"this",
".",
"confidence",
",",
"o",
".",
"getConfidence",
"(",
")",
")",
".",
"toComparison",
"(",
")",
";",
"}"
] |
Implementation of the comparator interface.
@param o the object being compared
@return an integer indicating the ordering
|
[
"Implementation",
"of",
"the",
"comparator",
"interface",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/dependency/naming/GenericIdentifier.java#L188-L198
|
17,960
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/analyzer/AssemblyAnalyzer.java
|
AssemblyAnalyzer.buildArgumentList
|
protected List<String> buildArgumentList() {
// Use file.separator as a wild guess as to whether this is Windows
final List<String> args = new ArrayList<>();
if (!StringUtils.isEmpty(getSettings().getString(Settings.KEYS.ANALYZER_ASSEMBLY_DOTNET_PATH))) {
args.add(getSettings().getString(Settings.KEYS.ANALYZER_ASSEMBLY_DOTNET_PATH));
} else if (isDotnetPath()) {
args.add("dotnet");
} else {
return null;
}
args.add(grokAssembly.getPath());
return args;
}
|
java
|
protected List<String> buildArgumentList() {
// Use file.separator as a wild guess as to whether this is Windows
final List<String> args = new ArrayList<>();
if (!StringUtils.isEmpty(getSettings().getString(Settings.KEYS.ANALYZER_ASSEMBLY_DOTNET_PATH))) {
args.add(getSettings().getString(Settings.KEYS.ANALYZER_ASSEMBLY_DOTNET_PATH));
} else if (isDotnetPath()) {
args.add("dotnet");
} else {
return null;
}
args.add(grokAssembly.getPath());
return args;
}
|
[
"protected",
"List",
"<",
"String",
">",
"buildArgumentList",
"(",
")",
"{",
"// Use file.separator as a wild guess as to whether this is Windows",
"final",
"List",
"<",
"String",
">",
"args",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"if",
"(",
"!",
"StringUtils",
".",
"isEmpty",
"(",
"getSettings",
"(",
")",
".",
"getString",
"(",
"Settings",
".",
"KEYS",
".",
"ANALYZER_ASSEMBLY_DOTNET_PATH",
")",
")",
")",
"{",
"args",
".",
"add",
"(",
"getSettings",
"(",
")",
".",
"getString",
"(",
"Settings",
".",
"KEYS",
".",
"ANALYZER_ASSEMBLY_DOTNET_PATH",
")",
")",
";",
"}",
"else",
"if",
"(",
"isDotnetPath",
"(",
")",
")",
"{",
"args",
".",
"add",
"(",
"\"dotnet\"",
")",
";",
"}",
"else",
"{",
"return",
"null",
";",
"}",
"args",
".",
"add",
"(",
"grokAssembly",
".",
"getPath",
"(",
")",
")",
";",
"return",
"args",
";",
"}"
] |
Builds the beginnings of a List for ProcessBuilder
@return the list of arguments to begin populating the ProcessBuilder
|
[
"Builds",
"the",
"beginnings",
"of",
"a",
"List",
"for",
"ProcessBuilder"
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/analyzer/AssemblyAnalyzer.java#L105-L117
|
17,961
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/analyzer/AssemblyAnalyzer.java
|
AssemblyAnalyzer.prepareFileTypeAnalyzer
|
@Override
public void prepareFileTypeAnalyzer(Engine engine) throws InitializationException {
final File location;
try (InputStream in = FileUtils.getResourceAsStream("GrokAssembly.zip")) {
if (in == null) {
throw new InitializationException("Unable to extract GrokAssembly.dll - file not found");
}
location = FileUtils.createTempDirectory(getSettings().getTempDirectory());
ExtractionUtil.extractFiles(in, location);
} catch (ExtractionException ex) {
throw new InitializationException("Unable to extract GrokAssembly.dll", ex);
} catch (IOException ex) {
throw new InitializationException("Unable to create temp directory for GrokAssembly", ex);
}
grokAssembly = new File(location, "GrokAssembly.dll");
// Now, need to see if GrokAssembly actually runs from this location.
baseArgumentList = buildArgumentList();
//TODO this creates an "unreported" error - if someone doesn't look
// at the command output this could easily be missed (especially in an
// Ant or Maven build.
//
// We need to create a non-fatal warning error type that will
// get added to the report.
//TODO this idea needs to get replicated to the bundle audit analyzer.
if (baseArgumentList == null) {
setEnabled(false);
LOGGER.error("----------------------------------------------------");
LOGGER.error(".NET Assembly Analyzer could not be initialized and at least one "
+ "'exe' or 'dll' was scanned. The 'dotnet' executable could not be found on "
+ "the path; either disable the Assembly Analyzer or configure the path dotnet core.");
LOGGER.error("----------------------------------------------------");
return;
}
try {
final ProcessBuilder pb = new ProcessBuilder(baseArgumentList);
final Process p = pb.start();
// Try evacuating the error stream
IOUtils.copy(p.getErrorStream(), NullOutputStream.NULL_OUTPUT_STREAM);
final GrokParser grok = new GrokParser();
final AssemblyData data = grok.parse(p.getInputStream());
if (p.waitFor() != 1 || data == null || StringUtils.isEmpty(data.getError())) {
LOGGER.warn("An error occurred with the .NET AssemblyAnalyzer, please see the log for more details.");
LOGGER.debug("GrokAssembly.dll is not working properly");
grokAssembly = null;
setEnabled(false);
throw new InitializationException("Could not execute .NET AssemblyAnalyzer");
}
} catch (InitializationException e) {
setEnabled(false);
throw e;
} catch (IOException | InterruptedException e) {
LOGGER.warn("An error occurred with the .NET AssemblyAnalyzer;\n"
+ "this can be ignored unless you are scanning .NET DLLs. Please see the log for more details.");
LOGGER.debug("Could not execute GrokAssembly {}", e.getMessage());
setEnabled(false);
throw new InitializationException("An error occurred with the .NET AssemblyAnalyzer", e);
}
}
|
java
|
@Override
public void prepareFileTypeAnalyzer(Engine engine) throws InitializationException {
final File location;
try (InputStream in = FileUtils.getResourceAsStream("GrokAssembly.zip")) {
if (in == null) {
throw new InitializationException("Unable to extract GrokAssembly.dll - file not found");
}
location = FileUtils.createTempDirectory(getSettings().getTempDirectory());
ExtractionUtil.extractFiles(in, location);
} catch (ExtractionException ex) {
throw new InitializationException("Unable to extract GrokAssembly.dll", ex);
} catch (IOException ex) {
throw new InitializationException("Unable to create temp directory for GrokAssembly", ex);
}
grokAssembly = new File(location, "GrokAssembly.dll");
// Now, need to see if GrokAssembly actually runs from this location.
baseArgumentList = buildArgumentList();
//TODO this creates an "unreported" error - if someone doesn't look
// at the command output this could easily be missed (especially in an
// Ant or Maven build.
//
// We need to create a non-fatal warning error type that will
// get added to the report.
//TODO this idea needs to get replicated to the bundle audit analyzer.
if (baseArgumentList == null) {
setEnabled(false);
LOGGER.error("----------------------------------------------------");
LOGGER.error(".NET Assembly Analyzer could not be initialized and at least one "
+ "'exe' or 'dll' was scanned. The 'dotnet' executable could not be found on "
+ "the path; either disable the Assembly Analyzer or configure the path dotnet core.");
LOGGER.error("----------------------------------------------------");
return;
}
try {
final ProcessBuilder pb = new ProcessBuilder(baseArgumentList);
final Process p = pb.start();
// Try evacuating the error stream
IOUtils.copy(p.getErrorStream(), NullOutputStream.NULL_OUTPUT_STREAM);
final GrokParser grok = new GrokParser();
final AssemblyData data = grok.parse(p.getInputStream());
if (p.waitFor() != 1 || data == null || StringUtils.isEmpty(data.getError())) {
LOGGER.warn("An error occurred with the .NET AssemblyAnalyzer, please see the log for more details.");
LOGGER.debug("GrokAssembly.dll is not working properly");
grokAssembly = null;
setEnabled(false);
throw new InitializationException("Could not execute .NET AssemblyAnalyzer");
}
} catch (InitializationException e) {
setEnabled(false);
throw e;
} catch (IOException | InterruptedException e) {
LOGGER.warn("An error occurred with the .NET AssemblyAnalyzer;\n"
+ "this can be ignored unless you are scanning .NET DLLs. Please see the log for more details.");
LOGGER.debug("Could not execute GrokAssembly {}", e.getMessage());
setEnabled(false);
throw new InitializationException("An error occurred with the .NET AssemblyAnalyzer", e);
}
}
|
[
"@",
"Override",
"public",
"void",
"prepareFileTypeAnalyzer",
"(",
"Engine",
"engine",
")",
"throws",
"InitializationException",
"{",
"final",
"File",
"location",
";",
"try",
"(",
"InputStream",
"in",
"=",
"FileUtils",
".",
"getResourceAsStream",
"(",
"\"GrokAssembly.zip\"",
")",
")",
"{",
"if",
"(",
"in",
"==",
"null",
")",
"{",
"throw",
"new",
"InitializationException",
"(",
"\"Unable to extract GrokAssembly.dll - file not found\"",
")",
";",
"}",
"location",
"=",
"FileUtils",
".",
"createTempDirectory",
"(",
"getSettings",
"(",
")",
".",
"getTempDirectory",
"(",
")",
")",
";",
"ExtractionUtil",
".",
"extractFiles",
"(",
"in",
",",
"location",
")",
";",
"}",
"catch",
"(",
"ExtractionException",
"ex",
")",
"{",
"throw",
"new",
"InitializationException",
"(",
"\"Unable to extract GrokAssembly.dll\"",
",",
"ex",
")",
";",
"}",
"catch",
"(",
"IOException",
"ex",
")",
"{",
"throw",
"new",
"InitializationException",
"(",
"\"Unable to create temp directory for GrokAssembly\"",
",",
"ex",
")",
";",
"}",
"grokAssembly",
"=",
"new",
"File",
"(",
"location",
",",
"\"GrokAssembly.dll\"",
")",
";",
"// Now, need to see if GrokAssembly actually runs from this location.",
"baseArgumentList",
"=",
"buildArgumentList",
"(",
")",
";",
"//TODO this creates an \"unreported\" error - if someone doesn't look",
"// at the command output this could easily be missed (especially in an",
"// Ant or Maven build.",
"//",
"// We need to create a non-fatal warning error type that will",
"// get added to the report.",
"//TODO this idea needs to get replicated to the bundle audit analyzer.",
"if",
"(",
"baseArgumentList",
"==",
"null",
")",
"{",
"setEnabled",
"(",
"false",
")",
";",
"LOGGER",
".",
"error",
"(",
"\"----------------------------------------------------\"",
")",
";",
"LOGGER",
".",
"error",
"(",
"\".NET Assembly Analyzer could not be initialized and at least one \"",
"+",
"\"'exe' or 'dll' was scanned. The 'dotnet' executable could not be found on \"",
"+",
"\"the path; either disable the Assembly Analyzer or configure the path dotnet core.\"",
")",
";",
"LOGGER",
".",
"error",
"(",
"\"----------------------------------------------------\"",
")",
";",
"return",
";",
"}",
"try",
"{",
"final",
"ProcessBuilder",
"pb",
"=",
"new",
"ProcessBuilder",
"(",
"baseArgumentList",
")",
";",
"final",
"Process",
"p",
"=",
"pb",
".",
"start",
"(",
")",
";",
"// Try evacuating the error stream",
"IOUtils",
".",
"copy",
"(",
"p",
".",
"getErrorStream",
"(",
")",
",",
"NullOutputStream",
".",
"NULL_OUTPUT_STREAM",
")",
";",
"final",
"GrokParser",
"grok",
"=",
"new",
"GrokParser",
"(",
")",
";",
"final",
"AssemblyData",
"data",
"=",
"grok",
".",
"parse",
"(",
"p",
".",
"getInputStream",
"(",
")",
")",
";",
"if",
"(",
"p",
".",
"waitFor",
"(",
")",
"!=",
"1",
"||",
"data",
"==",
"null",
"||",
"StringUtils",
".",
"isEmpty",
"(",
"data",
".",
"getError",
"(",
")",
")",
")",
"{",
"LOGGER",
".",
"warn",
"(",
"\"An error occurred with the .NET AssemblyAnalyzer, please see the log for more details.\"",
")",
";",
"LOGGER",
".",
"debug",
"(",
"\"GrokAssembly.dll is not working properly\"",
")",
";",
"grokAssembly",
"=",
"null",
";",
"setEnabled",
"(",
"false",
")",
";",
"throw",
"new",
"InitializationException",
"(",
"\"Could not execute .NET AssemblyAnalyzer\"",
")",
";",
"}",
"}",
"catch",
"(",
"InitializationException",
"e",
")",
"{",
"setEnabled",
"(",
"false",
")",
";",
"throw",
"e",
";",
"}",
"catch",
"(",
"IOException",
"|",
"InterruptedException",
"e",
")",
"{",
"LOGGER",
".",
"warn",
"(",
"\"An error occurred with the .NET AssemblyAnalyzer;\\n\"",
"+",
"\"this can be ignored unless you are scanning .NET DLLs. Please see the log for more details.\"",
")",
";",
"LOGGER",
".",
"debug",
"(",
"\"Could not execute GrokAssembly {}\"",
",",
"e",
".",
"getMessage",
"(",
")",
")",
";",
"setEnabled",
"(",
"false",
")",
";",
"throw",
"new",
"InitializationException",
"(",
"\"An error occurred with the .NET AssemblyAnalyzer\"",
",",
"e",
")",
";",
"}",
"}"
] |
Initialize the analyzer. In this case, extract GrokAssembly.dll to a
temporary location.
@param engine a reference to the dependency-check engine
@throws InitializationException thrown if anything goes wrong
|
[
"Initialize",
"the",
"analyzer",
".",
"In",
"this",
"case",
"extract",
"GrokAssembly",
".",
"dll",
"to",
"a",
"temporary",
"location",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/analyzer/AssemblyAnalyzer.java#L330-L390
|
17,962
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/analyzer/AssemblyAnalyzer.java
|
AssemblyAnalyzer.isDotnetPath
|
private boolean isDotnetPath() {
final String[] args = new String[2];
args[0] = "dotnet";
args[1] = "--version";
final ProcessBuilder pb = new ProcessBuilder(args);
try {
final Process proc = pb.start();
final int retCode = proc.waitFor();
if (retCode == 0) {
return true;
}
final byte[] version = new byte[50];
final int read = proc.getInputStream().read(version);
if (read > 0) {
final String v = new String(version, UTF_8);
if (v.length() > 0) {
return true;
}
}
} catch (IOException | InterruptedException ex) {
LOGGER.debug("Path search failed for dotnet", ex);
}
return false;
}
|
java
|
private boolean isDotnetPath() {
final String[] args = new String[2];
args[0] = "dotnet";
args[1] = "--version";
final ProcessBuilder pb = new ProcessBuilder(args);
try {
final Process proc = pb.start();
final int retCode = proc.waitFor();
if (retCode == 0) {
return true;
}
final byte[] version = new byte[50];
final int read = proc.getInputStream().read(version);
if (read > 0) {
final String v = new String(version, UTF_8);
if (v.length() > 0) {
return true;
}
}
} catch (IOException | InterruptedException ex) {
LOGGER.debug("Path search failed for dotnet", ex);
}
return false;
}
|
[
"private",
"boolean",
"isDotnetPath",
"(",
")",
"{",
"final",
"String",
"[",
"]",
"args",
"=",
"new",
"String",
"[",
"2",
"]",
";",
"args",
"[",
"0",
"]",
"=",
"\"dotnet\"",
";",
"args",
"[",
"1",
"]",
"=",
"\"--version\"",
";",
"final",
"ProcessBuilder",
"pb",
"=",
"new",
"ProcessBuilder",
"(",
"args",
")",
";",
"try",
"{",
"final",
"Process",
"proc",
"=",
"pb",
".",
"start",
"(",
")",
";",
"final",
"int",
"retCode",
"=",
"proc",
".",
"waitFor",
"(",
")",
";",
"if",
"(",
"retCode",
"==",
"0",
")",
"{",
"return",
"true",
";",
"}",
"final",
"byte",
"[",
"]",
"version",
"=",
"new",
"byte",
"[",
"50",
"]",
";",
"final",
"int",
"read",
"=",
"proc",
".",
"getInputStream",
"(",
")",
".",
"read",
"(",
"version",
")",
";",
"if",
"(",
"read",
">",
"0",
")",
"{",
"final",
"String",
"v",
"=",
"new",
"String",
"(",
"version",
",",
"UTF_8",
")",
";",
"if",
"(",
"v",
".",
"length",
"(",
")",
">",
"0",
")",
"{",
"return",
"true",
";",
"}",
"}",
"}",
"catch",
"(",
"IOException",
"|",
"InterruptedException",
"ex",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"Path search failed for dotnet\"",
",",
"ex",
")",
";",
"}",
"return",
"false",
";",
"}"
] |
Tests to see if a file is in the system path.
@return <code>true</code> if dotnet could be found in the path; otherwise
<code>false</code>
|
[
"Tests",
"to",
"see",
"if",
"a",
"file",
"is",
"in",
"the",
"system",
"path",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/analyzer/AssemblyAnalyzer.java#L444-L467
|
17,963
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/analyzer/AssemblyAnalyzer.java
|
AssemblyAnalyzer.addMatchingValues
|
protected static void addMatchingValues(List<String> packages, String value, Dependency dep, EvidenceType type) {
if (value == null || value.isEmpty() || packages == null || packages.isEmpty()) {
return;
}
for (String key : packages) {
final int pos = StringUtils.indexOfIgnoreCase(value, key);
if ((pos == 0 && (key.length() == value.length() || (key.length() < value.length()
&& !Character.isLetterOrDigit(value.charAt(key.length())))))
|| (pos > 0 && !Character.isLetterOrDigit(value.charAt(pos - 1))
&& (pos + key.length() == value.length() || (key.length() < value.length()
&& !Character.isLetterOrDigit(value.charAt(pos + key.length())))))) {
dep.addEvidence(type, "dll", "namespace", key, Confidence.HIGHEST);
}
}
}
|
java
|
protected static void addMatchingValues(List<String> packages, String value, Dependency dep, EvidenceType type) {
if (value == null || value.isEmpty() || packages == null || packages.isEmpty()) {
return;
}
for (String key : packages) {
final int pos = StringUtils.indexOfIgnoreCase(value, key);
if ((pos == 0 && (key.length() == value.length() || (key.length() < value.length()
&& !Character.isLetterOrDigit(value.charAt(key.length())))))
|| (pos > 0 && !Character.isLetterOrDigit(value.charAt(pos - 1))
&& (pos + key.length() == value.length() || (key.length() < value.length()
&& !Character.isLetterOrDigit(value.charAt(pos + key.length())))))) {
dep.addEvidence(type, "dll", "namespace", key, Confidence.HIGHEST);
}
}
}
|
[
"protected",
"static",
"void",
"addMatchingValues",
"(",
"List",
"<",
"String",
">",
"packages",
",",
"String",
"value",
",",
"Dependency",
"dep",
",",
"EvidenceType",
"type",
")",
"{",
"if",
"(",
"value",
"==",
"null",
"||",
"value",
".",
"isEmpty",
"(",
")",
"||",
"packages",
"==",
"null",
"||",
"packages",
".",
"isEmpty",
"(",
")",
")",
"{",
"return",
";",
"}",
"for",
"(",
"String",
"key",
":",
"packages",
")",
"{",
"final",
"int",
"pos",
"=",
"StringUtils",
".",
"indexOfIgnoreCase",
"(",
"value",
",",
"key",
")",
";",
"if",
"(",
"(",
"pos",
"==",
"0",
"&&",
"(",
"key",
".",
"length",
"(",
")",
"==",
"value",
".",
"length",
"(",
")",
"||",
"(",
"key",
".",
"length",
"(",
")",
"<",
"value",
".",
"length",
"(",
")",
"&&",
"!",
"Character",
".",
"isLetterOrDigit",
"(",
"value",
".",
"charAt",
"(",
"key",
".",
"length",
"(",
")",
")",
")",
")",
")",
")",
"||",
"(",
"pos",
">",
"0",
"&&",
"!",
"Character",
".",
"isLetterOrDigit",
"(",
"value",
".",
"charAt",
"(",
"pos",
"-",
"1",
")",
")",
"&&",
"(",
"pos",
"+",
"key",
".",
"length",
"(",
")",
"==",
"value",
".",
"length",
"(",
")",
"||",
"(",
"key",
".",
"length",
"(",
")",
"<",
"value",
".",
"length",
"(",
")",
"&&",
"!",
"Character",
".",
"isLetterOrDigit",
"(",
"value",
".",
"charAt",
"(",
"pos",
"+",
"key",
".",
"length",
"(",
")",
")",
")",
")",
")",
")",
")",
"{",
"dep",
".",
"addEvidence",
"(",
"type",
",",
"\"dll\"",
",",
"\"namespace\"",
",",
"key",
",",
"Confidence",
".",
"HIGHEST",
")",
";",
"}",
"}",
"}"
] |
Cycles through the collection of class name information to see if parts
of the package names are contained in the provided value. If found, it
will be added as the HIGHEST confidence evidence because we have more
then one source corroborating the value.
@param packages a collection of class name information
@param value the value to check to see if it contains a package name
@param dep the dependency to add new entries too
@param type the type of evidence (vendor, product, or version)
|
[
"Cycles",
"through",
"the",
"collection",
"of",
"class",
"name",
"information",
"to",
"see",
"if",
"parts",
"of",
"the",
"package",
"names",
"are",
"contained",
"in",
"the",
"provided",
"value",
".",
"If",
"found",
"it",
"will",
"be",
"added",
"as",
"the",
"HIGHEST",
"confidence",
"evidence",
"because",
"we",
"have",
"more",
"then",
"one",
"source",
"corroborating",
"the",
"value",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/analyzer/AssemblyAnalyzer.java#L480-L495
|
17,964
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/data/update/nvd/ProcessTask.java
|
ProcessTask.call
|
@Override
public ProcessTask call() throws Exception {
try {
processFiles();
} catch (UpdateException ex) {
this.exception = ex;
} finally {
settings.cleanup(false);
}
return this;
}
|
java
|
@Override
public ProcessTask call() throws Exception {
try {
processFiles();
} catch (UpdateException ex) {
this.exception = ex;
} finally {
settings.cleanup(false);
}
return this;
}
|
[
"@",
"Override",
"public",
"ProcessTask",
"call",
"(",
")",
"throws",
"Exception",
"{",
"try",
"{",
"processFiles",
"(",
")",
";",
"}",
"catch",
"(",
"UpdateException",
"ex",
")",
"{",
"this",
".",
"exception",
"=",
"ex",
";",
"}",
"finally",
"{",
"settings",
".",
"cleanup",
"(",
"false",
")",
";",
"}",
"return",
"this",
";",
"}"
] |
Implements the callable interface.
@return this object
@throws Exception thrown if there is an exception; note that any
UpdateExceptions are simply added to the tasks exception collection
|
[
"Implements",
"the",
"callable",
"interface",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/data/update/nvd/ProcessTask.java#L110-L120
|
17,965
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/data/update/nvd/ProcessTask.java
|
ProcessTask.importJSON
|
protected void importJSON(File file) throws ParserConfigurationException,
IOException, SQLException, DatabaseException, ClassNotFoundException, UpdateException {
final NvdCveParser parser = new NvdCveParser(settings, cveDB);
parser.parse(file);
}
|
java
|
protected void importJSON(File file) throws ParserConfigurationException,
IOException, SQLException, DatabaseException, ClassNotFoundException, UpdateException {
final NvdCveParser parser = new NvdCveParser(settings, cveDB);
parser.parse(file);
}
|
[
"protected",
"void",
"importJSON",
"(",
"File",
"file",
")",
"throws",
"ParserConfigurationException",
",",
"IOException",
",",
"SQLException",
",",
"DatabaseException",
",",
"ClassNotFoundException",
",",
"UpdateException",
"{",
"final",
"NvdCveParser",
"parser",
"=",
"new",
"NvdCveParser",
"(",
"settings",
",",
"cveDB",
")",
";",
"parser",
".",
"parse",
"(",
"file",
")",
";",
"}"
] |
Imports the NVD CVE JSON File into the database.
@param file the file containing the NVD CVE JSON
@throws ParserConfigurationException is thrown if there is a parser
configuration exception
@throws IOException is thrown if there is a IO Exception
@throws SQLException is thrown if there is a SQL exception
@throws DatabaseException is thrown if there is a database exception
@throws ClassNotFoundException thrown if the h2 database driver cannot be
loaded
@throws UpdateException thrown if the file could not be found
|
[
"Imports",
"the",
"NVD",
"CVE",
"JSON",
"File",
"into",
"the",
"database",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/data/update/nvd/ProcessTask.java#L135-L140
|
17,966
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/data/update/nvd/ProcessTask.java
|
ProcessTask.processFiles
|
private void processFiles() throws UpdateException {
LOGGER.info("Processing Started for NVD CVE - {}", downloadTask.getNvdCveInfo().getId());
final long startProcessing = System.currentTimeMillis();
try {
importJSON(downloadTask.getFile());
cveDB.commit();
properties.save(downloadTask.getNvdCveInfo());
} catch (ParserConfigurationException | SQLException | DatabaseException | ClassNotFoundException | IOException ex) {
throw new UpdateException(ex);
} finally {
downloadTask.cleanup();
}
LOGGER.info("Processing Complete for NVD CVE - {} ({} ms)", downloadTask.getNvdCveInfo().getId(),
System.currentTimeMillis() - startProcessing);
}
|
java
|
private void processFiles() throws UpdateException {
LOGGER.info("Processing Started for NVD CVE - {}", downloadTask.getNvdCveInfo().getId());
final long startProcessing = System.currentTimeMillis();
try {
importJSON(downloadTask.getFile());
cveDB.commit();
properties.save(downloadTask.getNvdCveInfo());
} catch (ParserConfigurationException | SQLException | DatabaseException | ClassNotFoundException | IOException ex) {
throw new UpdateException(ex);
} finally {
downloadTask.cleanup();
}
LOGGER.info("Processing Complete for NVD CVE - {} ({} ms)", downloadTask.getNvdCveInfo().getId(),
System.currentTimeMillis() - startProcessing);
}
|
[
"private",
"void",
"processFiles",
"(",
")",
"throws",
"UpdateException",
"{",
"LOGGER",
".",
"info",
"(",
"\"Processing Started for NVD CVE - {}\"",
",",
"downloadTask",
".",
"getNvdCveInfo",
"(",
")",
".",
"getId",
"(",
")",
")",
";",
"final",
"long",
"startProcessing",
"=",
"System",
".",
"currentTimeMillis",
"(",
")",
";",
"try",
"{",
"importJSON",
"(",
"downloadTask",
".",
"getFile",
"(",
")",
")",
";",
"cveDB",
".",
"commit",
"(",
")",
";",
"properties",
".",
"save",
"(",
"downloadTask",
".",
"getNvdCveInfo",
"(",
")",
")",
";",
"}",
"catch",
"(",
"ParserConfigurationException",
"|",
"SQLException",
"|",
"DatabaseException",
"|",
"ClassNotFoundException",
"|",
"IOException",
"ex",
")",
"{",
"throw",
"new",
"UpdateException",
"(",
"ex",
")",
";",
"}",
"finally",
"{",
"downloadTask",
".",
"cleanup",
"(",
")",
";",
"}",
"LOGGER",
".",
"info",
"(",
"\"Processing Complete for NVD CVE - {} ({} ms)\"",
",",
"downloadTask",
".",
"getNvdCveInfo",
"(",
")",
".",
"getId",
"(",
")",
",",
"System",
".",
"currentTimeMillis",
"(",
")",
"-",
"startProcessing",
")",
";",
"}"
] |
Processes the NVD CVE XML file and imports the data into the DB.
@throws UpdateException thrown if there is an error loading the data into
the database
|
[
"Processes",
"the",
"NVD",
"CVE",
"XML",
"file",
"and",
"imports",
"the",
"data",
"into",
"the",
"DB",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/data/update/nvd/ProcessTask.java#L148-L162
|
17,967
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/xml/XmlInputStream.java
|
XmlInputStream.read
|
private StringBuilder read(int n) throws IOException {
// Input stream finished?
boolean eof = false;
// Read that many.
final StringBuilder s = new StringBuilder(n);
while (s.length() < n && !eof) {
// Always get from the pushBack buffer.
if (pushBack.length() == 0) {
// Read something from the stream into pushBack.
eof = readIntoPushBack();
}
// Pushback only contains deliverable codes.
if (pushBack.length() > 0) {
// Grab one character
s.append(pushBack.charAt(0));
// Remove it from pushBack
pushBack.deleteCharAt(0);
}
}
return s;
}
|
java
|
private StringBuilder read(int n) throws IOException {
// Input stream finished?
boolean eof = false;
// Read that many.
final StringBuilder s = new StringBuilder(n);
while (s.length() < n && !eof) {
// Always get from the pushBack buffer.
if (pushBack.length() == 0) {
// Read something from the stream into pushBack.
eof = readIntoPushBack();
}
// Pushback only contains deliverable codes.
if (pushBack.length() > 0) {
// Grab one character
s.append(pushBack.charAt(0));
// Remove it from pushBack
pushBack.deleteCharAt(0);
}
}
return s;
}
|
[
"private",
"StringBuilder",
"read",
"(",
"int",
"n",
")",
"throws",
"IOException",
"{",
"// Input stream finished?",
"boolean",
"eof",
"=",
"false",
";",
"// Read that many.",
"final",
"StringBuilder",
"s",
"=",
"new",
"StringBuilder",
"(",
"n",
")",
";",
"while",
"(",
"s",
".",
"length",
"(",
")",
"<",
"n",
"&&",
"!",
"eof",
")",
"{",
"// Always get from the pushBack buffer.",
"if",
"(",
"pushBack",
".",
"length",
"(",
")",
"==",
"0",
")",
"{",
"// Read something from the stream into pushBack.",
"eof",
"=",
"readIntoPushBack",
"(",
")",
";",
"}",
"// Pushback only contains deliverable codes.",
"if",
"(",
"pushBack",
".",
"length",
"(",
")",
">",
"0",
")",
"{",
"// Grab one character",
"s",
".",
"append",
"(",
"pushBack",
".",
"charAt",
"(",
"0",
")",
")",
";",
"// Remove it from pushBack",
"pushBack",
".",
"deleteCharAt",
"(",
"0",
")",
";",
"}",
"}",
"return",
"s",
";",
"}"
] |
Read n characters.
@param n the number of characters to read
@return the characters read
@throws IOException thrown when an error occurs
|
[
"Read",
"n",
"characters",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/xml/XmlInputStream.java#L86-L108
|
17,968
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/xml/XmlInputStream.java
|
XmlInputStream.readIntoPushBack
|
private boolean readIntoPushBack() throws IOException {
// File finished?
boolean eof = false;
// Next char.
final int ch = in.read();
if (ch >= 0) {
// Discard whitespace at start?
if (!(pulled == 0 && isWhiteSpace(ch))) {
// Good code.
pulled += 1;
// Parse out the &stuff;
if (ch == '&') {
// Process the &
readAmpersand();
} else {
// Not an '&', just append.
pushBack.append((char) ch);
}
}
} else {
// Hit end of file.
eof = true;
}
return eof;
}
|
java
|
private boolean readIntoPushBack() throws IOException {
// File finished?
boolean eof = false;
// Next char.
final int ch = in.read();
if (ch >= 0) {
// Discard whitespace at start?
if (!(pulled == 0 && isWhiteSpace(ch))) {
// Good code.
pulled += 1;
// Parse out the &stuff;
if (ch == '&') {
// Process the &
readAmpersand();
} else {
// Not an '&', just append.
pushBack.append((char) ch);
}
}
} else {
// Hit end of file.
eof = true;
}
return eof;
}
|
[
"private",
"boolean",
"readIntoPushBack",
"(",
")",
"throws",
"IOException",
"{",
"// File finished?",
"boolean",
"eof",
"=",
"false",
";",
"// Next char.",
"final",
"int",
"ch",
"=",
"in",
".",
"read",
"(",
")",
";",
"if",
"(",
"ch",
">=",
"0",
")",
"{",
"// Discard whitespace at start?",
"if",
"(",
"!",
"(",
"pulled",
"==",
"0",
"&&",
"isWhiteSpace",
"(",
"ch",
")",
")",
")",
"{",
"// Good code.",
"pulled",
"+=",
"1",
";",
"// Parse out the &stuff;",
"if",
"(",
"ch",
"==",
"'",
"'",
")",
"{",
"// Process the &",
"readAmpersand",
"(",
")",
";",
"}",
"else",
"{",
"// Not an '&', just append.",
"pushBack",
".",
"append",
"(",
"(",
"char",
")",
"ch",
")",
";",
"}",
"}",
"}",
"else",
"{",
"// Hit end of file.",
"eof",
"=",
"true",
";",
"}",
"return",
"eof",
";",
"}"
] |
Might not actually push back anything but usually will.
@return true if at end-of-file
@throws IOException thrown if there is an IO exception in the underlying
steam
|
[
"Might",
"not",
"actually",
"push",
"back",
"anything",
"but",
"usually",
"will",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/xml/XmlInputStream.java#L117-L141
|
17,969
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/xml/XmlInputStream.java
|
XmlInputStream.readAmpersand
|
private void readAmpersand() throws IOException {
// Read the whole word, up to and including the ;
final StringBuilder reference = new StringBuilder();
int ch;
// Should end in a ';'
for (ch = in.read(); isAlphaNumeric(ch); ch = in.read()) {
reference.append((char) ch);
}
// Did we tidily finish?
if (ch == ';') {
// Yes! Translate it into a &#nnn; code.
final String code = XmlEntity.fromNamedReference(reference);
if (code != null) {
// Keep it.
pushBack.append(code);
} else {
// invalid entity. Encode the & and append the sequence of chars.
pushBack.append("&").append(reference).append((char) ch);
}
} else {
// Did not terminate properly!
// Perhaps an & on its own or a malformed reference.
// Either way, escape the &
pushBack.append("&").append(reference).append((char) ch);
}
}
|
java
|
private void readAmpersand() throws IOException {
// Read the whole word, up to and including the ;
final StringBuilder reference = new StringBuilder();
int ch;
// Should end in a ';'
for (ch = in.read(); isAlphaNumeric(ch); ch = in.read()) {
reference.append((char) ch);
}
// Did we tidily finish?
if (ch == ';') {
// Yes! Translate it into a &#nnn; code.
final String code = XmlEntity.fromNamedReference(reference);
if (code != null) {
// Keep it.
pushBack.append(code);
} else {
// invalid entity. Encode the & and append the sequence of chars.
pushBack.append("&").append(reference).append((char) ch);
}
} else {
// Did not terminate properly!
// Perhaps an & on its own or a malformed reference.
// Either way, escape the &
pushBack.append("&").append(reference).append((char) ch);
}
}
|
[
"private",
"void",
"readAmpersand",
"(",
")",
"throws",
"IOException",
"{",
"// Read the whole word, up to and including the ;",
"final",
"StringBuilder",
"reference",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"int",
"ch",
";",
"// Should end in a ';'",
"for",
"(",
"ch",
"=",
"in",
".",
"read",
"(",
")",
";",
"isAlphaNumeric",
"(",
"ch",
")",
";",
"ch",
"=",
"in",
".",
"read",
"(",
")",
")",
"{",
"reference",
".",
"append",
"(",
"(",
"char",
")",
"ch",
")",
";",
"}",
"// Did we tidily finish?",
"if",
"(",
"ch",
"==",
"'",
"'",
")",
"{",
"// Yes! Translate it into a &#nnn; code.",
"final",
"String",
"code",
"=",
"XmlEntity",
".",
"fromNamedReference",
"(",
"reference",
")",
";",
"if",
"(",
"code",
"!=",
"null",
")",
"{",
"// Keep it.",
"pushBack",
".",
"append",
"(",
"code",
")",
";",
"}",
"else",
"{",
"// invalid entity. Encode the & and append the sequence of chars.",
"pushBack",
".",
"append",
"(",
"\"&\"",
")",
".",
"append",
"(",
"reference",
")",
".",
"append",
"(",
"(",
"char",
")",
"ch",
")",
";",
"}",
"}",
"else",
"{",
"// Did not terminate properly!",
"// Perhaps an & on its own or a malformed reference.",
"// Either way, escape the &",
"pushBack",
".",
"append",
"(",
"\"&\"",
")",
".",
"append",
"(",
"reference",
")",
".",
"append",
"(",
"(",
"char",
")",
"ch",
")",
";",
"}",
"}"
] |
Deal with an ampersand in the stream.
@throws IOException thrown if an unknown entity is encountered
|
[
"Deal",
"with",
"an",
"ampersand",
"in",
"the",
"stream",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/xml/XmlInputStream.java#L148-L173
|
17,970
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/xml/XmlInputStream.java
|
XmlInputStream.given
|
private void given(CharSequence s, int wanted, int got) {
red.append(s);
given += got;
LOGGER.trace("Given: [" + wanted + "," + got + "]-" + s);
}
|
java
|
private void given(CharSequence s, int wanted, int got) {
red.append(s);
given += got;
LOGGER.trace("Given: [" + wanted + "," + got + "]-" + s);
}
|
[
"private",
"void",
"given",
"(",
"CharSequence",
"s",
",",
"int",
"wanted",
",",
"int",
"got",
")",
"{",
"red",
".",
"append",
"(",
"s",
")",
";",
"given",
"+=",
"got",
";",
"LOGGER",
".",
"trace",
"(",
"\"Given: [\"",
"+",
"wanted",
"+",
"\",\"",
"+",
"got",
"+",
"\"]-\"",
"+",
"s",
")",
";",
"}"
] |
Keep track of what we've given them.
@param s the sequence of characters given
@param wanted the number of characters wanted
@param got the number of characters given
|
[
"Keep",
"track",
"of",
"what",
"we",
"ve",
"given",
"them",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/xml/XmlInputStream.java#L182-L186
|
17,971
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/xml/XmlInputStream.java
|
XmlInputStream.read
|
@Override
public int read(byte[] data, int offset, int length) throws IOException {
final StringBuilder s = read(length);
int n = 0;
for (int i = 0; i < Math.min(length, s.length()); i++) {
data[offset + i] = (byte) s.charAt(i);
n += 1;
}
given(s, length, n);
return n > 0 ? n : -1;
}
|
java
|
@Override
public int read(byte[] data, int offset, int length) throws IOException {
final StringBuilder s = read(length);
int n = 0;
for (int i = 0; i < Math.min(length, s.length()); i++) {
data[offset + i] = (byte) s.charAt(i);
n += 1;
}
given(s, length, n);
return n > 0 ? n : -1;
}
|
[
"@",
"Override",
"public",
"int",
"read",
"(",
"byte",
"[",
"]",
"data",
",",
"int",
"offset",
",",
"int",
"length",
")",
"throws",
"IOException",
"{",
"final",
"StringBuilder",
"s",
"=",
"read",
"(",
"length",
")",
";",
"int",
"n",
"=",
"0",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"Math",
".",
"min",
"(",
"length",
",",
"s",
".",
"length",
"(",
")",
")",
";",
"i",
"++",
")",
"{",
"data",
"[",
"offset",
"+",
"i",
"]",
"=",
"(",
"byte",
")",
"s",
".",
"charAt",
"(",
"i",
")",
";",
"n",
"+=",
"1",
";",
"}",
"given",
"(",
"s",
",",
"length",
",",
"n",
")",
";",
"return",
"n",
">",
"0",
"?",
"n",
":",
"-",
"1",
";",
"}"
] |
Reads the next length of bytes from the stream into the given byte array
at the given offset.
@param data the buffer to store the data read
@param offset the offset in the buffer to start writing
@param length the length of data to read
@return the number of bytes read
@throws IOException thrown when there is an issue with the underlying
stream
|
[
"Reads",
"the",
"next",
"length",
"of",
"bytes",
"from",
"the",
"stream",
"into",
"the",
"given",
"byte",
"array",
"at",
"the",
"given",
"offset",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/xml/XmlInputStream.java#L212-L222
|
17,972
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/data/cpe/CpeMemoryIndex.java
|
CpeMemoryIndex.open
|
public synchronized void open(CveDB cve, Settings settings) throws IndexException {
if (INSTANCE.usageCount.addAndGet(1) == 1) {
try {
final File temp = settings.getTempDirectory();
index = new MMapDirectory(temp.toPath());
buildIndex(cve);
indexReader = DirectoryReader.open(index);
} catch (IOException ex) {
throw new IndexException(ex);
}
indexSearcher = new IndexSearcher(indexReader);
searchingAnalyzer = createSearchingAnalyzer();
queryParser = new QueryParser(Fields.DOCUMENT_KEY, searchingAnalyzer);
}
}
|
java
|
public synchronized void open(CveDB cve, Settings settings) throws IndexException {
if (INSTANCE.usageCount.addAndGet(1) == 1) {
try {
final File temp = settings.getTempDirectory();
index = new MMapDirectory(temp.toPath());
buildIndex(cve);
indexReader = DirectoryReader.open(index);
} catch (IOException ex) {
throw new IndexException(ex);
}
indexSearcher = new IndexSearcher(indexReader);
searchingAnalyzer = createSearchingAnalyzer();
queryParser = new QueryParser(Fields.DOCUMENT_KEY, searchingAnalyzer);
}
}
|
[
"public",
"synchronized",
"void",
"open",
"(",
"CveDB",
"cve",
",",
"Settings",
"settings",
")",
"throws",
"IndexException",
"{",
"if",
"(",
"INSTANCE",
".",
"usageCount",
".",
"addAndGet",
"(",
"1",
")",
"==",
"1",
")",
"{",
"try",
"{",
"final",
"File",
"temp",
"=",
"settings",
".",
"getTempDirectory",
"(",
")",
";",
"index",
"=",
"new",
"MMapDirectory",
"(",
"temp",
".",
"toPath",
"(",
")",
")",
";",
"buildIndex",
"(",
"cve",
")",
";",
"indexReader",
"=",
"DirectoryReader",
".",
"open",
"(",
"index",
")",
";",
"}",
"catch",
"(",
"IOException",
"ex",
")",
"{",
"throw",
"new",
"IndexException",
"(",
"ex",
")",
";",
"}",
"indexSearcher",
"=",
"new",
"IndexSearcher",
"(",
"indexReader",
")",
";",
"searchingAnalyzer",
"=",
"createSearchingAnalyzer",
"(",
")",
";",
"queryParser",
"=",
"new",
"QueryParser",
"(",
"Fields",
".",
"DOCUMENT_KEY",
",",
"searchingAnalyzer",
")",
";",
"}",
"}"
] |
Creates and loads data into an in memory index.
@param cve the data source to retrieve the cpe data
@param settings a reference to the dependency-check settings
@throws IndexException thrown if there is an error creating the index
|
[
"Creates",
"and",
"loads",
"data",
"into",
"an",
"in",
"memory",
"index",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/data/cpe/CpeMemoryIndex.java#L134-L149
|
17,973
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/data/cpe/CpeMemoryIndex.java
|
CpeMemoryIndex.createSearchingAnalyzer
|
private Analyzer createSearchingAnalyzer() {
final Map<String, Analyzer> fieldAnalyzers = new HashMap<>();
fieldAnalyzers.put(Fields.DOCUMENT_KEY, new KeywordAnalyzer());
productFieldAnalyzer = new SearchFieldAnalyzer();
vendorFieldAnalyzer = new SearchFieldAnalyzer();
fieldAnalyzers.put(Fields.PRODUCT, productFieldAnalyzer);
fieldAnalyzers.put(Fields.VENDOR, vendorFieldAnalyzer);
return new PerFieldAnalyzerWrapper(new KeywordAnalyzer(), fieldAnalyzers);
}
|
java
|
private Analyzer createSearchingAnalyzer() {
final Map<String, Analyzer> fieldAnalyzers = new HashMap<>();
fieldAnalyzers.put(Fields.DOCUMENT_KEY, new KeywordAnalyzer());
productFieldAnalyzer = new SearchFieldAnalyzer();
vendorFieldAnalyzer = new SearchFieldAnalyzer();
fieldAnalyzers.put(Fields.PRODUCT, productFieldAnalyzer);
fieldAnalyzers.put(Fields.VENDOR, vendorFieldAnalyzer);
return new PerFieldAnalyzerWrapper(new KeywordAnalyzer(), fieldAnalyzers);
}
|
[
"private",
"Analyzer",
"createSearchingAnalyzer",
"(",
")",
"{",
"final",
"Map",
"<",
"String",
",",
"Analyzer",
">",
"fieldAnalyzers",
"=",
"new",
"HashMap",
"<>",
"(",
")",
";",
"fieldAnalyzers",
".",
"put",
"(",
"Fields",
".",
"DOCUMENT_KEY",
",",
"new",
"KeywordAnalyzer",
"(",
")",
")",
";",
"productFieldAnalyzer",
"=",
"new",
"SearchFieldAnalyzer",
"(",
")",
";",
"vendorFieldAnalyzer",
"=",
"new",
"SearchFieldAnalyzer",
"(",
")",
";",
"fieldAnalyzers",
".",
"put",
"(",
"Fields",
".",
"PRODUCT",
",",
"productFieldAnalyzer",
")",
";",
"fieldAnalyzers",
".",
"put",
"(",
"Fields",
".",
"VENDOR",
",",
"vendorFieldAnalyzer",
")",
";",
"return",
"new",
"PerFieldAnalyzerWrapper",
"(",
"new",
"KeywordAnalyzer",
"(",
")",
",",
"fieldAnalyzers",
")",
";",
"}"
] |
Creates an Analyzer for searching the CPE Index.
@return the CPE Analyzer.
|
[
"Creates",
"an",
"Analyzer",
"for",
"searching",
"the",
"CPE",
"Index",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/data/cpe/CpeMemoryIndex.java#L165-L174
|
17,974
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/data/cpe/CpeMemoryIndex.java
|
CpeMemoryIndex.close
|
@Override
public synchronized void close() {
final int count = INSTANCE.usageCount.get() - 1;
if (count <= 0) {
INSTANCE.usageCount.set(0);
if (searchingAnalyzer != null) {
searchingAnalyzer.close();
searchingAnalyzer = null;
}
if (indexReader != null) {
try {
indexReader.close();
} catch (IOException ex) {
LOGGER.trace("", ex);
}
indexReader = null;
}
queryParser = null;
indexSearcher = null;
if (index != null) {
try {
index.close();
} catch (IOException ex) {
LOGGER.trace("", ex);
}
index = null;
}
}
}
|
java
|
@Override
public synchronized void close() {
final int count = INSTANCE.usageCount.get() - 1;
if (count <= 0) {
INSTANCE.usageCount.set(0);
if (searchingAnalyzer != null) {
searchingAnalyzer.close();
searchingAnalyzer = null;
}
if (indexReader != null) {
try {
indexReader.close();
} catch (IOException ex) {
LOGGER.trace("", ex);
}
indexReader = null;
}
queryParser = null;
indexSearcher = null;
if (index != null) {
try {
index.close();
} catch (IOException ex) {
LOGGER.trace("", ex);
}
index = null;
}
}
}
|
[
"@",
"Override",
"public",
"synchronized",
"void",
"close",
"(",
")",
"{",
"final",
"int",
"count",
"=",
"INSTANCE",
".",
"usageCount",
".",
"get",
"(",
")",
"-",
"1",
";",
"if",
"(",
"count",
"<=",
"0",
")",
"{",
"INSTANCE",
".",
"usageCount",
".",
"set",
"(",
"0",
")",
";",
"if",
"(",
"searchingAnalyzer",
"!=",
"null",
")",
"{",
"searchingAnalyzer",
".",
"close",
"(",
")",
";",
"searchingAnalyzer",
"=",
"null",
";",
"}",
"if",
"(",
"indexReader",
"!=",
"null",
")",
"{",
"try",
"{",
"indexReader",
".",
"close",
"(",
")",
";",
"}",
"catch",
"(",
"IOException",
"ex",
")",
"{",
"LOGGER",
".",
"trace",
"(",
"\"\"",
",",
"ex",
")",
";",
"}",
"indexReader",
"=",
"null",
";",
"}",
"queryParser",
"=",
"null",
";",
"indexSearcher",
"=",
"null",
";",
"if",
"(",
"index",
"!=",
"null",
")",
"{",
"try",
"{",
"index",
".",
"close",
"(",
")",
";",
"}",
"catch",
"(",
"IOException",
"ex",
")",
"{",
"LOGGER",
".",
"trace",
"(",
"\"\"",
",",
"ex",
")",
";",
"}",
"index",
"=",
"null",
";",
"}",
"}",
"}"
] |
Closes the CPE Index.
|
[
"Closes",
"the",
"CPE",
"Index",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/data/cpe/CpeMemoryIndex.java#L179-L207
|
17,975
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/data/cpe/CpeMemoryIndex.java
|
CpeMemoryIndex.buildIndex
|
private void buildIndex(CveDB cve) throws IndexException {
try (Analyzer analyzer = createSearchingAnalyzer();
IndexWriter indexWriter = new IndexWriter(index,
new IndexWriterConfig(analyzer))) {
final FieldType ft = new FieldType(TextField.TYPE_STORED);
//ignore term frequency
ft.setIndexOptions(IndexOptions.DOCS);
//ignore field length normalization
ft.setOmitNorms(true);
// Tip: reuse the Document and Fields for performance...
// See "Re-use Document and Field instances" from
// http://wiki.apache.org/lucene-java/ImproveIndexingSpeed
final Document doc = new Document();
final Field v = new Field(Fields.VENDOR, Fields.VENDOR, ft);
final Field p = new Field(Fields.PRODUCT, Fields.PRODUCT, ft);
doc.add(v);
doc.add(p);
final Set<Pair<String, String>> data = cve.getVendorProductList();
for (Pair<String, String> pair : data) {
if (pair.getLeft() != null && pair.getRight() != null) {
v.setStringValue(pair.getLeft());
p.setStringValue(pair.getRight());
indexWriter.addDocument(doc);
resetAnalyzers();
}
}
indexWriter.commit();
} catch (DatabaseException ex) {
LOGGER.debug("", ex);
throw new IndexException("Error reading CPE data", ex);
} catch (IOException ex) {
throw new IndexException("Unable to close an in-memory index", ex);
}
}
|
java
|
private void buildIndex(CveDB cve) throws IndexException {
try (Analyzer analyzer = createSearchingAnalyzer();
IndexWriter indexWriter = new IndexWriter(index,
new IndexWriterConfig(analyzer))) {
final FieldType ft = new FieldType(TextField.TYPE_STORED);
//ignore term frequency
ft.setIndexOptions(IndexOptions.DOCS);
//ignore field length normalization
ft.setOmitNorms(true);
// Tip: reuse the Document and Fields for performance...
// See "Re-use Document and Field instances" from
// http://wiki.apache.org/lucene-java/ImproveIndexingSpeed
final Document doc = new Document();
final Field v = new Field(Fields.VENDOR, Fields.VENDOR, ft);
final Field p = new Field(Fields.PRODUCT, Fields.PRODUCT, ft);
doc.add(v);
doc.add(p);
final Set<Pair<String, String>> data = cve.getVendorProductList();
for (Pair<String, String> pair : data) {
if (pair.getLeft() != null && pair.getRight() != null) {
v.setStringValue(pair.getLeft());
p.setStringValue(pair.getRight());
indexWriter.addDocument(doc);
resetAnalyzers();
}
}
indexWriter.commit();
} catch (DatabaseException ex) {
LOGGER.debug("", ex);
throw new IndexException("Error reading CPE data", ex);
} catch (IOException ex) {
throw new IndexException("Unable to close an in-memory index", ex);
}
}
|
[
"private",
"void",
"buildIndex",
"(",
"CveDB",
"cve",
")",
"throws",
"IndexException",
"{",
"try",
"(",
"Analyzer",
"analyzer",
"=",
"createSearchingAnalyzer",
"(",
")",
";",
"IndexWriter",
"indexWriter",
"=",
"new",
"IndexWriter",
"(",
"index",
",",
"new",
"IndexWriterConfig",
"(",
"analyzer",
")",
")",
")",
"{",
"final",
"FieldType",
"ft",
"=",
"new",
"FieldType",
"(",
"TextField",
".",
"TYPE_STORED",
")",
";",
"//ignore term frequency",
"ft",
".",
"setIndexOptions",
"(",
"IndexOptions",
".",
"DOCS",
")",
";",
"//ignore field length normalization",
"ft",
".",
"setOmitNorms",
"(",
"true",
")",
";",
"// Tip: reuse the Document and Fields for performance...",
"// See \"Re-use Document and Field instances\" from",
"// http://wiki.apache.org/lucene-java/ImproveIndexingSpeed",
"final",
"Document",
"doc",
"=",
"new",
"Document",
"(",
")",
";",
"final",
"Field",
"v",
"=",
"new",
"Field",
"(",
"Fields",
".",
"VENDOR",
",",
"Fields",
".",
"VENDOR",
",",
"ft",
")",
";",
"final",
"Field",
"p",
"=",
"new",
"Field",
"(",
"Fields",
".",
"PRODUCT",
",",
"Fields",
".",
"PRODUCT",
",",
"ft",
")",
";",
"doc",
".",
"add",
"(",
"v",
")",
";",
"doc",
".",
"add",
"(",
"p",
")",
";",
"final",
"Set",
"<",
"Pair",
"<",
"String",
",",
"String",
">",
">",
"data",
"=",
"cve",
".",
"getVendorProductList",
"(",
")",
";",
"for",
"(",
"Pair",
"<",
"String",
",",
"String",
">",
"pair",
":",
"data",
")",
"{",
"if",
"(",
"pair",
".",
"getLeft",
"(",
")",
"!=",
"null",
"&&",
"pair",
".",
"getRight",
"(",
")",
"!=",
"null",
")",
"{",
"v",
".",
"setStringValue",
"(",
"pair",
".",
"getLeft",
"(",
")",
")",
";",
"p",
".",
"setStringValue",
"(",
"pair",
".",
"getRight",
"(",
")",
")",
";",
"indexWriter",
".",
"addDocument",
"(",
"doc",
")",
";",
"resetAnalyzers",
"(",
")",
";",
"}",
"}",
"indexWriter",
".",
"commit",
"(",
")",
";",
"}",
"catch",
"(",
"DatabaseException",
"ex",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"\"",
",",
"ex",
")",
";",
"throw",
"new",
"IndexException",
"(",
"\"Error reading CPE data\"",
",",
"ex",
")",
";",
"}",
"catch",
"(",
"IOException",
"ex",
")",
"{",
"throw",
"new",
"IndexException",
"(",
"\"Unable to close an in-memory index\"",
",",
"ex",
")",
";",
"}",
"}"
] |
Builds the CPE Lucene Index based off of the data within the CveDB.
@param cve the data base containing the CPE data
@throws IndexException thrown if there is an issue creating the index
|
[
"Builds",
"the",
"CPE",
"Lucene",
"Index",
"based",
"off",
"of",
"the",
"data",
"within",
"the",
"CveDB",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/data/cpe/CpeMemoryIndex.java#L215-L252
|
17,976
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/data/cpe/CpeMemoryIndex.java
|
CpeMemoryIndex.search
|
public synchronized TopDocs search(String searchString, int maxQueryResults) throws ParseException, IndexException, IOException {
final Query query = parseQuery(searchString);
return search(query, maxQueryResults);
}
|
java
|
public synchronized TopDocs search(String searchString, int maxQueryResults) throws ParseException, IndexException, IOException {
final Query query = parseQuery(searchString);
return search(query, maxQueryResults);
}
|
[
"public",
"synchronized",
"TopDocs",
"search",
"(",
"String",
"searchString",
",",
"int",
"maxQueryResults",
")",
"throws",
"ParseException",
",",
"IndexException",
",",
"IOException",
"{",
"final",
"Query",
"query",
"=",
"parseQuery",
"(",
"searchString",
")",
";",
"return",
"search",
"(",
"query",
",",
"maxQueryResults",
")",
";",
"}"
] |
Searches the index using the given search string.
@param searchString the query text
@param maxQueryResults the maximum number of documents to return
@return the TopDocs found by the search
@throws ParseException thrown when the searchString is invalid
@throws IndexException thrown when there is an internal error resetting
the search analyzer
@throws IOException is thrown if there is an issue with the underlying
Index
|
[
"Searches",
"the",
"index",
"using",
"the",
"given",
"search",
"string",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/data/cpe/CpeMemoryIndex.java#L266-L269
|
17,977
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/data/cpe/CpeMemoryIndex.java
|
CpeMemoryIndex.parseQuery
|
public synchronized Query parseQuery(String searchString) throws ParseException, IndexException {
if (searchString == null || searchString.trim().isEmpty()) {
throw new ParseException("Query is null or empty");
}
LOGGER.debug(searchString);
final Query query = queryParser.parse(searchString);
try {
resetAnalyzers();
} catch (IOException ex) {
throw new IndexException("Unable to reset the analyzer after parsing", ex);
}
return query;
}
|
java
|
public synchronized Query parseQuery(String searchString) throws ParseException, IndexException {
if (searchString == null || searchString.trim().isEmpty()) {
throw new ParseException("Query is null or empty");
}
LOGGER.debug(searchString);
final Query query = queryParser.parse(searchString);
try {
resetAnalyzers();
} catch (IOException ex) {
throw new IndexException("Unable to reset the analyzer after parsing", ex);
}
return query;
}
|
[
"public",
"synchronized",
"Query",
"parseQuery",
"(",
"String",
"searchString",
")",
"throws",
"ParseException",
",",
"IndexException",
"{",
"if",
"(",
"searchString",
"==",
"null",
"||",
"searchString",
".",
"trim",
"(",
")",
".",
"isEmpty",
"(",
")",
")",
"{",
"throw",
"new",
"ParseException",
"(",
"\"Query is null or empty\"",
")",
";",
"}",
"LOGGER",
".",
"debug",
"(",
"searchString",
")",
";",
"final",
"Query",
"query",
"=",
"queryParser",
".",
"parse",
"(",
"searchString",
")",
";",
"try",
"{",
"resetAnalyzers",
"(",
")",
";",
"}",
"catch",
"(",
"IOException",
"ex",
")",
"{",
"throw",
"new",
"IndexException",
"(",
"\"Unable to reset the analyzer after parsing\"",
",",
"ex",
")",
";",
"}",
"return",
"query",
";",
"}"
] |
Parses the given string into a Lucene Query.
@param searchString the search text
@return the Query object
@throws ParseException thrown if the search text cannot be parsed
@throws IndexException thrown if there is an error resetting the
analyzers
|
[
"Parses",
"the",
"given",
"string",
"into",
"a",
"Lucene",
"Query",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/data/cpe/CpeMemoryIndex.java#L280-L293
|
17,978
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/data/cpe/CpeMemoryIndex.java
|
CpeMemoryIndex.search
|
public synchronized TopDocs search(Query query, int maxQueryResults) throws CorruptIndexException, IOException {
return indexSearcher.search(query, maxQueryResults);
}
|
java
|
public synchronized TopDocs search(Query query, int maxQueryResults) throws CorruptIndexException, IOException {
return indexSearcher.search(query, maxQueryResults);
}
|
[
"public",
"synchronized",
"TopDocs",
"search",
"(",
"Query",
"query",
",",
"int",
"maxQueryResults",
")",
"throws",
"CorruptIndexException",
",",
"IOException",
"{",
"return",
"indexSearcher",
".",
"search",
"(",
"query",
",",
"maxQueryResults",
")",
";",
"}"
] |
Searches the index using the given query.
@param query the query used to search the index
@param maxQueryResults the max number of results to return
@return the TopDocs found be the query
@throws CorruptIndexException thrown if the Index is corrupt
@throws IOException thrown if there is an IOException
|
[
"Searches",
"the",
"index",
"using",
"the",
"given",
"query",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/data/cpe/CpeMemoryIndex.java#L304-L306
|
17,979
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/data/cpe/CpeMemoryIndex.java
|
CpeMemoryIndex.explain
|
public synchronized String explain(Query query, int doc) throws IOException {
return indexSearcher.explain(query, doc).toString();
}
|
java
|
public synchronized String explain(Query query, int doc) throws IOException {
return indexSearcher.explain(query, doc).toString();
}
|
[
"public",
"synchronized",
"String",
"explain",
"(",
"Query",
"query",
",",
"int",
"doc",
")",
"throws",
"IOException",
"{",
"return",
"indexSearcher",
".",
"explain",
"(",
"query",
",",
"doc",
")",
".",
"toString",
"(",
")",
";",
"}"
] |
Method to explain queries matches.
@param query the query used
@param doc the document matched
@return the expalanation
@throws IOException thrown if there is an index error
|
[
"Method",
"to",
"explain",
"queries",
"matches",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/data/cpe/CpeMemoryIndex.java#L339-L341
|
17,980
|
jtablesaw/tablesaw
|
core/src/main/java/tech/tablesaw/api/StringColumn.java
|
StringColumn.append
|
public StringColumn append(String value) {
try {
lookupTable.append(value);
} catch (NoKeysAvailableException ex) {
lookupTable = lookupTable.promoteYourself();
try {
lookupTable.append(value);
} catch (NoKeysAvailableException e) {
// this can't happen
throw new IllegalStateException(e);
}
}
return this;
}
|
java
|
public StringColumn append(String value) {
try {
lookupTable.append(value);
} catch (NoKeysAvailableException ex) {
lookupTable = lookupTable.promoteYourself();
try {
lookupTable.append(value);
} catch (NoKeysAvailableException e) {
// this can't happen
throw new IllegalStateException(e);
}
}
return this;
}
|
[
"public",
"StringColumn",
"append",
"(",
"String",
"value",
")",
"{",
"try",
"{",
"lookupTable",
".",
"append",
"(",
"value",
")",
";",
"}",
"catch",
"(",
"NoKeysAvailableException",
"ex",
")",
"{",
"lookupTable",
"=",
"lookupTable",
".",
"promoteYourself",
"(",
")",
";",
"try",
"{",
"lookupTable",
".",
"append",
"(",
"value",
")",
";",
"}",
"catch",
"(",
"NoKeysAvailableException",
"e",
")",
"{",
"// this can't happen",
"throw",
"new",
"IllegalStateException",
"(",
"e",
")",
";",
"}",
"}",
"return",
"this",
";",
"}"
] |
Added for naming consistency with all other columns
|
[
"Added",
"for",
"naming",
"consistency",
"with",
"all",
"other",
"columns"
] |
68a75b4098ac677e9486df5572cf13ec39f9f701
|
https://github.com/jtablesaw/tablesaw/blob/68a75b4098ac677e9486df5572cf13ec39f9f701/core/src/main/java/tech/tablesaw/api/StringColumn.java#L484-L497
|
17,981
|
jtablesaw/tablesaw
|
core/src/main/java/tech/tablesaw/columns/strings/ByteDictionaryMap.java
|
ByteDictionaryMap.addValuesToSelection
|
private void addValuesToSelection(Selection results, byte key) {
if (key != DEFAULT_RETURN_VALUE) {
int i = 0;
for (byte next : values) {
if (key == next) {
results.add(i);
}
i++;
}
}
}
|
java
|
private void addValuesToSelection(Selection results, byte key) {
if (key != DEFAULT_RETURN_VALUE) {
int i = 0;
for (byte next : values) {
if (key == next) {
results.add(i);
}
i++;
}
}
}
|
[
"private",
"void",
"addValuesToSelection",
"(",
"Selection",
"results",
",",
"byte",
"key",
")",
"{",
"if",
"(",
"key",
"!=",
"DEFAULT_RETURN_VALUE",
")",
"{",
"int",
"i",
"=",
"0",
";",
"for",
"(",
"byte",
"next",
":",
"values",
")",
"{",
"if",
"(",
"key",
"==",
"next",
")",
"{",
"results",
".",
"add",
"(",
"i",
")",
";",
"}",
"i",
"++",
";",
"}",
"}",
"}"
] |
Given a key matching some string, add to the selection the index of every record that matches that key
|
[
"Given",
"a",
"key",
"matching",
"some",
"string",
"add",
"to",
"the",
"selection",
"the",
"index",
"of",
"every",
"record",
"that",
"matches",
"that",
"key"
] |
68a75b4098ac677e9486df5572cf13ec39f9f701
|
https://github.com/jtablesaw/tablesaw/blob/68a75b4098ac677e9486df5572cf13ec39f9f701/core/src/main/java/tech/tablesaw/columns/strings/ByteDictionaryMap.java#L229-L239
|
17,982
|
jtablesaw/tablesaw
|
core/src/main/java/tech/tablesaw/io/FileReader.java
|
FileReader.selectColumnNames
|
private String[] selectColumnNames(List<String> names, ColumnType[] types) {
List<String> header = new ArrayList<>();
for (int i = 0; i < types.length; i++) {
if (types[i] != SKIP) {
String name = names.get(i);
name = name.trim();
header.add(name);
}
}
String[] result = new String[header.size()];
return header.toArray(result);
}
|
java
|
private String[] selectColumnNames(List<String> names, ColumnType[] types) {
List<String> header = new ArrayList<>();
for (int i = 0; i < types.length; i++) {
if (types[i] != SKIP) {
String name = names.get(i);
name = name.trim();
header.add(name);
}
}
String[] result = new String[header.size()];
return header.toArray(result);
}
|
[
"private",
"String",
"[",
"]",
"selectColumnNames",
"(",
"List",
"<",
"String",
">",
"names",
",",
"ColumnType",
"[",
"]",
"types",
")",
"{",
"List",
"<",
"String",
">",
"header",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"types",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"types",
"[",
"i",
"]",
"!=",
"SKIP",
")",
"{",
"String",
"name",
"=",
"names",
".",
"get",
"(",
"i",
")",
";",
"name",
"=",
"name",
".",
"trim",
"(",
")",
";",
"header",
".",
"add",
"(",
"name",
")",
";",
"}",
"}",
"String",
"[",
"]",
"result",
"=",
"new",
"String",
"[",
"header",
".",
"size",
"(",
")",
"]",
";",
"return",
"header",
".",
"toArray",
"(",
"result",
")",
";",
"}"
] |
Reads column names from header, skipping any for which the type == SKIP
|
[
"Reads",
"column",
"names",
"from",
"header",
"skipping",
"any",
"for",
"which",
"the",
"type",
"==",
"SKIP"
] |
68a75b4098ac677e9486df5572cf13ec39f9f701
|
https://github.com/jtablesaw/tablesaw/blob/68a75b4098ac677e9486df5572cf13ec39f9f701/core/src/main/java/tech/tablesaw/io/FileReader.java#L178-L189
|
17,983
|
jtablesaw/tablesaw
|
core/src/main/java/tech/tablesaw/aggregate/Summarizer.java
|
Summarizer.summarize
|
private Table summarize(TableSliceGroup group) {
List<Table> results = new ArrayList<>();
ArrayListMultimap<String, AggregateFunction<?, ?>> reductionMultimap = getAggregateFunctionMultimap();
for (String name : reductionMultimap.keys()) {
List<AggregateFunction<?, ?>> reductions = reductionMultimap.get(name);
results.add(group.aggregate(name, reductions.toArray(new AggregateFunction<?, ?>[0])));
}
return combineTables(results);
}
|
java
|
private Table summarize(TableSliceGroup group) {
List<Table> results = new ArrayList<>();
ArrayListMultimap<String, AggregateFunction<?, ?>> reductionMultimap = getAggregateFunctionMultimap();
for (String name : reductionMultimap.keys()) {
List<AggregateFunction<?, ?>> reductions = reductionMultimap.get(name);
results.add(group.aggregate(name, reductions.toArray(new AggregateFunction<?, ?>[0])));
}
return combineTables(results);
}
|
[
"private",
"Table",
"summarize",
"(",
"TableSliceGroup",
"group",
")",
"{",
"List",
"<",
"Table",
">",
"results",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"ArrayListMultimap",
"<",
"String",
",",
"AggregateFunction",
"<",
"?",
",",
"?",
">",
">",
"reductionMultimap",
"=",
"getAggregateFunctionMultimap",
"(",
")",
";",
"for",
"(",
"String",
"name",
":",
"reductionMultimap",
".",
"keys",
"(",
")",
")",
"{",
"List",
"<",
"AggregateFunction",
"<",
"?",
",",
"?",
">",
">",
"reductions",
"=",
"reductionMultimap",
".",
"get",
"(",
"name",
")",
";",
"results",
".",
"add",
"(",
"group",
".",
"aggregate",
"(",
"name",
",",
"reductions",
".",
"toArray",
"(",
"new",
"AggregateFunction",
"<",
"?",
",",
"?",
">",
"[",
"0",
"]",
")",
")",
")",
";",
"}",
"return",
"combineTables",
"(",
"results",
")",
";",
"}"
] |
Associates the columns to be summarized with the functions that match their type. All valid combinations are used
@param group A table slice group
@return A table containing a row of summarized data for each group in the table slice group
|
[
"Associates",
"the",
"columns",
"to",
"be",
"summarized",
"with",
"the",
"functions",
"that",
"match",
"their",
"type",
".",
"All",
"valid",
"combinations",
"are",
"used"
] |
68a75b4098ac677e9486df5572cf13ec39f9f701
|
https://github.com/jtablesaw/tablesaw/blob/68a75b4098ac677e9486df5572cf13ec39f9f701/core/src/main/java/tech/tablesaw/aggregate/Summarizer.java#L196-L206
|
17,984
|
jtablesaw/tablesaw
|
core/src/main/java/tech/tablesaw/table/StandardTableSliceGroup.java
|
StandardTableSliceGroup.create
|
public static StandardTableSliceGroup create(Table original, String... columnsNames) {
List<CategoricalColumn<?>> columns = original.categoricalColumns(columnsNames);
return new StandardTableSliceGroup(original, columns.toArray(new CategoricalColumn<?>[0]));
}
|
java
|
public static StandardTableSliceGroup create(Table original, String... columnsNames) {
List<CategoricalColumn<?>> columns = original.categoricalColumns(columnsNames);
return new StandardTableSliceGroup(original, columns.toArray(new CategoricalColumn<?>[0]));
}
|
[
"public",
"static",
"StandardTableSliceGroup",
"create",
"(",
"Table",
"original",
",",
"String",
"...",
"columnsNames",
")",
"{",
"List",
"<",
"CategoricalColumn",
"<",
"?",
">",
">",
"columns",
"=",
"original",
".",
"categoricalColumns",
"(",
"columnsNames",
")",
";",
"return",
"new",
"StandardTableSliceGroup",
"(",
"original",
",",
"columns",
".",
"toArray",
"(",
"new",
"CategoricalColumn",
"<",
"?",
">",
"[",
"0",
"]",
")",
")",
";",
"}"
] |
Returns a viewGroup splitting the original table on the given columns.
The named columns must be CategoricalColumns
|
[
"Returns",
"a",
"viewGroup",
"splitting",
"the",
"original",
"table",
"on",
"the",
"given",
"columns",
".",
"The",
"named",
"columns",
"must",
"be",
"CategoricalColumns"
] |
68a75b4098ac677e9486df5572cf13ec39f9f701
|
https://github.com/jtablesaw/tablesaw/blob/68a75b4098ac677e9486df5572cf13ec39f9f701/core/src/main/java/tech/tablesaw/table/StandardTableSliceGroup.java#L50-L53
|
17,985
|
jtablesaw/tablesaw
|
core/src/main/java/tech/tablesaw/table/StandardTableSliceGroup.java
|
StandardTableSliceGroup.splitOn
|
private void splitOn(String... columnNames) {
List<Column<?>> columns = getSourceTable().columns(columnNames);
int byteSize = getByteSize(columns);
byte[] currentKey = null;
String currentStringKey = null;
TableSlice view;
Selection selection = new BitmapBackedSelection();
for (int row = 0; row < getSourceTable().rowCount(); row++) {
ByteBuffer byteBuffer = ByteBuffer.allocate(byteSize);
String newStringKey = "";
for (int col = 0; col < columnNames.length; col++) {
if (col > 0) {
newStringKey = newStringKey + SPLIT_STRING;
}
Column<?> c = getSourceTable().column(columnNames[col]);
String groupKey = getSourceTable().getUnformatted(row, getSourceTable().columnIndex(c));
newStringKey = newStringKey + groupKey;
byteBuffer.put(c.asBytes(row));
}
byte[] newKey = byteBuffer.array();
if (row == 0) {
currentKey = newKey;
currentStringKey = newStringKey;
}
if (!Arrays.equals(newKey, currentKey)) {
currentKey = newKey;
view = new TableSlice(getSourceTable(), selection);
view.setName(currentStringKey);
currentStringKey = newStringKey;
addSlice(view);
selection = new BitmapBackedSelection();
selection.add(row);
} else {
selection.add(row);
}
}
if (!selection.isEmpty()) {
view = new TableSlice(getSourceTable(), selection);
view.setName(currentStringKey);
addSlice(view);
}
}
|
java
|
private void splitOn(String... columnNames) {
List<Column<?>> columns = getSourceTable().columns(columnNames);
int byteSize = getByteSize(columns);
byte[] currentKey = null;
String currentStringKey = null;
TableSlice view;
Selection selection = new BitmapBackedSelection();
for (int row = 0; row < getSourceTable().rowCount(); row++) {
ByteBuffer byteBuffer = ByteBuffer.allocate(byteSize);
String newStringKey = "";
for (int col = 0; col < columnNames.length; col++) {
if (col > 0) {
newStringKey = newStringKey + SPLIT_STRING;
}
Column<?> c = getSourceTable().column(columnNames[col]);
String groupKey = getSourceTable().getUnformatted(row, getSourceTable().columnIndex(c));
newStringKey = newStringKey + groupKey;
byteBuffer.put(c.asBytes(row));
}
byte[] newKey = byteBuffer.array();
if (row == 0) {
currentKey = newKey;
currentStringKey = newStringKey;
}
if (!Arrays.equals(newKey, currentKey)) {
currentKey = newKey;
view = new TableSlice(getSourceTable(), selection);
view.setName(currentStringKey);
currentStringKey = newStringKey;
addSlice(view);
selection = new BitmapBackedSelection();
selection.add(row);
} else {
selection.add(row);
}
}
if (!selection.isEmpty()) {
view = new TableSlice(getSourceTable(), selection);
view.setName(currentStringKey);
addSlice(view);
}
}
|
[
"private",
"void",
"splitOn",
"(",
"String",
"...",
"columnNames",
")",
"{",
"List",
"<",
"Column",
"<",
"?",
">",
">",
"columns",
"=",
"getSourceTable",
"(",
")",
".",
"columns",
"(",
"columnNames",
")",
";",
"int",
"byteSize",
"=",
"getByteSize",
"(",
"columns",
")",
";",
"byte",
"[",
"]",
"currentKey",
"=",
"null",
";",
"String",
"currentStringKey",
"=",
"null",
";",
"TableSlice",
"view",
";",
"Selection",
"selection",
"=",
"new",
"BitmapBackedSelection",
"(",
")",
";",
"for",
"(",
"int",
"row",
"=",
"0",
";",
"row",
"<",
"getSourceTable",
"(",
")",
".",
"rowCount",
"(",
")",
";",
"row",
"++",
")",
"{",
"ByteBuffer",
"byteBuffer",
"=",
"ByteBuffer",
".",
"allocate",
"(",
"byteSize",
")",
";",
"String",
"newStringKey",
"=",
"\"\"",
";",
"for",
"(",
"int",
"col",
"=",
"0",
";",
"col",
"<",
"columnNames",
".",
"length",
";",
"col",
"++",
")",
"{",
"if",
"(",
"col",
">",
"0",
")",
"{",
"newStringKey",
"=",
"newStringKey",
"+",
"SPLIT_STRING",
";",
"}",
"Column",
"<",
"?",
">",
"c",
"=",
"getSourceTable",
"(",
")",
".",
"column",
"(",
"columnNames",
"[",
"col",
"]",
")",
";",
"String",
"groupKey",
"=",
"getSourceTable",
"(",
")",
".",
"getUnformatted",
"(",
"row",
",",
"getSourceTable",
"(",
")",
".",
"columnIndex",
"(",
"c",
")",
")",
";",
"newStringKey",
"=",
"newStringKey",
"+",
"groupKey",
";",
"byteBuffer",
".",
"put",
"(",
"c",
".",
"asBytes",
"(",
"row",
")",
")",
";",
"}",
"byte",
"[",
"]",
"newKey",
"=",
"byteBuffer",
".",
"array",
"(",
")",
";",
"if",
"(",
"row",
"==",
"0",
")",
"{",
"currentKey",
"=",
"newKey",
";",
"currentStringKey",
"=",
"newStringKey",
";",
"}",
"if",
"(",
"!",
"Arrays",
".",
"equals",
"(",
"newKey",
",",
"currentKey",
")",
")",
"{",
"currentKey",
"=",
"newKey",
";",
"view",
"=",
"new",
"TableSlice",
"(",
"getSourceTable",
"(",
")",
",",
"selection",
")",
";",
"view",
".",
"setName",
"(",
"currentStringKey",
")",
";",
"currentStringKey",
"=",
"newStringKey",
";",
"addSlice",
"(",
"view",
")",
";",
"selection",
"=",
"new",
"BitmapBackedSelection",
"(",
")",
";",
"selection",
".",
"add",
"(",
"row",
")",
";",
"}",
"else",
"{",
"selection",
".",
"add",
"(",
"row",
")",
";",
"}",
"}",
"if",
"(",
"!",
"selection",
".",
"isEmpty",
"(",
")",
")",
"{",
"view",
"=",
"new",
"TableSlice",
"(",
"getSourceTable",
"(",
")",
",",
"selection",
")",
";",
"view",
".",
"setName",
"(",
"currentStringKey",
")",
";",
"addSlice",
"(",
"view",
")",
";",
"}",
"}"
] |
Splits the sourceTable table into sub-tables, grouping on the columns whose names are given in
splitColumnNames
|
[
"Splits",
"the",
"sourceTable",
"table",
"into",
"sub",
"-",
"tables",
"grouping",
"on",
"the",
"columns",
"whose",
"names",
"are",
"given",
"in",
"splitColumnNames"
] |
68a75b4098ac677e9486df5572cf13ec39f9f701
|
https://github.com/jtablesaw/tablesaw/blob/68a75b4098ac677e9486df5572cf13ec39f9f701/core/src/main/java/tech/tablesaw/table/StandardTableSliceGroup.java#L67-L115
|
17,986
|
jtablesaw/tablesaw
|
core/src/main/java/tech/tablesaw/api/ShortColumn.java
|
ShortColumn.asFloatColumn
|
@Override
public FloatColumn asFloatColumn() {
FloatArrayList values = new FloatArrayList();
for (int d : data) {
values.add(d);
}
values.trim();
return FloatColumn.create(this.name(), values.elements());
}
|
java
|
@Override
public FloatColumn asFloatColumn() {
FloatArrayList values = new FloatArrayList();
for (int d : data) {
values.add(d);
}
values.trim();
return FloatColumn.create(this.name(), values.elements());
}
|
[
"@",
"Override",
"public",
"FloatColumn",
"asFloatColumn",
"(",
")",
"{",
"FloatArrayList",
"values",
"=",
"new",
"FloatArrayList",
"(",
")",
";",
"for",
"(",
"int",
"d",
":",
"data",
")",
"{",
"values",
".",
"add",
"(",
"d",
")",
";",
"}",
"values",
".",
"trim",
"(",
")",
";",
"return",
"FloatColumn",
".",
"create",
"(",
"this",
".",
"name",
"(",
")",
",",
"values",
".",
"elements",
"(",
")",
")",
";",
"}"
] |
Returns a new FloatColumn containing a value for each value in this column, truncating if necessary.
A widening primitive conversion from an int to a float does not lose information about the overall magnitude
of a numeric value. It may, however, result in loss of precision - that is, the result may lose some of the
least significant bits of the value. In this case, the resulting floating-point value will be a correctly
rounded version of the integer value, using IEEE 754 round-to-nearest mode.
Despite the fact that a loss of precision may occur, a widening primitive conversion never results in a
run-time exception.
A missing value in the receiver is converted to a missing value in the result
|
[
"Returns",
"a",
"new",
"FloatColumn",
"containing",
"a",
"value",
"for",
"each",
"value",
"in",
"this",
"column",
"truncating",
"if",
"necessary",
"."
] |
68a75b4098ac677e9486df5572cf13ec39f9f701
|
https://github.com/jtablesaw/tablesaw/blob/68a75b4098ac677e9486df5572cf13ec39f9f701/core/src/main/java/tech/tablesaw/api/ShortColumn.java#L478-L486
|
17,987
|
jtablesaw/tablesaw
|
core/src/main/java/tech/tablesaw/api/ShortColumn.java
|
ShortColumn.asDoubleColumn
|
@Override
public DoubleColumn asDoubleColumn() {
DoubleArrayList values = new DoubleArrayList();
for (int d : data) {
values.add(d);
}
values.trim();
return DoubleColumn.create(this.name(), values.elements());
}
|
java
|
@Override
public DoubleColumn asDoubleColumn() {
DoubleArrayList values = new DoubleArrayList();
for (int d : data) {
values.add(d);
}
values.trim();
return DoubleColumn.create(this.name(), values.elements());
}
|
[
"@",
"Override",
"public",
"DoubleColumn",
"asDoubleColumn",
"(",
")",
"{",
"DoubleArrayList",
"values",
"=",
"new",
"DoubleArrayList",
"(",
")",
";",
"for",
"(",
"int",
"d",
":",
"data",
")",
"{",
"values",
".",
"add",
"(",
"d",
")",
";",
"}",
"values",
".",
"trim",
"(",
")",
";",
"return",
"DoubleColumn",
".",
"create",
"(",
"this",
".",
"name",
"(",
")",
",",
"values",
".",
"elements",
"(",
")",
")",
";",
"}"
] |
Returns a new DoubleColumn containing a value for each value in this column, truncating if necessary.
A widening primitive conversion from an int to a double does not lose information about the overall magnitude
of a numeric value. It may, however, result in loss of precision - that is, the result may lose some of the
least significant bits of the value. In this case, the resulting floating-point value will be a correctly
rounded version of the integer value, using IEEE 754 round-to-nearest mode.
Despite the fact that a loss of precision may occur, a widening primitive conversion never results in a
run-time exception.
A missing value in the receiver is converted to a missing value in the result
|
[
"Returns",
"a",
"new",
"DoubleColumn",
"containing",
"a",
"value",
"for",
"each",
"value",
"in",
"this",
"column",
"truncating",
"if",
"necessary",
"."
] |
68a75b4098ac677e9486df5572cf13ec39f9f701
|
https://github.com/jtablesaw/tablesaw/blob/68a75b4098ac677e9486df5572cf13ec39f9f701/core/src/main/java/tech/tablesaw/api/ShortColumn.java#L501-L509
|
17,988
|
jtablesaw/tablesaw
|
core/src/main/java/tech/tablesaw/io/AddCellToColumnException.java
|
AddCellToColumnException.dumpRow
|
public void dumpRow(PrintStream out) {
for (int i = 0; i < columnNames.size(); i++) {
out.print("Column ");
out.print(i);
out.print(" ");
out.print(columnNames.get(columnIndex));
out.print(" : ");
try {
out.println(line[i]);
} catch (ArrayIndexOutOfBoundsException aioobe) {
out.println("Unable to get cell " + i + " of this line");
}
}
}
|
java
|
public void dumpRow(PrintStream out) {
for (int i = 0; i < columnNames.size(); i++) {
out.print("Column ");
out.print(i);
out.print(" ");
out.print(columnNames.get(columnIndex));
out.print(" : ");
try {
out.println(line[i]);
} catch (ArrayIndexOutOfBoundsException aioobe) {
out.println("Unable to get cell " + i + " of this line");
}
}
}
|
[
"public",
"void",
"dumpRow",
"(",
"PrintStream",
"out",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"columnNames",
".",
"size",
"(",
")",
";",
"i",
"++",
")",
"{",
"out",
".",
"print",
"(",
"\"Column \"",
")",
";",
"out",
".",
"print",
"(",
"i",
")",
";",
"out",
".",
"print",
"(",
"\" \"",
")",
";",
"out",
".",
"print",
"(",
"columnNames",
".",
"get",
"(",
"columnIndex",
")",
")",
";",
"out",
".",
"print",
"(",
"\" : \"",
")",
";",
"try",
"{",
"out",
".",
"println",
"(",
"line",
"[",
"i",
"]",
")",
";",
"}",
"catch",
"(",
"ArrayIndexOutOfBoundsException",
"aioobe",
")",
"{",
"out",
".",
"println",
"(",
"\"Unable to get cell \"",
"+",
"i",
"+",
"\" of this line\"",
")",
";",
"}",
"}",
"}"
] |
Dumps to a PrintStream the information relative to the row that caused the problem
@param out The PrintStream to output to
|
[
"Dumps",
"to",
"a",
"PrintStream",
"the",
"information",
"relative",
"to",
"the",
"row",
"that",
"caused",
"the",
"problem"
] |
68a75b4098ac677e9486df5572cf13ec39f9f701
|
https://github.com/jtablesaw/tablesaw/blob/68a75b4098ac677e9486df5572cf13ec39f9f701/core/src/main/java/tech/tablesaw/io/AddCellToColumnException.java#L104-L117
|
17,989
|
jtablesaw/tablesaw
|
core/src/main/java/tech/tablesaw/api/TimeColumn.java
|
TimeColumn.asList
|
public List<LocalTime> asList() {
List<LocalTime> times = new ArrayList<>();
for (LocalTime time : this) {
times.add(time);
}
return times;
}
|
java
|
public List<LocalTime> asList() {
List<LocalTime> times = new ArrayList<>();
for (LocalTime time : this) {
times.add(time);
}
return times;
}
|
[
"public",
"List",
"<",
"LocalTime",
">",
"asList",
"(",
")",
"{",
"List",
"<",
"LocalTime",
">",
"times",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"for",
"(",
"LocalTime",
"time",
":",
"this",
")",
"{",
"times",
".",
"add",
"(",
"time",
")",
";",
"}",
"return",
"times",
";",
"}"
] |
Returns the entire contents of this column as a list
|
[
"Returns",
"the",
"entire",
"contents",
"of",
"this",
"column",
"as",
"a",
"list"
] |
68a75b4098ac677e9486df5572cf13ec39f9f701
|
https://github.com/jtablesaw/tablesaw/blob/68a75b4098ac677e9486df5572cf13ec39f9f701/core/src/main/java/tech/tablesaw/api/TimeColumn.java#L246-L252
|
17,990
|
jtablesaw/tablesaw
|
html/src/main/java/tech/tablesaw/io/html/HtmlWriter.java
|
HtmlWriter.row
|
private static Element row(int row, Table table, ElementCreator elements, HtmlWriteOptions options) {
Element tr = elements.create("tr", null, row);
for (Column<?> col : table.columns()) {
if (options.escapeText()) {
tr.appendChild(elements.create("td", col, row)
.appendText(String.valueOf(col.getString(row))));
} else {
tr.appendChild(elements.create("td", col, row)
.appendChild(new DataNode(String.valueOf(col.getString(row)))));
}
}
return tr;
}
|
java
|
private static Element row(int row, Table table, ElementCreator elements, HtmlWriteOptions options) {
Element tr = elements.create("tr", null, row);
for (Column<?> col : table.columns()) {
if (options.escapeText()) {
tr.appendChild(elements.create("td", col, row)
.appendText(String.valueOf(col.getString(row))));
} else {
tr.appendChild(elements.create("td", col, row)
.appendChild(new DataNode(String.valueOf(col.getString(row)))));
}
}
return tr;
}
|
[
"private",
"static",
"Element",
"row",
"(",
"int",
"row",
",",
"Table",
"table",
",",
"ElementCreator",
"elements",
",",
"HtmlWriteOptions",
"options",
")",
"{",
"Element",
"tr",
"=",
"elements",
".",
"create",
"(",
"\"tr\"",
",",
"null",
",",
"row",
")",
";",
"for",
"(",
"Column",
"<",
"?",
">",
"col",
":",
"table",
".",
"columns",
"(",
")",
")",
"{",
"if",
"(",
"options",
".",
"escapeText",
"(",
")",
")",
"{",
"tr",
".",
"appendChild",
"(",
"elements",
".",
"create",
"(",
"\"td\"",
",",
"col",
",",
"row",
")",
".",
"appendText",
"(",
"String",
".",
"valueOf",
"(",
"col",
".",
"getString",
"(",
"row",
")",
")",
")",
")",
";",
"}",
"else",
"{",
"tr",
".",
"appendChild",
"(",
"elements",
".",
"create",
"(",
"\"td\"",
",",
"col",
",",
"row",
")",
".",
"appendChild",
"(",
"new",
"DataNode",
"(",
"String",
".",
"valueOf",
"(",
"col",
".",
"getString",
"(",
"row",
")",
")",
")",
")",
")",
";",
"}",
"}",
"return",
"tr",
";",
"}"
] |
Returns a string containing the html output of one table row
|
[
"Returns",
"a",
"string",
"containing",
"the",
"html",
"output",
"of",
"one",
"table",
"row"
] |
68a75b4098ac677e9486df5572cf13ec39f9f701
|
https://github.com/jtablesaw/tablesaw/blob/68a75b4098ac677e9486df5572cf13ec39f9f701/html/src/main/java/tech/tablesaw/io/html/HtmlWriter.java#L62-L74
|
17,991
|
jtablesaw/tablesaw
|
core/src/main/java/tech/tablesaw/io/Source.java
|
Source.createReader
|
public Reader createReader(byte[] cachedBytes) throws IOException {
if (cachedBytes != null) {
return new InputStreamReader(new ByteArrayInputStream(cachedBytes));
}
if (inputStream != null) {
return new InputStreamReader(inputStream, charset);
}
if (reader != null) {
return reader;
}
return new InputStreamReader(new FileInputStream(file), charset);
}
|
java
|
public Reader createReader(byte[] cachedBytes) throws IOException {
if (cachedBytes != null) {
return new InputStreamReader(new ByteArrayInputStream(cachedBytes));
}
if (inputStream != null) {
return new InputStreamReader(inputStream, charset);
}
if (reader != null) {
return reader;
}
return new InputStreamReader(new FileInputStream(file), charset);
}
|
[
"public",
"Reader",
"createReader",
"(",
"byte",
"[",
"]",
"cachedBytes",
")",
"throws",
"IOException",
"{",
"if",
"(",
"cachedBytes",
"!=",
"null",
")",
"{",
"return",
"new",
"InputStreamReader",
"(",
"new",
"ByteArrayInputStream",
"(",
"cachedBytes",
")",
")",
";",
"}",
"if",
"(",
"inputStream",
"!=",
"null",
")",
"{",
"return",
"new",
"InputStreamReader",
"(",
"inputStream",
",",
"charset",
")",
";",
"}",
"if",
"(",
"reader",
"!=",
"null",
")",
"{",
"return",
"reader",
";",
"}",
"return",
"new",
"InputStreamReader",
"(",
"new",
"FileInputStream",
"(",
"file",
")",
",",
"charset",
")",
";",
"}"
] |
If cachedBytes are not null, returns a Reader created from the cachedBytes.
Otherwise, returns a Reader from the underlying source.
|
[
"If",
"cachedBytes",
"are",
"not",
"null",
"returns",
"a",
"Reader",
"created",
"from",
"the",
"cachedBytes",
".",
"Otherwise",
"returns",
"a",
"Reader",
"from",
"the",
"underlying",
"source",
"."
] |
68a75b4098ac677e9486df5572cf13ec39f9f701
|
https://github.com/jtablesaw/tablesaw/blob/68a75b4098ac677e9486df5572cf13ec39f9f701/core/src/main/java/tech/tablesaw/io/Source.java#L82-L93
|
17,992
|
jtablesaw/tablesaw
|
core/src/main/java/tech/tablesaw/api/DateTimeColumn.java
|
DateTimeColumn.asEpochSecondArray
|
public long[] asEpochSecondArray(ZoneOffset offset) {
long[] output = new long[data.size()];
for (int i = 0; i < data.size(); i++) {
LocalDateTime dateTime = PackedLocalDateTime.asLocalDateTime(data.getLong(i));
if (dateTime == null) {
output[i] = Long.MIN_VALUE;
} else {
output[i] = dateTime.toEpochSecond(offset);
}
}
return output;
}
|
java
|
public long[] asEpochSecondArray(ZoneOffset offset) {
long[] output = new long[data.size()];
for (int i = 0; i < data.size(); i++) {
LocalDateTime dateTime = PackedLocalDateTime.asLocalDateTime(data.getLong(i));
if (dateTime == null) {
output[i] = Long.MIN_VALUE;
} else {
output[i] = dateTime.toEpochSecond(offset);
}
}
return output;
}
|
[
"public",
"long",
"[",
"]",
"asEpochSecondArray",
"(",
"ZoneOffset",
"offset",
")",
"{",
"long",
"[",
"]",
"output",
"=",
"new",
"long",
"[",
"data",
".",
"size",
"(",
")",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"data",
".",
"size",
"(",
")",
";",
"i",
"++",
")",
"{",
"LocalDateTime",
"dateTime",
"=",
"PackedLocalDateTime",
".",
"asLocalDateTime",
"(",
"data",
".",
"getLong",
"(",
"i",
")",
")",
";",
"if",
"(",
"dateTime",
"==",
"null",
")",
"{",
"output",
"[",
"i",
"]",
"=",
"Long",
".",
"MIN_VALUE",
";",
"}",
"else",
"{",
"output",
"[",
"i",
"]",
"=",
"dateTime",
".",
"toEpochSecond",
"(",
"offset",
")",
";",
"}",
"}",
"return",
"output",
";",
"}"
] |
Returns the seconds from epoch for each value as an array based on the given offset
If a value is missing, Long.MIN_VALUE is used
|
[
"Returns",
"the",
"seconds",
"from",
"epoch",
"for",
"each",
"value",
"as",
"an",
"array",
"based",
"on",
"the",
"given",
"offset"
] |
68a75b4098ac677e9486df5572cf13ec39f9f701
|
https://github.com/jtablesaw/tablesaw/blob/68a75b4098ac677e9486df5572cf13ec39f9f701/core/src/main/java/tech/tablesaw/api/DateTimeColumn.java#L389-L400
|
17,993
|
jtablesaw/tablesaw
|
core/src/main/java/tech/tablesaw/api/DateTimeColumn.java
|
DateTimeColumn.asEpochMillisArray
|
public long[] asEpochMillisArray(ZoneOffset offset) {
long[] output = new long[data.size()];
for (int i = 0; i < data.size(); i++) {
LocalDateTime dateTime = PackedLocalDateTime.asLocalDateTime(data.getLong(i));
if (dateTime == null) {
output[i] = Long.MIN_VALUE;
} else {
output[i] = dateTime.toInstant(offset).toEpochMilli();
}
}
return output;
}
|
java
|
public long[] asEpochMillisArray(ZoneOffset offset) {
long[] output = new long[data.size()];
for (int i = 0; i < data.size(); i++) {
LocalDateTime dateTime = PackedLocalDateTime.asLocalDateTime(data.getLong(i));
if (dateTime == null) {
output[i] = Long.MIN_VALUE;
} else {
output[i] = dateTime.toInstant(offset).toEpochMilli();
}
}
return output;
}
|
[
"public",
"long",
"[",
"]",
"asEpochMillisArray",
"(",
"ZoneOffset",
"offset",
")",
"{",
"long",
"[",
"]",
"output",
"=",
"new",
"long",
"[",
"data",
".",
"size",
"(",
")",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"data",
".",
"size",
"(",
")",
";",
"i",
"++",
")",
"{",
"LocalDateTime",
"dateTime",
"=",
"PackedLocalDateTime",
".",
"asLocalDateTime",
"(",
"data",
".",
"getLong",
"(",
"i",
")",
")",
";",
"if",
"(",
"dateTime",
"==",
"null",
")",
"{",
"output",
"[",
"i",
"]",
"=",
"Long",
".",
"MIN_VALUE",
";",
"}",
"else",
"{",
"output",
"[",
"i",
"]",
"=",
"dateTime",
".",
"toInstant",
"(",
"offset",
")",
".",
"toEpochMilli",
"(",
")",
";",
"}",
"}",
"return",
"output",
";",
"}"
] |
Returns an array where each entry is the difference, measured in milliseconds,
between the LocalDateTime and midnight, January 1, 1970 UTC.
If a missing value is encountered, Long.MIN_VALUE is inserted in the array
|
[
"Returns",
"an",
"array",
"where",
"each",
"entry",
"is",
"the",
"difference",
"measured",
"in",
"milliseconds",
"between",
"the",
"LocalDateTime",
"and",
"midnight",
"January",
"1",
"1970",
"UTC",
"."
] |
68a75b4098ac677e9486df5572cf13ec39f9f701
|
https://github.com/jtablesaw/tablesaw/blob/68a75b4098ac677e9486df5572cf13ec39f9f701/core/src/main/java/tech/tablesaw/api/DateTimeColumn.java#L418-L429
|
17,994
|
jtablesaw/tablesaw
|
core/src/main/java/tech/tablesaw/selection/BitmapBackedSelection.java
|
BitmapBackedSelection.iterator
|
@Override
public IntIterator iterator() {
return new IntIterator() {
private final org.roaringbitmap.IntIterator iterator = bitmap.getIntIterator();
@Override
public int nextInt() {
return iterator.next();
}
@Override
public int skip(int k) {
throw new UnsupportedOperationException("Views do not support skipping in the iterator");
}
@Override
public boolean hasNext() {
return iterator.hasNext();
}
};
}
|
java
|
@Override
public IntIterator iterator() {
return new IntIterator() {
private final org.roaringbitmap.IntIterator iterator = bitmap.getIntIterator();
@Override
public int nextInt() {
return iterator.next();
}
@Override
public int skip(int k) {
throw new UnsupportedOperationException("Views do not support skipping in the iterator");
}
@Override
public boolean hasNext() {
return iterator.hasNext();
}
};
}
|
[
"@",
"Override",
"public",
"IntIterator",
"iterator",
"(",
")",
"{",
"return",
"new",
"IntIterator",
"(",
")",
"{",
"private",
"final",
"org",
".",
"roaringbitmap",
".",
"IntIterator",
"iterator",
"=",
"bitmap",
".",
"getIntIterator",
"(",
")",
";",
"@",
"Override",
"public",
"int",
"nextInt",
"(",
")",
"{",
"return",
"iterator",
".",
"next",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"int",
"skip",
"(",
"int",
"k",
")",
"{",
"throw",
"new",
"UnsupportedOperationException",
"(",
"\"Views do not support skipping in the iterator\"",
")",
";",
"}",
"@",
"Override",
"public",
"boolean",
"hasNext",
"(",
")",
"{",
"return",
"iterator",
".",
"hasNext",
"(",
")",
";",
"}",
"}",
";",
"}"
] |
Returns a fastUtil intIterator that wraps a bitmap intIterator
|
[
"Returns",
"a",
"fastUtil",
"intIterator",
"that",
"wraps",
"a",
"bitmap",
"intIterator"
] |
68a75b4098ac677e9486df5572cf13ec39f9f701
|
https://github.com/jtablesaw/tablesaw/blob/68a75b4098ac677e9486df5572cf13ec39f9f701/core/src/main/java/tech/tablesaw/selection/BitmapBackedSelection.java#L172-L194
|
17,995
|
jtablesaw/tablesaw
|
core/src/main/java/tech/tablesaw/selection/BitmapBackedSelection.java
|
BitmapBackedSelection.selectNRowsAtRandom
|
protected static Selection selectNRowsAtRandom(int n, int max) {
Selection selection = new BitmapBackedSelection();
if (n > max) {
throw new IllegalArgumentException("Illegal arguments: N (" + n + ") greater than Max (" + max + ")");
}
int[] rows = new int[n];
if (n == max) {
for (int k = 0; k < n; ++k) {
selection.add(k);
}
return selection;
}
BitSet bs = new BitSet(max);
int cardinality = 0;
Random random = new Random();
while (cardinality < n) {
int v = random.nextInt(max);
if (!bs.get(v)) {
bs.set(v);
cardinality++;
}
}
int pos = 0;
for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i + 1)) {
rows[pos++] = i;
}
for (int row : rows) {
selection.add(row);
}
return selection;
}
|
java
|
protected static Selection selectNRowsAtRandom(int n, int max) {
Selection selection = new BitmapBackedSelection();
if (n > max) {
throw new IllegalArgumentException("Illegal arguments: N (" + n + ") greater than Max (" + max + ")");
}
int[] rows = new int[n];
if (n == max) {
for (int k = 0; k < n; ++k) {
selection.add(k);
}
return selection;
}
BitSet bs = new BitSet(max);
int cardinality = 0;
Random random = new Random();
while (cardinality < n) {
int v = random.nextInt(max);
if (!bs.get(v)) {
bs.set(v);
cardinality++;
}
}
int pos = 0;
for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i + 1)) {
rows[pos++] = i;
}
for (int row : rows) {
selection.add(row);
}
return selection;
}
|
[
"protected",
"static",
"Selection",
"selectNRowsAtRandom",
"(",
"int",
"n",
",",
"int",
"max",
")",
"{",
"Selection",
"selection",
"=",
"new",
"BitmapBackedSelection",
"(",
")",
";",
"if",
"(",
"n",
">",
"max",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Illegal arguments: N (\"",
"+",
"n",
"+",
"\") greater than Max (\"",
"+",
"max",
"+",
"\")\"",
")",
";",
"}",
"int",
"[",
"]",
"rows",
"=",
"new",
"int",
"[",
"n",
"]",
";",
"if",
"(",
"n",
"==",
"max",
")",
"{",
"for",
"(",
"int",
"k",
"=",
"0",
";",
"k",
"<",
"n",
";",
"++",
"k",
")",
"{",
"selection",
".",
"add",
"(",
"k",
")",
";",
"}",
"return",
"selection",
";",
"}",
"BitSet",
"bs",
"=",
"new",
"BitSet",
"(",
"max",
")",
";",
"int",
"cardinality",
"=",
"0",
";",
"Random",
"random",
"=",
"new",
"Random",
"(",
")",
";",
"while",
"(",
"cardinality",
"<",
"n",
")",
"{",
"int",
"v",
"=",
"random",
".",
"nextInt",
"(",
"max",
")",
";",
"if",
"(",
"!",
"bs",
".",
"get",
"(",
"v",
")",
")",
"{",
"bs",
".",
"set",
"(",
"v",
")",
";",
"cardinality",
"++",
";",
"}",
"}",
"int",
"pos",
"=",
"0",
";",
"for",
"(",
"int",
"i",
"=",
"bs",
".",
"nextSetBit",
"(",
"0",
")",
";",
"i",
">=",
"0",
";",
"i",
"=",
"bs",
".",
"nextSetBit",
"(",
"i",
"+",
"1",
")",
")",
"{",
"rows",
"[",
"pos",
"++",
"]",
"=",
"i",
";",
"}",
"for",
"(",
"int",
"row",
":",
"rows",
")",
"{",
"selection",
".",
"add",
"(",
"row",
")",
";",
"}",
"return",
"selection",
";",
"}"
] |
Returns an randomly generated selection of size N where Max is the largest possible value
|
[
"Returns",
"an",
"randomly",
"generated",
"selection",
"of",
"size",
"N",
"where",
"Max",
"is",
"the",
"largest",
"possible",
"value"
] |
68a75b4098ac677e9486df5572cf13ec39f9f701
|
https://github.com/jtablesaw/tablesaw/blob/68a75b4098ac677e9486df5572cf13ec39f9f701/core/src/main/java/tech/tablesaw/selection/BitmapBackedSelection.java#L224-L256
|
17,996
|
jtablesaw/tablesaw
|
core/src/main/java/tech/tablesaw/api/BooleanColumn.java
|
BooleanColumn.get
|
@Override
public Boolean get(int i) {
byte b = data.getByte(i);
if (b == BooleanColumnType.BYTE_TRUE) {
return Boolean.TRUE;
}
if (b == BooleanColumnType.BYTE_FALSE) {
return Boolean.FALSE;
}
return null;
}
|
java
|
@Override
public Boolean get(int i) {
byte b = data.getByte(i);
if (b == BooleanColumnType.BYTE_TRUE) {
return Boolean.TRUE;
}
if (b == BooleanColumnType.BYTE_FALSE) {
return Boolean.FALSE;
}
return null;
}
|
[
"@",
"Override",
"public",
"Boolean",
"get",
"(",
"int",
"i",
")",
"{",
"byte",
"b",
"=",
"data",
".",
"getByte",
"(",
"i",
")",
";",
"if",
"(",
"b",
"==",
"BooleanColumnType",
".",
"BYTE_TRUE",
")",
"{",
"return",
"Boolean",
".",
"TRUE",
";",
"}",
"if",
"(",
"b",
"==",
"BooleanColumnType",
".",
"BYTE_FALSE",
")",
"{",
"return",
"Boolean",
".",
"FALSE",
";",
"}",
"return",
"null",
";",
"}"
] |
Returns the value in row i as a Boolean
@param i the row number
@return A Boolean object (may be null)
|
[
"Returns",
"the",
"value",
"in",
"row",
"i",
"as",
"a",
"Boolean"
] |
68a75b4098ac677e9486df5572cf13ec39f9f701
|
https://github.com/jtablesaw/tablesaw/blob/68a75b4098ac677e9486df5572cf13ec39f9f701/core/src/main/java/tech/tablesaw/api/BooleanColumn.java#L382-L392
|
17,997
|
jtablesaw/tablesaw
|
core/src/main/java/tech/tablesaw/api/BooleanColumn.java
|
BooleanColumn.set
|
public BooleanColumn set(Selection rowSelection, boolean newValue) {
for (int row : rowSelection) {
set(row, newValue);
}
return this;
}
|
java
|
public BooleanColumn set(Selection rowSelection, boolean newValue) {
for (int row : rowSelection) {
set(row, newValue);
}
return this;
}
|
[
"public",
"BooleanColumn",
"set",
"(",
"Selection",
"rowSelection",
",",
"boolean",
"newValue",
")",
"{",
"for",
"(",
"int",
"row",
":",
"rowSelection",
")",
"{",
"set",
"(",
"row",
",",
"newValue",
")",
";",
"}",
"return",
"this",
";",
"}"
] |
Conditionally update this column, replacing current values with newValue for all rows where the current value
matches the selection criteria
|
[
"Conditionally",
"update",
"this",
"column",
"replacing",
"current",
"values",
"with",
"newValue",
"for",
"all",
"rows",
"where",
"the",
"current",
"value",
"matches",
"the",
"selection",
"criteria"
] |
68a75b4098ac677e9486df5572cf13ec39f9f701
|
https://github.com/jtablesaw/tablesaw/blob/68a75b4098ac677e9486df5572cf13ec39f9f701/core/src/main/java/tech/tablesaw/api/BooleanColumn.java#L558-L563
|
17,998
|
jtablesaw/tablesaw
|
core/src/main/java/tech/tablesaw/table/Rows.java
|
Rows.copyRowsToTable
|
@SuppressWarnings({"rawtypes","unchecked"})
public static void copyRowsToTable(Selection rows, Table oldTable, Table newTable) {
for (int columnIndex = 0; columnIndex < oldTable.columnCount(); columnIndex++) {
Column oldColumn = oldTable.column(columnIndex);
int r = 0;
for (int i : rows) {
newTable.column(columnIndex).set(r, oldColumn, i);
r++;
}
}
}
|
java
|
@SuppressWarnings({"rawtypes","unchecked"})
public static void copyRowsToTable(Selection rows, Table oldTable, Table newTable) {
for (int columnIndex = 0; columnIndex < oldTable.columnCount(); columnIndex++) {
Column oldColumn = oldTable.column(columnIndex);
int r = 0;
for (int i : rows) {
newTable.column(columnIndex).set(r, oldColumn, i);
r++;
}
}
}
|
[
"@",
"SuppressWarnings",
"(",
"{",
"\"rawtypes\"",
",",
"\"unchecked\"",
"}",
")",
"public",
"static",
"void",
"copyRowsToTable",
"(",
"Selection",
"rows",
",",
"Table",
"oldTable",
",",
"Table",
"newTable",
")",
"{",
"for",
"(",
"int",
"columnIndex",
"=",
"0",
";",
"columnIndex",
"<",
"oldTable",
".",
"columnCount",
"(",
")",
";",
"columnIndex",
"++",
")",
"{",
"Column",
"oldColumn",
"=",
"oldTable",
".",
"column",
"(",
"columnIndex",
")",
";",
"int",
"r",
"=",
"0",
";",
"for",
"(",
"int",
"i",
":",
"rows",
")",
"{",
"newTable",
".",
"column",
"(",
"columnIndex",
")",
".",
"set",
"(",
"r",
",",
"oldColumn",
",",
"i",
")",
";",
"r",
"++",
";",
"}",
"}",
"}"
] |
Copies the rows indicated by the row index values in the given selection from oldTable to newTable
|
[
"Copies",
"the",
"rows",
"indicated",
"by",
"the",
"row",
"index",
"values",
"in",
"the",
"given",
"selection",
"from",
"oldTable",
"to",
"newTable"
] |
68a75b4098ac677e9486df5572cf13ec39f9f701
|
https://github.com/jtablesaw/tablesaw/blob/68a75b4098ac677e9486df5572cf13ec39f9f701/core/src/main/java/tech/tablesaw/table/Rows.java#L37-L48
|
17,999
|
jtablesaw/tablesaw
|
core/src/main/java/tech/tablesaw/io/DataFrameWriter.java
|
DataFrameWriter.csv
|
public void csv(String file) throws IOException {
CsvWriteOptions options = CsvWriteOptions.builder(file).build();
new CsvWriter().write(table, options);
}
|
java
|
public void csv(String file) throws IOException {
CsvWriteOptions options = CsvWriteOptions.builder(file).build();
new CsvWriter().write(table, options);
}
|
[
"public",
"void",
"csv",
"(",
"String",
"file",
")",
"throws",
"IOException",
"{",
"CsvWriteOptions",
"options",
"=",
"CsvWriteOptions",
".",
"builder",
"(",
"file",
")",
".",
"build",
"(",
")",
";",
"new",
"CsvWriter",
"(",
")",
".",
"write",
"(",
"table",
",",
"options",
")",
";",
"}"
] |
legacy methods left for backwards compatibility
|
[
"legacy",
"methods",
"left",
"for",
"backwards",
"compatibility"
] |
68a75b4098ac677e9486df5572cf13ec39f9f701
|
https://github.com/jtablesaw/tablesaw/blob/68a75b4098ac677e9486df5572cf13ec39f9f701/core/src/main/java/tech/tablesaw/io/DataFrameWriter.java#L77-L80
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.