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,700
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/analyzer/DependencyBundlingAnalyzer.java
|
DependencyBundlingAnalyzer.npmVersionsMatch
|
public static boolean npmVersionsMatch(String current, String next) {
String left = current;
String right = next;
if (left == null || right == null) {
return false;
}
if (left.equals(right) || "*".equals(left) || "*".equals(right)) {
return true;
}
if (left.contains(" ")) { // we have a version string from package.json
if (right.contains(" ")) { // we can't evaluate this ">=1.5.4 <2.0.0" vs "2 || 3"
return false;
}
if (!right.matches("^\\d.*$")) {
right = stripLeadingNonNumeric(right);
if (right == null) {
return false;
}
}
try {
final Semver v = new Semver(right, SemverType.NPM);
return v.satisfies(left);
} catch (SemverException ex) {
LOGGER.trace("ignore", ex);
}
} else {
if (!left.matches("^\\d.*$")) {
left = stripLeadingNonNumeric(left);
if (left == null || left.isEmpty()) {
return false;
}
}
try {
Semver v = new Semver(left, SemverType.NPM);
if (!right.isEmpty() && v.satisfies(right)) {
return true;
}
if (!right.contains(" ")) {
left = current;
right = stripLeadingNonNumeric(right);
if (right != null) {
v = new Semver(right, SemverType.NPM);
return v.satisfies(left);
}
}
} catch (SemverException ex) {
LOGGER.trace("ignore", ex);
} catch (NullPointerException ex) {
LOGGER.error("SemVer comparison error: left:\"{}\", right:\"{}\"", left, right);
LOGGER.debug("SemVer comparison resulted in NPE", ex);
}
}
return false;
}
|
java
|
public static boolean npmVersionsMatch(String current, String next) {
String left = current;
String right = next;
if (left == null || right == null) {
return false;
}
if (left.equals(right) || "*".equals(left) || "*".equals(right)) {
return true;
}
if (left.contains(" ")) { // we have a version string from package.json
if (right.contains(" ")) { // we can't evaluate this ">=1.5.4 <2.0.0" vs "2 || 3"
return false;
}
if (!right.matches("^\\d.*$")) {
right = stripLeadingNonNumeric(right);
if (right == null) {
return false;
}
}
try {
final Semver v = new Semver(right, SemverType.NPM);
return v.satisfies(left);
} catch (SemverException ex) {
LOGGER.trace("ignore", ex);
}
} else {
if (!left.matches("^\\d.*$")) {
left = stripLeadingNonNumeric(left);
if (left == null || left.isEmpty()) {
return false;
}
}
try {
Semver v = new Semver(left, SemverType.NPM);
if (!right.isEmpty() && v.satisfies(right)) {
return true;
}
if (!right.contains(" ")) {
left = current;
right = stripLeadingNonNumeric(right);
if (right != null) {
v = new Semver(right, SemverType.NPM);
return v.satisfies(left);
}
}
} catch (SemverException ex) {
LOGGER.trace("ignore", ex);
} catch (NullPointerException ex) {
LOGGER.error("SemVer comparison error: left:\"{}\", right:\"{}\"", left, right);
LOGGER.debug("SemVer comparison resulted in NPE", ex);
}
}
return false;
}
|
[
"public",
"static",
"boolean",
"npmVersionsMatch",
"(",
"String",
"current",
",",
"String",
"next",
")",
"{",
"String",
"left",
"=",
"current",
";",
"String",
"right",
"=",
"next",
";",
"if",
"(",
"left",
"==",
"null",
"||",
"right",
"==",
"null",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"left",
".",
"equals",
"(",
"right",
")",
"||",
"\"*\"",
".",
"equals",
"(",
"left",
")",
"||",
"\"*\"",
".",
"equals",
"(",
"right",
")",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"left",
".",
"contains",
"(",
"\" \"",
")",
")",
"{",
"// we have a version string from package.json",
"if",
"(",
"right",
".",
"contains",
"(",
"\" \"",
")",
")",
"{",
"// we can't evaluate this \">=1.5.4 <2.0.0\" vs \"2 || 3\"",
"return",
"false",
";",
"}",
"if",
"(",
"!",
"right",
".",
"matches",
"(",
"\"^\\\\d.*$\"",
")",
")",
"{",
"right",
"=",
"stripLeadingNonNumeric",
"(",
"right",
")",
";",
"if",
"(",
"right",
"==",
"null",
")",
"{",
"return",
"false",
";",
"}",
"}",
"try",
"{",
"final",
"Semver",
"v",
"=",
"new",
"Semver",
"(",
"right",
",",
"SemverType",
".",
"NPM",
")",
";",
"return",
"v",
".",
"satisfies",
"(",
"left",
")",
";",
"}",
"catch",
"(",
"SemverException",
"ex",
")",
"{",
"LOGGER",
".",
"trace",
"(",
"\"ignore\"",
",",
"ex",
")",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"!",
"left",
".",
"matches",
"(",
"\"^\\\\d.*$\"",
")",
")",
"{",
"left",
"=",
"stripLeadingNonNumeric",
"(",
"left",
")",
";",
"if",
"(",
"left",
"==",
"null",
"||",
"left",
".",
"isEmpty",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"}",
"try",
"{",
"Semver",
"v",
"=",
"new",
"Semver",
"(",
"left",
",",
"SemverType",
".",
"NPM",
")",
";",
"if",
"(",
"!",
"right",
".",
"isEmpty",
"(",
")",
"&&",
"v",
".",
"satisfies",
"(",
"right",
")",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"!",
"right",
".",
"contains",
"(",
"\" \"",
")",
")",
"{",
"left",
"=",
"current",
";",
"right",
"=",
"stripLeadingNonNumeric",
"(",
"right",
")",
";",
"if",
"(",
"right",
"!=",
"null",
")",
"{",
"v",
"=",
"new",
"Semver",
"(",
"right",
",",
"SemverType",
".",
"NPM",
")",
";",
"return",
"v",
".",
"satisfies",
"(",
"left",
")",
";",
"}",
"}",
"}",
"catch",
"(",
"SemverException",
"ex",
")",
"{",
"LOGGER",
".",
"trace",
"(",
"\"ignore\"",
",",
"ex",
")",
";",
"}",
"catch",
"(",
"NullPointerException",
"ex",
")",
"{",
"LOGGER",
".",
"error",
"(",
"\"SemVer comparison error: left:\\\"{}\\\", right:\\\"{}\\\"\"",
",",
"left",
",",
"right",
")",
";",
"LOGGER",
".",
"debug",
"(",
"\"SemVer comparison resulted in NPE\"",
",",
"ex",
")",
";",
"}",
"}",
"return",
"false",
";",
"}"
] |
Determine if the dependency version is equal in the given dependencies.
This method attempts to evaluate version range checks.
@param current a dependency version to compare
@param next a dependency version to compare
@return true if the version is equal in both dependencies; otherwise
false
|
[
"Determine",
"if",
"the",
"dependency",
"version",
"is",
"equal",
"in",
"the",
"given",
"dependencies",
".",
"This",
"method",
"attempts",
"to",
"evaluate",
"version",
"range",
"checks",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/analyzer/DependencyBundlingAnalyzer.java#L509-L562
|
17,701
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/analyzer/DependencyBundlingAnalyzer.java
|
DependencyBundlingAnalyzer.stripLeadingNonNumeric
|
private static String stripLeadingNonNumeric(String str) {
for (int x = 0; x < str.length(); x++) {
if (Character.isDigit(str.codePointAt(x))) {
return str.substring(x);
}
}
return null;
}
|
java
|
private static String stripLeadingNonNumeric(String str) {
for (int x = 0; x < str.length(); x++) {
if (Character.isDigit(str.codePointAt(x))) {
return str.substring(x);
}
}
return null;
}
|
[
"private",
"static",
"String",
"stripLeadingNonNumeric",
"(",
"String",
"str",
")",
"{",
"for",
"(",
"int",
"x",
"=",
"0",
";",
"x",
"<",
"str",
".",
"length",
"(",
")",
";",
"x",
"++",
")",
"{",
"if",
"(",
"Character",
".",
"isDigit",
"(",
"str",
".",
"codePointAt",
"(",
"x",
")",
")",
")",
"{",
"return",
"str",
".",
"substring",
"(",
"x",
")",
";",
"}",
"}",
"return",
"null",
";",
"}"
] |
Strips leading non-numeric values from the start of the string. If no
numbers are present this will return null.
@param str the string to modify
@return the string without leading non-numeric characters
|
[
"Strips",
"leading",
"non",
"-",
"numeric",
"values",
"from",
"the",
"start",
"of",
"the",
"string",
".",
"If",
"no",
"numbers",
"are",
"present",
"this",
"will",
"return",
"null",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/analyzer/DependencyBundlingAnalyzer.java#L571-L578
|
17,702
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/dependency/Vulnerability.java
|
Vulnerability.getReferences
|
public List<Reference> getReferences(boolean sorted) {
final List<Reference> sortedRefs = new ArrayList<>(this.references);
if (sorted) {
Collections.sort(sortedRefs);
}
return sortedRefs;
}
|
java
|
public List<Reference> getReferences(boolean sorted) {
final List<Reference> sortedRefs = new ArrayList<>(this.references);
if (sorted) {
Collections.sort(sortedRefs);
}
return sortedRefs;
}
|
[
"public",
"List",
"<",
"Reference",
">",
"getReferences",
"(",
"boolean",
"sorted",
")",
"{",
"final",
"List",
"<",
"Reference",
">",
"sortedRefs",
"=",
"new",
"ArrayList",
"<>",
"(",
"this",
".",
"references",
")",
";",
"if",
"(",
"sorted",
")",
"{",
"Collections",
".",
"sort",
"(",
"sortedRefs",
")",
";",
"}",
"return",
"sortedRefs",
";",
"}"
] |
Returns the list of references. This is primarily used within the
generated reports.
@param sorted whether the returned list should be sorted
@return the list of references
|
[
"Returns",
"the",
"list",
"of",
"references",
".",
"This",
"is",
"primarily",
"used",
"within",
"the",
"generated",
"reports",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/dependency/Vulnerability.java#L182-L188
|
17,703
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/dependency/Vulnerability.java
|
Vulnerability.addReference
|
public void addReference(String referenceSource, String referenceName, String referenceUrl) {
final Reference ref = new Reference();
ref.setSource(referenceSource);
ref.setName(referenceName);
ref.setUrl(referenceUrl);
this.references.add(ref);
}
|
java
|
public void addReference(String referenceSource, String referenceName, String referenceUrl) {
final Reference ref = new Reference();
ref.setSource(referenceSource);
ref.setName(referenceName);
ref.setUrl(referenceUrl);
this.references.add(ref);
}
|
[
"public",
"void",
"addReference",
"(",
"String",
"referenceSource",
",",
"String",
"referenceName",
",",
"String",
"referenceUrl",
")",
"{",
"final",
"Reference",
"ref",
"=",
"new",
"Reference",
"(",
")",
";",
"ref",
".",
"setSource",
"(",
"referenceSource",
")",
";",
"ref",
".",
"setName",
"(",
"referenceName",
")",
";",
"ref",
".",
"setUrl",
"(",
"referenceUrl",
")",
";",
"this",
".",
"references",
".",
"add",
"(",
"ref",
")",
";",
"}"
] |
Adds a reference.
@param referenceSource the source of the reference
@param referenceName the referenceName of the reference
@param referenceUrl the url of the reference
|
[
"Adds",
"a",
"reference",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/dependency/Vulnerability.java#L215-L221
|
17,704
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/dependency/Vulnerability.java
|
Vulnerability.getVulnerableSoftware
|
public List<VulnerableSoftware> getVulnerableSoftware(boolean sorted) {
final List<VulnerableSoftware> sortedVulnerableSoftware = new ArrayList<>(this.vulnerableSoftware);
if (sorted) {
Collections.sort(sortedVulnerableSoftware);
}
return sortedVulnerableSoftware;
}
|
java
|
public List<VulnerableSoftware> getVulnerableSoftware(boolean sorted) {
final List<VulnerableSoftware> sortedVulnerableSoftware = new ArrayList<>(this.vulnerableSoftware);
if (sorted) {
Collections.sort(sortedVulnerableSoftware);
}
return sortedVulnerableSoftware;
}
|
[
"public",
"List",
"<",
"VulnerableSoftware",
">",
"getVulnerableSoftware",
"(",
"boolean",
"sorted",
")",
"{",
"final",
"List",
"<",
"VulnerableSoftware",
">",
"sortedVulnerableSoftware",
"=",
"new",
"ArrayList",
"<>",
"(",
"this",
".",
"vulnerableSoftware",
")",
";",
"if",
"(",
"sorted",
")",
"{",
"Collections",
".",
"sort",
"(",
"sortedVulnerableSoftware",
")",
";",
"}",
"return",
"sortedVulnerableSoftware",
";",
"}"
] |
Returns a sorted list of vulnerable software. This is primarily used for
display within reports.
@param sorted whether or not the list should be sorted
@return the list of vulnerable software
|
[
"Returns",
"a",
"sorted",
"list",
"of",
"vulnerable",
"software",
".",
"This",
"is",
"primarily",
"used",
"for",
"display",
"within",
"reports",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/dependency/Vulnerability.java#L239-L245
|
17,705
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/dependency/Vulnerability.java
|
Vulnerability.compareTo
|
@Override
public int compareTo(Vulnerability v) {
return new CompareToBuilder()
.append(this.name, v.name)
.toComparison();
}
|
java
|
@Override
public int compareTo(Vulnerability v) {
return new CompareToBuilder()
.append(this.name, v.name)
.toComparison();
}
|
[
"@",
"Override",
"public",
"int",
"compareTo",
"(",
"Vulnerability",
"v",
")",
"{",
"return",
"new",
"CompareToBuilder",
"(",
")",
".",
"append",
"(",
"this",
".",
"name",
",",
"v",
".",
"name",
")",
".",
"toComparison",
"(",
")",
";",
"}"
] |
Compares two vulnerabilities.
@param v a vulnerability to be compared
@return a negative integer, zero, or a positive integer as this object is
less than, equal to, or greater than the specified vulnerability
|
[
"Compares",
"two",
"vulnerabilities",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/dependency/Vulnerability.java#L407-L412
|
17,706
|
jeremylong/DependencyCheck
|
maven/src/main/java/org/owasp/dependencycheck/maven/BaseDependencyCheckMojo.java
|
BaseDependencyCheckMojo.artifactsMatch
|
private static boolean artifactsMatch(org.apache.maven.model.Dependency d, Artifact a) {
return isEqualOrNull(a.getArtifactId(), d.getArtifactId())
&& isEqualOrNull(a.getGroupId(), d.getGroupId())
&& isEqualOrNull(a.getVersion(), d.getVersion());
}
|
java
|
private static boolean artifactsMatch(org.apache.maven.model.Dependency d, Artifact a) {
return isEqualOrNull(a.getArtifactId(), d.getArtifactId())
&& isEqualOrNull(a.getGroupId(), d.getGroupId())
&& isEqualOrNull(a.getVersion(), d.getVersion());
}
|
[
"private",
"static",
"boolean",
"artifactsMatch",
"(",
"org",
".",
"apache",
".",
"maven",
".",
"model",
".",
"Dependency",
"d",
",",
"Artifact",
"a",
")",
"{",
"return",
"isEqualOrNull",
"(",
"a",
".",
"getArtifactId",
"(",
")",
",",
"d",
".",
"getArtifactId",
"(",
")",
")",
"&&",
"isEqualOrNull",
"(",
"a",
".",
"getGroupId",
"(",
")",
",",
"d",
".",
"getGroupId",
"(",
")",
")",
"&&",
"isEqualOrNull",
"(",
"a",
".",
"getVersion",
"(",
")",
",",
"d",
".",
"getVersion",
"(",
")",
")",
";",
"}"
] |
Determines if the groupId, artifactId, and version of the Maven
dependency and artifact match.
@param d the Maven dependency
@param a the Maven artifact
@return true if the groupId, artifactId, and version match
|
[
"Determines",
"if",
"the",
"groupId",
"artifactId",
"and",
"version",
"of",
"the",
"Maven",
"dependency",
"and",
"artifact",
"match",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/maven/src/main/java/org/owasp/dependencycheck/maven/BaseDependencyCheckMojo.java#L683-L687
|
17,707
|
jeremylong/DependencyCheck
|
maven/src/main/java/org/owasp/dependencycheck/maven/BaseDependencyCheckMojo.java
|
BaseDependencyCheckMojo.isEqualOrNull
|
private static boolean isEqualOrNull(String left, String right) {
return (left != null && left.equals(right)) || (left == null && right == null);
}
|
java
|
private static boolean isEqualOrNull(String left, String right) {
return (left != null && left.equals(right)) || (left == null && right == null);
}
|
[
"private",
"static",
"boolean",
"isEqualOrNull",
"(",
"String",
"left",
",",
"String",
"right",
")",
"{",
"return",
"(",
"left",
"!=",
"null",
"&&",
"left",
".",
"equals",
"(",
"right",
")",
")",
"||",
"(",
"left",
"==",
"null",
"&&",
"right",
"==",
"null",
")",
";",
"}"
] |
Compares two strings for equality; if both strings are null they are
considered equal.
@param left the first string to compare
@param right the second string to compare
@return true if the strings are equal or if they are both null; otherwise
false.
|
[
"Compares",
"two",
"strings",
"for",
"equality",
";",
"if",
"both",
"strings",
"are",
"null",
"they",
"are",
"considered",
"equal",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/maven/src/main/java/org/owasp/dependencycheck/maven/BaseDependencyCheckMojo.java#L698-L700
|
17,708
|
jeremylong/DependencyCheck
|
maven/src/main/java/org/owasp/dependencycheck/maven/BaseDependencyCheckMojo.java
|
BaseDependencyCheckMojo.execute
|
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
generatingSite = false;
final boolean shouldSkip = Boolean.parseBoolean(System.getProperty("dependency-check.skip", Boolean.toString(skip)));
if (shouldSkip) {
getLog().info("Skipping " + getName(Locale.US));
} else {
project.setContextValue("dependency-check-output-dir", this.outputDirectory);
runCheck();
}
}
|
java
|
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
generatingSite = false;
final boolean shouldSkip = Boolean.parseBoolean(System.getProperty("dependency-check.skip", Boolean.toString(skip)));
if (shouldSkip) {
getLog().info("Skipping " + getName(Locale.US));
} else {
project.setContextValue("dependency-check-output-dir", this.outputDirectory);
runCheck();
}
}
|
[
"@",
"Override",
"public",
"void",
"execute",
"(",
")",
"throws",
"MojoExecutionException",
",",
"MojoFailureException",
"{",
"generatingSite",
"=",
"false",
";",
"final",
"boolean",
"shouldSkip",
"=",
"Boolean",
".",
"parseBoolean",
"(",
"System",
".",
"getProperty",
"(",
"\"dependency-check.skip\"",
",",
"Boolean",
".",
"toString",
"(",
"skip",
")",
")",
")",
";",
"if",
"(",
"shouldSkip",
")",
"{",
"getLog",
"(",
")",
".",
"info",
"(",
"\"Skipping \"",
"+",
"getName",
"(",
"Locale",
".",
"US",
")",
")",
";",
"}",
"else",
"{",
"project",
".",
"setContextValue",
"(",
"\"dependency-check-output-dir\"",
",",
"this",
".",
"outputDirectory",
")",
";",
"runCheck",
"(",
")",
";",
"}",
"}"
] |
Executes dependency-check.
@throws MojoExecutionException thrown if there is an exception executing
the mojo
@throws MojoFailureException thrown if dependency-check failed the build
|
[
"Executes",
"dependency",
"-",
"check",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/maven/src/main/java/org/owasp/dependencycheck/maven/BaseDependencyCheckMojo.java#L709-L719
|
17,709
|
jeremylong/DependencyCheck
|
maven/src/main/java/org/owasp/dependencycheck/maven/BaseDependencyCheckMojo.java
|
BaseDependencyCheckMojo.getCorrectOutputDirectory
|
protected File getCorrectOutputDirectory(MavenProject current) {
final Object obj = current.getContextValue("dependency-check-output-dir");
if (obj != null && obj instanceof File) {
return (File) obj;
}//else we guess
File target = new File(current.getBuild().getDirectory());
if (target.getParentFile() != null && "target".equals(target.getParentFile().getName())) {
target = target.getParentFile();
}
return target;
}
|
java
|
protected File getCorrectOutputDirectory(MavenProject current) {
final Object obj = current.getContextValue("dependency-check-output-dir");
if (obj != null && obj instanceof File) {
return (File) obj;
}//else we guess
File target = new File(current.getBuild().getDirectory());
if (target.getParentFile() != null && "target".equals(target.getParentFile().getName())) {
target = target.getParentFile();
}
return target;
}
|
[
"protected",
"File",
"getCorrectOutputDirectory",
"(",
"MavenProject",
"current",
")",
"{",
"final",
"Object",
"obj",
"=",
"current",
".",
"getContextValue",
"(",
"\"dependency-check-output-dir\"",
")",
";",
"if",
"(",
"obj",
"!=",
"null",
"&&",
"obj",
"instanceof",
"File",
")",
"{",
"return",
"(",
"File",
")",
"obj",
";",
"}",
"//else we guess",
"File",
"target",
"=",
"new",
"File",
"(",
"current",
".",
"getBuild",
"(",
")",
".",
"getDirectory",
"(",
")",
")",
";",
"if",
"(",
"target",
".",
"getParentFile",
"(",
")",
"!=",
"null",
"&&",
"\"target\"",
".",
"equals",
"(",
"target",
".",
"getParentFile",
"(",
")",
".",
"getName",
"(",
")",
")",
")",
"{",
"target",
"=",
"target",
".",
"getParentFile",
"(",
")",
";",
"}",
"return",
"target",
";",
"}"
] |
Returns the correct output directory depending on if a site is being
executed or not.
@param current the Maven project to get the output directory from
@return the directory to write the report(s)
|
[
"Returns",
"the",
"correct",
"output",
"directory",
"depending",
"on",
"if",
"a",
"site",
"is",
"being",
"executed",
"or",
"not",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/maven/src/main/java/org/owasp/dependencycheck/maven/BaseDependencyCheckMojo.java#L808-L818
|
17,710
|
jeremylong/DependencyCheck
|
maven/src/main/java/org/owasp/dependencycheck/maven/BaseDependencyCheckMojo.java
|
BaseDependencyCheckMojo.toDependencyNode
|
private DependencyNode toDependencyNode(ProjectBuildingRequest buildingRequest, DependencyNode parent,
org.apache.maven.model.Dependency dependency) throws ArtifactResolverException {
final DefaultArtifactCoordinate coordinate = new DefaultArtifactCoordinate();
coordinate.setGroupId(dependency.getGroupId());
coordinate.setArtifactId(dependency.getArtifactId());
coordinate.setVersion(dependency.getVersion());
final ArtifactType type = session.getRepositorySession().getArtifactTypeRegistry().get(dependency.getType());
coordinate.setExtension(type.getExtension());
coordinate.setClassifier(type.getClassifier());
final Artifact artifact = artifactResolver.resolveArtifact(buildingRequest, coordinate).getArtifact();
artifact.setScope(dependency.getScope());
final DefaultDependencyNode node = new DefaultDependencyNode(parent, artifact, dependency.getVersion(), dependency.getScope(), null);
return node;
}
|
java
|
private DependencyNode toDependencyNode(ProjectBuildingRequest buildingRequest, DependencyNode parent,
org.apache.maven.model.Dependency dependency) throws ArtifactResolverException {
final DefaultArtifactCoordinate coordinate = new DefaultArtifactCoordinate();
coordinate.setGroupId(dependency.getGroupId());
coordinate.setArtifactId(dependency.getArtifactId());
coordinate.setVersion(dependency.getVersion());
final ArtifactType type = session.getRepositorySession().getArtifactTypeRegistry().get(dependency.getType());
coordinate.setExtension(type.getExtension());
coordinate.setClassifier(type.getClassifier());
final Artifact artifact = artifactResolver.resolveArtifact(buildingRequest, coordinate).getArtifact();
artifact.setScope(dependency.getScope());
final DefaultDependencyNode node = new DefaultDependencyNode(parent, artifact, dependency.getVersion(), dependency.getScope(), null);
return node;
}
|
[
"private",
"DependencyNode",
"toDependencyNode",
"(",
"ProjectBuildingRequest",
"buildingRequest",
",",
"DependencyNode",
"parent",
",",
"org",
".",
"apache",
".",
"maven",
".",
"model",
".",
"Dependency",
"dependency",
")",
"throws",
"ArtifactResolverException",
"{",
"final",
"DefaultArtifactCoordinate",
"coordinate",
"=",
"new",
"DefaultArtifactCoordinate",
"(",
")",
";",
"coordinate",
".",
"setGroupId",
"(",
"dependency",
".",
"getGroupId",
"(",
")",
")",
";",
"coordinate",
".",
"setArtifactId",
"(",
"dependency",
".",
"getArtifactId",
"(",
")",
")",
";",
"coordinate",
".",
"setVersion",
"(",
"dependency",
".",
"getVersion",
"(",
")",
")",
";",
"final",
"ArtifactType",
"type",
"=",
"session",
".",
"getRepositorySession",
"(",
")",
".",
"getArtifactTypeRegistry",
"(",
")",
".",
"get",
"(",
"dependency",
".",
"getType",
"(",
")",
")",
";",
"coordinate",
".",
"setExtension",
"(",
"type",
".",
"getExtension",
"(",
")",
")",
";",
"coordinate",
".",
"setClassifier",
"(",
"type",
".",
"getClassifier",
"(",
")",
")",
";",
"final",
"Artifact",
"artifact",
"=",
"artifactResolver",
".",
"resolveArtifact",
"(",
"buildingRequest",
",",
"coordinate",
")",
".",
"getArtifact",
"(",
")",
";",
"artifact",
".",
"setScope",
"(",
"dependency",
".",
"getScope",
"(",
")",
")",
";",
"final",
"DefaultDependencyNode",
"node",
"=",
"new",
"DefaultDependencyNode",
"(",
"parent",
",",
"artifact",
",",
"dependency",
".",
"getVersion",
"(",
")",
",",
"dependency",
".",
"getScope",
"(",
")",
",",
"null",
")",
";",
"return",
"node",
";",
"}"
] |
Converts the dependency to a dependency node object.
@param buildingRequest the Maven project building request
@param parent the parent node
@param dependency the dependency to convert
@return the resulting dependency node
@throws ArtifactResolverException thrown if the artifact could not be
retrieved
|
[
"Converts",
"the",
"dependency",
"to",
"a",
"dependency",
"node",
"object",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/maven/src/main/java/org/owasp/dependencycheck/maven/BaseDependencyCheckMojo.java#L882-L903
|
17,711
|
jeremylong/DependencyCheck
|
maven/src/main/java/org/owasp/dependencycheck/maven/BaseDependencyCheckMojo.java
|
BaseDependencyCheckMojo.collectDependencyManagementDependencies
|
private ExceptionCollection collectDependencyManagementDependencies(ProjectBuildingRequest buildingRequest, MavenProject project,
List<DependencyNode> nodes, boolean aggregate) {
if (skipDependencyManagement || project.getDependencyManagement() == null) {
return null;
}
ExceptionCollection exCol = null;
for (org.apache.maven.model.Dependency dependency : project.getDependencyManagement().getDependencies()) {
try {
nodes.add(toDependencyNode(buildingRequest, null, dependency));
} catch (ArtifactResolverException ex) {
getLog().debug(String.format("Aggregate : %s", aggregate));
if (exCol == null) {
exCol = new ExceptionCollection();
}
exCol.addException(ex);
}
}
return exCol;
}
|
java
|
private ExceptionCollection collectDependencyManagementDependencies(ProjectBuildingRequest buildingRequest, MavenProject project,
List<DependencyNode> nodes, boolean aggregate) {
if (skipDependencyManagement || project.getDependencyManagement() == null) {
return null;
}
ExceptionCollection exCol = null;
for (org.apache.maven.model.Dependency dependency : project.getDependencyManagement().getDependencies()) {
try {
nodes.add(toDependencyNode(buildingRequest, null, dependency));
} catch (ArtifactResolverException ex) {
getLog().debug(String.format("Aggregate : %s", aggregate));
if (exCol == null) {
exCol = new ExceptionCollection();
}
exCol.addException(ex);
}
}
return exCol;
}
|
[
"private",
"ExceptionCollection",
"collectDependencyManagementDependencies",
"(",
"ProjectBuildingRequest",
"buildingRequest",
",",
"MavenProject",
"project",
",",
"List",
"<",
"DependencyNode",
">",
"nodes",
",",
"boolean",
"aggregate",
")",
"{",
"if",
"(",
"skipDependencyManagement",
"||",
"project",
".",
"getDependencyManagement",
"(",
")",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"ExceptionCollection",
"exCol",
"=",
"null",
";",
"for",
"(",
"org",
".",
"apache",
".",
"maven",
".",
"model",
".",
"Dependency",
"dependency",
":",
"project",
".",
"getDependencyManagement",
"(",
")",
".",
"getDependencies",
"(",
")",
")",
"{",
"try",
"{",
"nodes",
".",
"add",
"(",
"toDependencyNode",
"(",
"buildingRequest",
",",
"null",
",",
"dependency",
")",
")",
";",
"}",
"catch",
"(",
"ArtifactResolverException",
"ex",
")",
"{",
"getLog",
"(",
")",
".",
"debug",
"(",
"String",
".",
"format",
"(",
"\"Aggregate : %s\"",
",",
"aggregate",
")",
")",
";",
"if",
"(",
"exCol",
"==",
"null",
")",
"{",
"exCol",
"=",
"new",
"ExceptionCollection",
"(",
")",
";",
"}",
"exCol",
".",
"addException",
"(",
"ex",
")",
";",
"}",
"}",
"return",
"exCol",
";",
"}"
] |
Collect dependencies from the dependency management section.
@param buildingRequest the Maven project building request
@param project the project being analyzed
@param nodes the list of dependency nodes
@param aggregate whether or not this is an aggregate analysis
@return a collection of exceptions if any occurred; otherwise
<code>null</code>
|
[
"Collect",
"dependencies",
"from",
"the",
"dependency",
"management",
"section",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/maven/src/main/java/org/owasp/dependencycheck/maven/BaseDependencyCheckMojo.java#L915-L934
|
17,712
|
jeremylong/DependencyCheck
|
maven/src/main/java/org/owasp/dependencycheck/maven/BaseDependencyCheckMojo.java
|
BaseDependencyCheckMojo.runCheck
|
protected void runCheck() throws MojoExecutionException, MojoFailureException {
try (Engine engine = initializeEngine()) {
ExceptionCollection exCol = scanDependencies(engine);
try {
engine.analyzeDependencies();
} catch (ExceptionCollection ex) {
exCol = handleAnalysisExceptions(exCol, ex);
}
if (exCol == null || !exCol.isFatal()) {
File outputDir = getCorrectOutputDirectory(this.getProject());
if (outputDir == null) {
//in some regards we shouldn't be writing this, but we are anyway.
//we shouldn't write this because nothing is configured to generate this report.
outputDir = new File(this.getProject().getBuild().getDirectory());
}
try {
final MavenProject p = this.getProject();
engine.writeReports(p.getName(), p.getGroupId(), p.getArtifactId(), p.getVersion(), outputDir, getFormat());
} catch (ReportException ex) {
if (exCol == null) {
exCol = new ExceptionCollection(ex);
} else {
exCol.addException(ex);
}
if (this.isFailOnError()) {
throw new MojoExecutionException("One or more exceptions occurred during dependency-check analysis", exCol);
} else {
getLog().debug("Error writing the report", ex);
}
}
showSummary(this.getProject(), engine.getDependencies());
checkForFailure(engine.getDependencies());
if (exCol != null && this.isFailOnError()) {
throw new MojoExecutionException("One or more exceptions occurred during dependency-check analysis", exCol);
}
}
} catch (DatabaseException ex) {
if (getLog().isDebugEnabled()) {
getLog().debug("Database connection error", ex);
}
final String msg = "An exception occurred connecting to the local database. Please see the log file for more details.";
if (this.isFailOnError()) {
throw new MojoExecutionException(msg, ex);
}
getLog().error(msg, ex);
} finally {
getSettings().cleanup();
}
}
|
java
|
protected void runCheck() throws MojoExecutionException, MojoFailureException {
try (Engine engine = initializeEngine()) {
ExceptionCollection exCol = scanDependencies(engine);
try {
engine.analyzeDependencies();
} catch (ExceptionCollection ex) {
exCol = handleAnalysisExceptions(exCol, ex);
}
if (exCol == null || !exCol.isFatal()) {
File outputDir = getCorrectOutputDirectory(this.getProject());
if (outputDir == null) {
//in some regards we shouldn't be writing this, but we are anyway.
//we shouldn't write this because nothing is configured to generate this report.
outputDir = new File(this.getProject().getBuild().getDirectory());
}
try {
final MavenProject p = this.getProject();
engine.writeReports(p.getName(), p.getGroupId(), p.getArtifactId(), p.getVersion(), outputDir, getFormat());
} catch (ReportException ex) {
if (exCol == null) {
exCol = new ExceptionCollection(ex);
} else {
exCol.addException(ex);
}
if (this.isFailOnError()) {
throw new MojoExecutionException("One or more exceptions occurred during dependency-check analysis", exCol);
} else {
getLog().debug("Error writing the report", ex);
}
}
showSummary(this.getProject(), engine.getDependencies());
checkForFailure(engine.getDependencies());
if (exCol != null && this.isFailOnError()) {
throw new MojoExecutionException("One or more exceptions occurred during dependency-check analysis", exCol);
}
}
} catch (DatabaseException ex) {
if (getLog().isDebugEnabled()) {
getLog().debug("Database connection error", ex);
}
final String msg = "An exception occurred connecting to the local database. Please see the log file for more details.";
if (this.isFailOnError()) {
throw new MojoExecutionException(msg, ex);
}
getLog().error(msg, ex);
} finally {
getSettings().cleanup();
}
}
|
[
"protected",
"void",
"runCheck",
"(",
")",
"throws",
"MojoExecutionException",
",",
"MojoFailureException",
"{",
"try",
"(",
"Engine",
"engine",
"=",
"initializeEngine",
"(",
")",
")",
"{",
"ExceptionCollection",
"exCol",
"=",
"scanDependencies",
"(",
"engine",
")",
";",
"try",
"{",
"engine",
".",
"analyzeDependencies",
"(",
")",
";",
"}",
"catch",
"(",
"ExceptionCollection",
"ex",
")",
"{",
"exCol",
"=",
"handleAnalysisExceptions",
"(",
"exCol",
",",
"ex",
")",
";",
"}",
"if",
"(",
"exCol",
"==",
"null",
"||",
"!",
"exCol",
".",
"isFatal",
"(",
")",
")",
"{",
"File",
"outputDir",
"=",
"getCorrectOutputDirectory",
"(",
"this",
".",
"getProject",
"(",
")",
")",
";",
"if",
"(",
"outputDir",
"==",
"null",
")",
"{",
"//in some regards we shouldn't be writing this, but we are anyway.",
"//we shouldn't write this because nothing is configured to generate this report.",
"outputDir",
"=",
"new",
"File",
"(",
"this",
".",
"getProject",
"(",
")",
".",
"getBuild",
"(",
")",
".",
"getDirectory",
"(",
")",
")",
";",
"}",
"try",
"{",
"final",
"MavenProject",
"p",
"=",
"this",
".",
"getProject",
"(",
")",
";",
"engine",
".",
"writeReports",
"(",
"p",
".",
"getName",
"(",
")",
",",
"p",
".",
"getGroupId",
"(",
")",
",",
"p",
".",
"getArtifactId",
"(",
")",
",",
"p",
".",
"getVersion",
"(",
")",
",",
"outputDir",
",",
"getFormat",
"(",
")",
")",
";",
"}",
"catch",
"(",
"ReportException",
"ex",
")",
"{",
"if",
"(",
"exCol",
"==",
"null",
")",
"{",
"exCol",
"=",
"new",
"ExceptionCollection",
"(",
"ex",
")",
";",
"}",
"else",
"{",
"exCol",
".",
"addException",
"(",
"ex",
")",
";",
"}",
"if",
"(",
"this",
".",
"isFailOnError",
"(",
")",
")",
"{",
"throw",
"new",
"MojoExecutionException",
"(",
"\"One or more exceptions occurred during dependency-check analysis\"",
",",
"exCol",
")",
";",
"}",
"else",
"{",
"getLog",
"(",
")",
".",
"debug",
"(",
"\"Error writing the report\"",
",",
"ex",
")",
";",
"}",
"}",
"showSummary",
"(",
"this",
".",
"getProject",
"(",
")",
",",
"engine",
".",
"getDependencies",
"(",
")",
")",
";",
"checkForFailure",
"(",
"engine",
".",
"getDependencies",
"(",
")",
")",
";",
"if",
"(",
"exCol",
"!=",
"null",
"&&",
"this",
".",
"isFailOnError",
"(",
")",
")",
"{",
"throw",
"new",
"MojoExecutionException",
"(",
"\"One or more exceptions occurred during dependency-check analysis\"",
",",
"exCol",
")",
";",
"}",
"}",
"}",
"catch",
"(",
"DatabaseException",
"ex",
")",
"{",
"if",
"(",
"getLog",
"(",
")",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"getLog",
"(",
")",
".",
"debug",
"(",
"\"Database connection error\"",
",",
"ex",
")",
";",
"}",
"final",
"String",
"msg",
"=",
"\"An exception occurred connecting to the local database. Please see the log file for more details.\"",
";",
"if",
"(",
"this",
".",
"isFailOnError",
"(",
")",
")",
"{",
"throw",
"new",
"MojoExecutionException",
"(",
"msg",
",",
"ex",
")",
";",
"}",
"getLog",
"(",
")",
".",
"error",
"(",
"msg",
",",
"ex",
")",
";",
"}",
"finally",
"{",
"getSettings",
"(",
")",
".",
"cleanup",
"(",
")",
";",
"}",
"}"
] |
Executes the dependency-check scan and generates the necessary report.
@throws MojoExecutionException thrown if there is an exception running
the scan
@throws MojoFailureException thrown if dependency-check is configured to
fail the build
|
[
"Executes",
"the",
"dependency",
"-",
"check",
"scan",
"and",
"generates",
"the",
"necessary",
"report",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/maven/src/main/java/org/owasp/dependencycheck/maven/BaseDependencyCheckMojo.java#L1313-L1362
|
17,713
|
jeremylong/DependencyCheck
|
maven/src/main/java/org/owasp/dependencycheck/maven/BaseDependencyCheckMojo.java
|
BaseDependencyCheckMojo.handleAnalysisExceptions
|
private ExceptionCollection handleAnalysisExceptions(ExceptionCollection currentEx, ExceptionCollection newEx) throws MojoExecutionException {
ExceptionCollection returnEx = currentEx;
if (returnEx == null) {
returnEx = newEx;
} else {
returnEx.getExceptions().addAll(newEx.getExceptions());
if (newEx.isFatal()) {
returnEx.setFatal(true);
}
}
if (returnEx.isFatal()) {
final String msg = String.format("Fatal exception(s) analyzing %s", getProject().getName());
if (this.isFailOnError()) {
throw new MojoExecutionException(msg, returnEx);
}
getLog().error(msg);
if (getLog().isDebugEnabled()) {
getLog().debug(returnEx);
}
} else {
final String msg = String.format("Exception(s) analyzing %s", getProject().getName());
if (getLog().isDebugEnabled()) {
getLog().debug(msg, returnEx);
}
}
return returnEx;
}
|
java
|
private ExceptionCollection handleAnalysisExceptions(ExceptionCollection currentEx, ExceptionCollection newEx) throws MojoExecutionException {
ExceptionCollection returnEx = currentEx;
if (returnEx == null) {
returnEx = newEx;
} else {
returnEx.getExceptions().addAll(newEx.getExceptions());
if (newEx.isFatal()) {
returnEx.setFatal(true);
}
}
if (returnEx.isFatal()) {
final String msg = String.format("Fatal exception(s) analyzing %s", getProject().getName());
if (this.isFailOnError()) {
throw new MojoExecutionException(msg, returnEx);
}
getLog().error(msg);
if (getLog().isDebugEnabled()) {
getLog().debug(returnEx);
}
} else {
final String msg = String.format("Exception(s) analyzing %s", getProject().getName());
if (getLog().isDebugEnabled()) {
getLog().debug(msg, returnEx);
}
}
return returnEx;
}
|
[
"private",
"ExceptionCollection",
"handleAnalysisExceptions",
"(",
"ExceptionCollection",
"currentEx",
",",
"ExceptionCollection",
"newEx",
")",
"throws",
"MojoExecutionException",
"{",
"ExceptionCollection",
"returnEx",
"=",
"currentEx",
";",
"if",
"(",
"returnEx",
"==",
"null",
")",
"{",
"returnEx",
"=",
"newEx",
";",
"}",
"else",
"{",
"returnEx",
".",
"getExceptions",
"(",
")",
".",
"addAll",
"(",
"newEx",
".",
"getExceptions",
"(",
")",
")",
";",
"if",
"(",
"newEx",
".",
"isFatal",
"(",
")",
")",
"{",
"returnEx",
".",
"setFatal",
"(",
"true",
")",
";",
"}",
"}",
"if",
"(",
"returnEx",
".",
"isFatal",
"(",
")",
")",
"{",
"final",
"String",
"msg",
"=",
"String",
".",
"format",
"(",
"\"Fatal exception(s) analyzing %s\"",
",",
"getProject",
"(",
")",
".",
"getName",
"(",
")",
")",
";",
"if",
"(",
"this",
".",
"isFailOnError",
"(",
")",
")",
"{",
"throw",
"new",
"MojoExecutionException",
"(",
"msg",
",",
"returnEx",
")",
";",
"}",
"getLog",
"(",
")",
".",
"error",
"(",
"msg",
")",
";",
"if",
"(",
"getLog",
"(",
")",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"getLog",
"(",
")",
".",
"debug",
"(",
"returnEx",
")",
";",
"}",
"}",
"else",
"{",
"final",
"String",
"msg",
"=",
"String",
".",
"format",
"(",
"\"Exception(s) analyzing %s\"",
",",
"getProject",
"(",
")",
".",
"getName",
"(",
")",
")",
";",
"if",
"(",
"getLog",
"(",
")",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"getLog",
"(",
")",
".",
"debug",
"(",
"msg",
",",
"returnEx",
")",
";",
"}",
"}",
"return",
"returnEx",
";",
"}"
] |
Combines the two exception collections and if either are fatal, throw an
MojoExecutionException
@param currentEx the primary exception collection
@param newEx the new exception collection to add
@return the combined exception collection
@throws MojoExecutionException thrown if dependency-check is configured
to fail on errors
|
[
"Combines",
"the",
"two",
"exception",
"collections",
"and",
"if",
"either",
"are",
"fatal",
"throw",
"an",
"MojoExecutionException"
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/maven/src/main/java/org/owasp/dependencycheck/maven/BaseDependencyCheckMojo.java#L1374-L1400
|
17,714
|
jeremylong/DependencyCheck
|
maven/src/main/java/org/owasp/dependencycheck/maven/BaseDependencyCheckMojo.java
|
BaseDependencyCheckMojo.getOutputName
|
@Override
public String getOutputName() {
if ("HTML".equalsIgnoreCase(this.format) || "ALL".equalsIgnoreCase(this.format)) {
return "dependency-check-report";
} else if ("XML".equalsIgnoreCase(this.format)) {
return "dependency-check-report.xml";
} else if ("JUNIT".equalsIgnoreCase(this.format)) {
return "dependency-check-junit.xml";
} else if ("JSON".equalsIgnoreCase(this.format)) {
return "dependency-check-report.json";
} else if ("CSV".equalsIgnoreCase(this.format)) {
return "dependency-check-report.csv";
} else {
getLog().warn("Unknown report format used during site generation.");
return "dependency-check-report";
}
}
|
java
|
@Override
public String getOutputName() {
if ("HTML".equalsIgnoreCase(this.format) || "ALL".equalsIgnoreCase(this.format)) {
return "dependency-check-report";
} else if ("XML".equalsIgnoreCase(this.format)) {
return "dependency-check-report.xml";
} else if ("JUNIT".equalsIgnoreCase(this.format)) {
return "dependency-check-junit.xml";
} else if ("JSON".equalsIgnoreCase(this.format)) {
return "dependency-check-report.json";
} else if ("CSV".equalsIgnoreCase(this.format)) {
return "dependency-check-report.csv";
} else {
getLog().warn("Unknown report format used during site generation.");
return "dependency-check-report";
}
}
|
[
"@",
"Override",
"public",
"String",
"getOutputName",
"(",
")",
"{",
"if",
"(",
"\"HTML\"",
".",
"equalsIgnoreCase",
"(",
"this",
".",
"format",
")",
"||",
"\"ALL\"",
".",
"equalsIgnoreCase",
"(",
"this",
".",
"format",
")",
")",
"{",
"return",
"\"dependency-check-report\"",
";",
"}",
"else",
"if",
"(",
"\"XML\"",
".",
"equalsIgnoreCase",
"(",
"this",
".",
"format",
")",
")",
"{",
"return",
"\"dependency-check-report.xml\"",
";",
"}",
"else",
"if",
"(",
"\"JUNIT\"",
".",
"equalsIgnoreCase",
"(",
"this",
".",
"format",
")",
")",
"{",
"return",
"\"dependency-check-junit.xml\"",
";",
"}",
"else",
"if",
"(",
"\"JSON\"",
".",
"equalsIgnoreCase",
"(",
"this",
".",
"format",
")",
")",
"{",
"return",
"\"dependency-check-report.json\"",
";",
"}",
"else",
"if",
"(",
"\"CSV\"",
".",
"equalsIgnoreCase",
"(",
"this",
".",
"format",
")",
")",
"{",
"return",
"\"dependency-check-report.csv\"",
";",
"}",
"else",
"{",
"getLog",
"(",
")",
".",
"warn",
"(",
"\"Unknown report format used during site generation.\"",
")",
";",
"return",
"\"dependency-check-report\"",
";",
"}",
"}"
] |
Returns the output name.
@return the output name
|
[
"Returns",
"the",
"output",
"name",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/maven/src/main/java/org/owasp/dependencycheck/maven/BaseDependencyCheckMojo.java#L1456-L1472
|
17,715
|
jeremylong/DependencyCheck
|
maven/src/main/java/org/owasp/dependencycheck/maven/BaseDependencyCheckMojo.java
|
BaseDependencyCheckMojo.decryptServerPassword
|
private String decryptServerPassword(Server server) throws SecDispatcherException {
//CSOFF: LineLength
//The following fix was copied from:
// https://github.com/bsorrentino/maven-confluence-plugin/blob/master/maven-confluence-reporting-plugin/src/main/java/org/bsc/maven/confluence/plugin/AbstractBaseConfluenceMojo.java
//
// FIX to resolve
// org.sonatype.plexus.components.sec.dispatcher.SecDispatcherException:
// java.io.FileNotFoundException: ~/.settings-security.xml (No such file or directory)
//
//CSON: LineLength
if (securityDispatcher instanceof DefaultSecDispatcher) {
((DefaultSecDispatcher) securityDispatcher).setConfigurationFile("~/.m2/settings-security.xml");
}
return securityDispatcher.decrypt(server.getPassword());
}
|
java
|
private String decryptServerPassword(Server server) throws SecDispatcherException {
//CSOFF: LineLength
//The following fix was copied from:
// https://github.com/bsorrentino/maven-confluence-plugin/blob/master/maven-confluence-reporting-plugin/src/main/java/org/bsc/maven/confluence/plugin/AbstractBaseConfluenceMojo.java
//
// FIX to resolve
// org.sonatype.plexus.components.sec.dispatcher.SecDispatcherException:
// java.io.FileNotFoundException: ~/.settings-security.xml (No such file or directory)
//
//CSON: LineLength
if (securityDispatcher instanceof DefaultSecDispatcher) {
((DefaultSecDispatcher) securityDispatcher).setConfigurationFile("~/.m2/settings-security.xml");
}
return securityDispatcher.decrypt(server.getPassword());
}
|
[
"private",
"String",
"decryptServerPassword",
"(",
"Server",
"server",
")",
"throws",
"SecDispatcherException",
"{",
"//CSOFF: LineLength",
"//The following fix was copied from:",
"// https://github.com/bsorrentino/maven-confluence-plugin/blob/master/maven-confluence-reporting-plugin/src/main/java/org/bsc/maven/confluence/plugin/AbstractBaseConfluenceMojo.java",
"//",
"// FIX to resolve",
"// org.sonatype.plexus.components.sec.dispatcher.SecDispatcherException:",
"// java.io.FileNotFoundException: ~/.settings-security.xml (No such file or directory)",
"//",
"//CSON: LineLength",
"if",
"(",
"securityDispatcher",
"instanceof",
"DefaultSecDispatcher",
")",
"{",
"(",
"(",
"DefaultSecDispatcher",
")",
"securityDispatcher",
")",
".",
"setConfigurationFile",
"(",
"\"~/.m2/settings-security.xml\"",
")",
";",
"}",
"return",
"securityDispatcher",
".",
"decrypt",
"(",
"server",
".",
"getPassword",
"(",
")",
")",
";",
"}"
] |
Obtains the configured password for the given server.
@param server the configured server from the settings.xml
@return the decrypted password from the Maven configuration
@throws SecDispatcherException thrown if there is an error decrypting the
password
|
[
"Obtains",
"the",
"configured",
"password",
"for",
"the",
"given",
"server",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/maven/src/main/java/org/owasp/dependencycheck/maven/BaseDependencyCheckMojo.java#L1688-L1703
|
17,716
|
jeremylong/DependencyCheck
|
maven/src/main/java/org/owasp/dependencycheck/maven/BaseDependencyCheckMojo.java
|
BaseDependencyCheckMojo.determineSuppressions
|
private String[] determineSuppressions() {
String[] suppressions = suppressionFiles;
if (suppressionFile != null) {
if (suppressions == null) {
suppressions = new String[]{suppressionFile};
} else {
suppressions = Arrays.copyOf(suppressions, suppressions.length + 1);
suppressions[suppressions.length - 1] = suppressionFile;
}
}
return suppressions;
}
|
java
|
private String[] determineSuppressions() {
String[] suppressions = suppressionFiles;
if (suppressionFile != null) {
if (suppressions == null) {
suppressions = new String[]{suppressionFile};
} else {
suppressions = Arrays.copyOf(suppressions, suppressions.length + 1);
suppressions[suppressions.length - 1] = suppressionFile;
}
}
return suppressions;
}
|
[
"private",
"String",
"[",
"]",
"determineSuppressions",
"(",
")",
"{",
"String",
"[",
"]",
"suppressions",
"=",
"suppressionFiles",
";",
"if",
"(",
"suppressionFile",
"!=",
"null",
")",
"{",
"if",
"(",
"suppressions",
"==",
"null",
")",
"{",
"suppressions",
"=",
"new",
"String",
"[",
"]",
"{",
"suppressionFile",
"}",
";",
"}",
"else",
"{",
"suppressions",
"=",
"Arrays",
".",
"copyOf",
"(",
"suppressions",
",",
"suppressions",
".",
"length",
"+",
"1",
")",
";",
"suppressions",
"[",
"suppressions",
".",
"length",
"-",
"1",
"]",
"=",
"suppressionFile",
";",
"}",
"}",
"return",
"suppressions",
";",
"}"
] |
Combines the configured suppressionFile and suppressionFiles into a
single array.
@return an array of suppression file paths
|
[
"Combines",
"the",
"configured",
"suppressionFile",
"and",
"suppressionFiles",
"into",
"a",
"single",
"array",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/maven/src/main/java/org/owasp/dependencycheck/maven/BaseDependencyCheckMojo.java#L1711-L1722
|
17,717
|
jeremylong/DependencyCheck
|
maven/src/main/java/org/owasp/dependencycheck/maven/BaseDependencyCheckMojo.java
|
BaseDependencyCheckMojo.getMavenProxy
|
private Proxy getMavenProxy() {
if (mavenSettings != null) {
final List<Proxy> proxies = mavenSettings.getProxies();
if (proxies != null && !proxies.isEmpty()) {
if (mavenSettingsProxyId != null) {
for (Proxy proxy : proxies) {
if (mavenSettingsProxyId.equalsIgnoreCase(proxy.getId())) {
return proxy;
}
}
} else {
for (Proxy aProxy : proxies) {
if (aProxy.isActive()) {
return aProxy;
}
}
}
}
}
return null;
}
|
java
|
private Proxy getMavenProxy() {
if (mavenSettings != null) {
final List<Proxy> proxies = mavenSettings.getProxies();
if (proxies != null && !proxies.isEmpty()) {
if (mavenSettingsProxyId != null) {
for (Proxy proxy : proxies) {
if (mavenSettingsProxyId.equalsIgnoreCase(proxy.getId())) {
return proxy;
}
}
} else {
for (Proxy aProxy : proxies) {
if (aProxy.isActive()) {
return aProxy;
}
}
}
}
}
return null;
}
|
[
"private",
"Proxy",
"getMavenProxy",
"(",
")",
"{",
"if",
"(",
"mavenSettings",
"!=",
"null",
")",
"{",
"final",
"List",
"<",
"Proxy",
">",
"proxies",
"=",
"mavenSettings",
".",
"getProxies",
"(",
")",
";",
"if",
"(",
"proxies",
"!=",
"null",
"&&",
"!",
"proxies",
".",
"isEmpty",
"(",
")",
")",
"{",
"if",
"(",
"mavenSettingsProxyId",
"!=",
"null",
")",
"{",
"for",
"(",
"Proxy",
"proxy",
":",
"proxies",
")",
"{",
"if",
"(",
"mavenSettingsProxyId",
".",
"equalsIgnoreCase",
"(",
"proxy",
".",
"getId",
"(",
")",
")",
")",
"{",
"return",
"proxy",
";",
"}",
"}",
"}",
"else",
"{",
"for",
"(",
"Proxy",
"aProxy",
":",
"proxies",
")",
"{",
"if",
"(",
"aProxy",
".",
"isActive",
"(",
")",
")",
"{",
"return",
"aProxy",
";",
"}",
"}",
"}",
"}",
"}",
"return",
"null",
";",
"}"
] |
Returns the maven proxy.
@return the maven proxy
|
[
"Returns",
"the",
"maven",
"proxy",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/maven/src/main/java/org/owasp/dependencycheck/maven/BaseDependencyCheckMojo.java#L1729-L1749
|
17,718
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/data/nvdcve/CveDB.java
|
CveDB.determineEcosystem
|
private String determineEcosystem(String baseEcosystem, String vendor, String product, String targetSw) {
if ("ibm".equals(vendor) && "java".equals(product)) {
return "c/c++";
}
if ("oracle".equals(vendor) && "vm".equals(product)) {
return "c/c++";
}
if ("*".equals(targetSw) || baseEcosystem != null) {
return baseEcosystem;
}
return targetSw;
}
|
java
|
private String determineEcosystem(String baseEcosystem, String vendor, String product, String targetSw) {
if ("ibm".equals(vendor) && "java".equals(product)) {
return "c/c++";
}
if ("oracle".equals(vendor) && "vm".equals(product)) {
return "c/c++";
}
if ("*".equals(targetSw) || baseEcosystem != null) {
return baseEcosystem;
}
return targetSw;
}
|
[
"private",
"String",
"determineEcosystem",
"(",
"String",
"baseEcosystem",
",",
"String",
"vendor",
",",
"String",
"product",
",",
"String",
"targetSw",
")",
"{",
"if",
"(",
"\"ibm\"",
".",
"equals",
"(",
"vendor",
")",
"&&",
"\"java\"",
".",
"equals",
"(",
"product",
")",
")",
"{",
"return",
"\"c/c++\"",
";",
"}",
"if",
"(",
"\"oracle\"",
".",
"equals",
"(",
"vendor",
")",
"&&",
"\"vm\"",
".",
"equals",
"(",
"product",
")",
")",
"{",
"return",
"\"c/c++\"",
";",
"}",
"if",
"(",
"\"*\"",
".",
"equals",
"(",
"targetSw",
")",
"||",
"baseEcosystem",
"!=",
"null",
")",
"{",
"return",
"baseEcosystem",
";",
"}",
"return",
"targetSw",
";",
"}"
] |
Attempts to determine the ecosystem based on the vendor, product and
targetSw.
@param baseEcosystem the base ecosystem
@param vendor the vendor
@param product the product
@param targetSw the target software
@return the ecosystem if one is identified
|
[
"Attempts",
"to",
"determine",
"the",
"ecosystem",
"based",
"on",
"the",
"vendor",
"product",
"and",
"targetSw",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/data/nvdcve/CveDB.java#L222-L233
|
17,719
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/data/nvdcve/CveDB.java
|
CveDB.determineDatabaseProductName
|
private String determineDatabaseProductName(Connection conn) {
try {
final String databaseProductName = conn.getMetaData().getDatabaseProductName().toLowerCase();
LOGGER.debug("Database product: {}", databaseProductName);
return databaseProductName;
} catch (SQLException se) {
LOGGER.warn("Problem determining database product!", se);
return null;
}
}
|
java
|
private String determineDatabaseProductName(Connection conn) {
try {
final String databaseProductName = conn.getMetaData().getDatabaseProductName().toLowerCase();
LOGGER.debug("Database product: {}", databaseProductName);
return databaseProductName;
} catch (SQLException se) {
LOGGER.warn("Problem determining database product!", se);
return null;
}
}
|
[
"private",
"String",
"determineDatabaseProductName",
"(",
"Connection",
"conn",
")",
"{",
"try",
"{",
"final",
"String",
"databaseProductName",
"=",
"conn",
".",
"getMetaData",
"(",
")",
".",
"getDatabaseProductName",
"(",
")",
".",
"toLowerCase",
"(",
")",
";",
"LOGGER",
".",
"debug",
"(",
"\"Database product: {}\"",
",",
"databaseProductName",
")",
";",
"return",
"databaseProductName",
";",
"}",
"catch",
"(",
"SQLException",
"se",
")",
"{",
"LOGGER",
".",
"warn",
"(",
"\"Problem determining database product!\"",
",",
"se",
")",
";",
"return",
"null",
";",
"}",
"}"
] |
Tries to determine the product name of the database.
@param conn the database connection
@return the product name of the database if successful, {@code null} else
|
[
"Tries",
"to",
"determine",
"the",
"product",
"name",
"of",
"the",
"database",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/data/nvdcve/CveDB.java#L367-L376
|
17,720
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/data/nvdcve/CveDB.java
|
CveDB.open
|
private synchronized void open() throws DatabaseException {
try {
if (!isOpen()) {
connection = connectionFactory.getConnection();
final String databaseProductName = determineDatabaseProductName(this.connection);
statementBundle = databaseProductName != null
? ResourceBundle.getBundle("data/dbStatements", new Locale(databaseProductName))
: ResourceBundle.getBundle("data/dbStatements");
prepareStatements();
databaseProperties = new DatabaseProperties(this);
}
} catch (DatabaseException e) {
releaseResources();
throw e;
}
}
|
java
|
private synchronized void open() throws DatabaseException {
try {
if (!isOpen()) {
connection = connectionFactory.getConnection();
final String databaseProductName = determineDatabaseProductName(this.connection);
statementBundle = databaseProductName != null
? ResourceBundle.getBundle("data/dbStatements", new Locale(databaseProductName))
: ResourceBundle.getBundle("data/dbStatements");
prepareStatements();
databaseProperties = new DatabaseProperties(this);
}
} catch (DatabaseException e) {
releaseResources();
throw e;
}
}
|
[
"private",
"synchronized",
"void",
"open",
"(",
")",
"throws",
"DatabaseException",
"{",
"try",
"{",
"if",
"(",
"!",
"isOpen",
"(",
")",
")",
"{",
"connection",
"=",
"connectionFactory",
".",
"getConnection",
"(",
")",
";",
"final",
"String",
"databaseProductName",
"=",
"determineDatabaseProductName",
"(",
"this",
".",
"connection",
")",
";",
"statementBundle",
"=",
"databaseProductName",
"!=",
"null",
"?",
"ResourceBundle",
".",
"getBundle",
"(",
"\"data/dbStatements\"",
",",
"new",
"Locale",
"(",
"databaseProductName",
")",
")",
":",
"ResourceBundle",
".",
"getBundle",
"(",
"\"data/dbStatements\"",
")",
";",
"prepareStatements",
"(",
")",
";",
"databaseProperties",
"=",
"new",
"DatabaseProperties",
"(",
"this",
")",
";",
"}",
"}",
"catch",
"(",
"DatabaseException",
"e",
")",
"{",
"releaseResources",
"(",
")",
";",
"throw",
"e",
";",
"}",
"}"
] |
Opens the database connection. If the database does not exist, it will
create a new one.
@throws DatabaseException thrown if there is an error opening the
database connection
|
[
"Opens",
"the",
"database",
"connection",
".",
"If",
"the",
"database",
"does",
"not",
"exist",
"it",
"will",
"create",
"a",
"new",
"one",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/data/nvdcve/CveDB.java#L385-L400
|
17,721
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/data/nvdcve/CveDB.java
|
CveDB.close
|
@Override
public synchronized void close() {
if (isOpen()) {
clearCache();
closeStatements();
try {
connection.close();
} catch (SQLException ex) {
LOGGER.error("There was an error attempting to close the CveDB, see the log for more details.");
LOGGER.debug("", ex);
} catch (Throwable ex) {
LOGGER.error("There was an exception attempting to close the CveDB, see the log for more details.");
LOGGER.debug("", ex);
}
releaseResources();
connectionFactory.cleanup();
}
}
|
java
|
@Override
public synchronized void close() {
if (isOpen()) {
clearCache();
closeStatements();
try {
connection.close();
} catch (SQLException ex) {
LOGGER.error("There was an error attempting to close the CveDB, see the log for more details.");
LOGGER.debug("", ex);
} catch (Throwable ex) {
LOGGER.error("There was an exception attempting to close the CveDB, see the log for more details.");
LOGGER.debug("", ex);
}
releaseResources();
connectionFactory.cleanup();
}
}
|
[
"@",
"Override",
"public",
"synchronized",
"void",
"close",
"(",
")",
"{",
"if",
"(",
"isOpen",
"(",
")",
")",
"{",
"clearCache",
"(",
")",
";",
"closeStatements",
"(",
")",
";",
"try",
"{",
"connection",
".",
"close",
"(",
")",
";",
"}",
"catch",
"(",
"SQLException",
"ex",
")",
"{",
"LOGGER",
".",
"error",
"(",
"\"There was an error attempting to close the CveDB, see the log for more details.\"",
")",
";",
"LOGGER",
".",
"debug",
"(",
"\"\"",
",",
"ex",
")",
";",
"}",
"catch",
"(",
"Throwable",
"ex",
")",
"{",
"LOGGER",
".",
"error",
"(",
"\"There was an exception attempting to close the CveDB, see the log for more details.\"",
")",
";",
"LOGGER",
".",
"debug",
"(",
"\"\"",
",",
"ex",
")",
";",
"}",
"releaseResources",
"(",
")",
";",
"connectionFactory",
".",
"cleanup",
"(",
")",
";",
"}",
"}"
] |
Closes the database connection. Close should be called on this object
when it is done being used.
|
[
"Closes",
"the",
"database",
"connection",
".",
"Close",
"should",
"be",
"called",
"on",
"this",
"object",
"when",
"it",
"is",
"done",
"being",
"used",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/data/nvdcve/CveDB.java#L406-L423
|
17,722
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/data/nvdcve/CveDB.java
|
CveDB.prepareStatements
|
private void prepareStatements() throws DatabaseException {
for (PreparedStatementCveDb key : values()) {
PreparedStatement preparedStatement = null;
try {
final String statementString = statementBundle.getString(key.name());
if (key == INSERT_VULNERABILITY || key == INSERT_CPE) {
preparedStatement = connection.prepareStatement(statementString, new String[]{"id"});
} else {
preparedStatement = connection.prepareStatement(statementString);
}
} catch (SQLException ex) {
throw new DatabaseException(ex);
} catch (MissingResourceException ex) {
if (!ex.getMessage().contains("key MERGE_PROPERTY")) {
throw new DatabaseException(ex);
}
}
if (preparedStatement != null) {
preparedStatements.put(key, preparedStatement);
}
}
}
|
java
|
private void prepareStatements() throws DatabaseException {
for (PreparedStatementCveDb key : values()) {
PreparedStatement preparedStatement = null;
try {
final String statementString = statementBundle.getString(key.name());
if (key == INSERT_VULNERABILITY || key == INSERT_CPE) {
preparedStatement = connection.prepareStatement(statementString, new String[]{"id"});
} else {
preparedStatement = connection.prepareStatement(statementString);
}
} catch (SQLException ex) {
throw new DatabaseException(ex);
} catch (MissingResourceException ex) {
if (!ex.getMessage().contains("key MERGE_PROPERTY")) {
throw new DatabaseException(ex);
}
}
if (preparedStatement != null) {
preparedStatements.put(key, preparedStatement);
}
}
}
|
[
"private",
"void",
"prepareStatements",
"(",
")",
"throws",
"DatabaseException",
"{",
"for",
"(",
"PreparedStatementCveDb",
"key",
":",
"values",
"(",
")",
")",
"{",
"PreparedStatement",
"preparedStatement",
"=",
"null",
";",
"try",
"{",
"final",
"String",
"statementString",
"=",
"statementBundle",
".",
"getString",
"(",
"key",
".",
"name",
"(",
")",
")",
";",
"if",
"(",
"key",
"==",
"INSERT_VULNERABILITY",
"||",
"key",
"==",
"INSERT_CPE",
")",
"{",
"preparedStatement",
"=",
"connection",
".",
"prepareStatement",
"(",
"statementString",
",",
"new",
"String",
"[",
"]",
"{",
"\"id\"",
"}",
")",
";",
"}",
"else",
"{",
"preparedStatement",
"=",
"connection",
".",
"prepareStatement",
"(",
"statementString",
")",
";",
"}",
"}",
"catch",
"(",
"SQLException",
"ex",
")",
"{",
"throw",
"new",
"DatabaseException",
"(",
"ex",
")",
";",
"}",
"catch",
"(",
"MissingResourceException",
"ex",
")",
"{",
"if",
"(",
"!",
"ex",
".",
"getMessage",
"(",
")",
".",
"contains",
"(",
"\"key MERGE_PROPERTY\"",
")",
")",
"{",
"throw",
"new",
"DatabaseException",
"(",
"ex",
")",
";",
"}",
"}",
"if",
"(",
"preparedStatement",
"!=",
"null",
")",
"{",
"preparedStatements",
".",
"put",
"(",
"key",
",",
"preparedStatement",
")",
";",
"}",
"}",
"}"
] |
Prepares all statements to be used.
@throws DatabaseException thrown if there is an error preparing the
statements
|
[
"Prepares",
"all",
"statements",
"to",
"be",
"used",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/data/nvdcve/CveDB.java#L450-L471
|
17,723
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/data/nvdcve/CveDB.java
|
CveDB.prepareStatement
|
private PreparedStatement prepareStatement(PreparedStatementCveDb key) throws DatabaseException {
PreparedStatement preparedStatement = null;
try {
final String statementString = statementBundle.getString(key.name());
if (key == INSERT_VULNERABILITY || key == INSERT_CPE) {
preparedStatement = connection.prepareStatement(statementString, Statement.RETURN_GENERATED_KEYS);
} else {
preparedStatement = connection.prepareStatement(statementString);
}
} catch (SQLException ex) {
throw new DatabaseException(ex);
} catch (MissingResourceException ex) {
if (!ex.getMessage().contains("key MERGE_PROPERTY")) {
throw new DatabaseException(ex);
}
}
return preparedStatement;
}
|
java
|
private PreparedStatement prepareStatement(PreparedStatementCveDb key) throws DatabaseException {
PreparedStatement preparedStatement = null;
try {
final String statementString = statementBundle.getString(key.name());
if (key == INSERT_VULNERABILITY || key == INSERT_CPE) {
preparedStatement = connection.prepareStatement(statementString, Statement.RETURN_GENERATED_KEYS);
} else {
preparedStatement = connection.prepareStatement(statementString);
}
} catch (SQLException ex) {
throw new DatabaseException(ex);
} catch (MissingResourceException ex) {
if (!ex.getMessage().contains("key MERGE_PROPERTY")) {
throw new DatabaseException(ex);
}
}
return preparedStatement;
}
|
[
"private",
"PreparedStatement",
"prepareStatement",
"(",
"PreparedStatementCveDb",
"key",
")",
"throws",
"DatabaseException",
"{",
"PreparedStatement",
"preparedStatement",
"=",
"null",
";",
"try",
"{",
"final",
"String",
"statementString",
"=",
"statementBundle",
".",
"getString",
"(",
"key",
".",
"name",
"(",
")",
")",
";",
"if",
"(",
"key",
"==",
"INSERT_VULNERABILITY",
"||",
"key",
"==",
"INSERT_CPE",
")",
"{",
"preparedStatement",
"=",
"connection",
".",
"prepareStatement",
"(",
"statementString",
",",
"Statement",
".",
"RETURN_GENERATED_KEYS",
")",
";",
"}",
"else",
"{",
"preparedStatement",
"=",
"connection",
".",
"prepareStatement",
"(",
"statementString",
")",
";",
"}",
"}",
"catch",
"(",
"SQLException",
"ex",
")",
"{",
"throw",
"new",
"DatabaseException",
"(",
"ex",
")",
";",
"}",
"catch",
"(",
"MissingResourceException",
"ex",
")",
"{",
"if",
"(",
"!",
"ex",
".",
"getMessage",
"(",
")",
".",
"contains",
"(",
"\"key MERGE_PROPERTY\"",
")",
")",
"{",
"throw",
"new",
"DatabaseException",
"(",
"ex",
")",
";",
"}",
"}",
"return",
"preparedStatement",
";",
"}"
] |
Creates a prepared statement from the given key. The SQL is stored in a
properties file and the key is used to lookup the specific query.
@param key the key to select the prepared statement from the properties
file
@return the prepared statement
@throws DatabaseException throw if there is an error generating the
prepared statement
|
[
"Creates",
"a",
"prepared",
"statement",
"from",
"the",
"given",
"key",
".",
"The",
"SQL",
"is",
"stored",
"in",
"a",
"properties",
"file",
"and",
"the",
"key",
"is",
"used",
"to",
"lookup",
"the",
"specific",
"query",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/data/nvdcve/CveDB.java#L483-L500
|
17,724
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/data/artifactory/ArtifactorySearch.java
|
ArtifactorySearch.connect
|
private HttpURLConnection connect(URL url) throws IOException {
LOGGER.debug("Searching Artifactory url {}", url);
// Determine if we need to use a proxy. The rules:
// 1) If the proxy is set, AND the setting is set to true, use the proxy
// 2) Otherwise, don't use the proxy (either the proxy isn't configured,
// or proxy is specifically set to false)
final URLConnectionFactory factory = new URLConnectionFactory(settings);
final HttpURLConnection conn = factory.createHttpURLConnection(url, useProxy);
conn.setDoOutput(true);
conn.addRequestProperty("X-Result-Detail", "info");
final String username = settings.getString(Settings.KEYS.ANALYZER_ARTIFACTORY_API_USERNAME);
final String apiToken = settings.getString(Settings.KEYS.ANALYZER_ARTIFACTORY_API_TOKEN);
if (username != null && apiToken != null) {
final String userpassword = username + ":" + apiToken;
final String encodedAuthorization = Base64.getEncoder().encodeToString(userpassword.getBytes(StandardCharsets.UTF_8));
conn.addRequestProperty("Authorization", "Basic " + encodedAuthorization);
} else {
final String bearerToken = settings.getString(Settings.KEYS.ANALYZER_ARTIFACTORY_BEARER_TOKEN);
if (bearerToken != null) {
conn.addRequestProperty("Authorization", "Bearer " + bearerToken);
}
}
conn.connect();
return conn;
}
|
java
|
private HttpURLConnection connect(URL url) throws IOException {
LOGGER.debug("Searching Artifactory url {}", url);
// Determine if we need to use a proxy. The rules:
// 1) If the proxy is set, AND the setting is set to true, use the proxy
// 2) Otherwise, don't use the proxy (either the proxy isn't configured,
// or proxy is specifically set to false)
final URLConnectionFactory factory = new URLConnectionFactory(settings);
final HttpURLConnection conn = factory.createHttpURLConnection(url, useProxy);
conn.setDoOutput(true);
conn.addRequestProperty("X-Result-Detail", "info");
final String username = settings.getString(Settings.KEYS.ANALYZER_ARTIFACTORY_API_USERNAME);
final String apiToken = settings.getString(Settings.KEYS.ANALYZER_ARTIFACTORY_API_TOKEN);
if (username != null && apiToken != null) {
final String userpassword = username + ":" + apiToken;
final String encodedAuthorization = Base64.getEncoder().encodeToString(userpassword.getBytes(StandardCharsets.UTF_8));
conn.addRequestProperty("Authorization", "Basic " + encodedAuthorization);
} else {
final String bearerToken = settings.getString(Settings.KEYS.ANALYZER_ARTIFACTORY_BEARER_TOKEN);
if (bearerToken != null) {
conn.addRequestProperty("Authorization", "Bearer " + bearerToken);
}
}
conn.connect();
return conn;
}
|
[
"private",
"HttpURLConnection",
"connect",
"(",
"URL",
"url",
")",
"throws",
"IOException",
"{",
"LOGGER",
".",
"debug",
"(",
"\"Searching Artifactory url {}\"",
",",
"url",
")",
";",
"// Determine if we need to use a proxy. The rules:",
"// 1) If the proxy is set, AND the setting is set to true, use the proxy",
"// 2) Otherwise, don't use the proxy (either the proxy isn't configured,",
"// or proxy is specifically set to false)",
"final",
"URLConnectionFactory",
"factory",
"=",
"new",
"URLConnectionFactory",
"(",
"settings",
")",
";",
"final",
"HttpURLConnection",
"conn",
"=",
"factory",
".",
"createHttpURLConnection",
"(",
"url",
",",
"useProxy",
")",
";",
"conn",
".",
"setDoOutput",
"(",
"true",
")",
";",
"conn",
".",
"addRequestProperty",
"(",
"\"X-Result-Detail\"",
",",
"\"info\"",
")",
";",
"final",
"String",
"username",
"=",
"settings",
".",
"getString",
"(",
"Settings",
".",
"KEYS",
".",
"ANALYZER_ARTIFACTORY_API_USERNAME",
")",
";",
"final",
"String",
"apiToken",
"=",
"settings",
".",
"getString",
"(",
"Settings",
".",
"KEYS",
".",
"ANALYZER_ARTIFACTORY_API_TOKEN",
")",
";",
"if",
"(",
"username",
"!=",
"null",
"&&",
"apiToken",
"!=",
"null",
")",
"{",
"final",
"String",
"userpassword",
"=",
"username",
"+",
"\":\"",
"+",
"apiToken",
";",
"final",
"String",
"encodedAuthorization",
"=",
"Base64",
".",
"getEncoder",
"(",
")",
".",
"encodeToString",
"(",
"userpassword",
".",
"getBytes",
"(",
"StandardCharsets",
".",
"UTF_8",
")",
")",
";",
"conn",
".",
"addRequestProperty",
"(",
"\"Authorization\"",
",",
"\"Basic \"",
"+",
"encodedAuthorization",
")",
";",
"}",
"else",
"{",
"final",
"String",
"bearerToken",
"=",
"settings",
".",
"getString",
"(",
"Settings",
".",
"KEYS",
".",
"ANALYZER_ARTIFACTORY_BEARER_TOKEN",
")",
";",
"if",
"(",
"bearerToken",
"!=",
"null",
")",
"{",
"conn",
".",
"addRequestProperty",
"(",
"\"Authorization\"",
",",
"\"Bearer \"",
"+",
"bearerToken",
")",
";",
"}",
"}",
"conn",
".",
"connect",
"(",
")",
";",
"return",
"conn",
";",
"}"
] |
Makes an connection to the given URL.
@param url the URL to connect to
@return the HTTP URL Connection
@throws IOException thrown if there is an error making the connection
|
[
"Makes",
"an",
"connection",
"to",
"the",
"given",
"URL",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/data/artifactory/ArtifactorySearch.java#L145-L173
|
17,725
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/data/artifactory/ArtifactorySearch.java
|
ArtifactorySearch.processResponse
|
protected List<MavenArtifact> processResponse(Dependency dependency, HttpURLConnection conn) throws IOException {
final JsonObject asJsonObject;
try (final InputStreamReader streamReader = new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8)) {
asJsonObject = new JsonParser().parse(streamReader).getAsJsonObject();
}
final JsonArray results = asJsonObject.getAsJsonArray("results");
final int numFound = results.size();
if (numFound == 0) {
throw new FileNotFoundException("Artifact " + dependency + " not found in Artifactory");
}
final List<MavenArtifact> result = new ArrayList<>(numFound);
for (JsonElement jsonElement : results) {
final JsonObject checksumList = jsonElement.getAsJsonObject().getAsJsonObject("checksums");
final JsonPrimitive sha256Primitive = checksumList.getAsJsonPrimitive("sha256");
final String sha1 = checksumList.getAsJsonPrimitive("sha1").getAsString();
final String sha256 = sha256Primitive == null ? null : sha256Primitive.getAsString();
final String md5 = checksumList.getAsJsonPrimitive("md5").getAsString();
checkHashes(dependency, sha1, sha256, md5);
final String downloadUri = jsonElement.getAsJsonObject().getAsJsonPrimitive("downloadUri").getAsString();
final String path = jsonElement.getAsJsonObject().getAsJsonPrimitive("path").getAsString();
final Matcher pathMatcher = PATH_PATTERN.matcher(path);
if (!pathMatcher.matches()) {
throw new IllegalStateException("Cannot extract the Maven information from the apth retrieved in Artifactory " + path);
}
final String groupId = pathMatcher.group("groupId").replace('/', '.');
final String artifactId = pathMatcher.group("artifactId");
final String version = pathMatcher.group("version");
result.add(new MavenArtifact(groupId, artifactId, version, downloadUri, MavenArtifact.derivePomUrl(artifactId, version, downloadUri)));
}
return result;
}
|
java
|
protected List<MavenArtifact> processResponse(Dependency dependency, HttpURLConnection conn) throws IOException {
final JsonObject asJsonObject;
try (final InputStreamReader streamReader = new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8)) {
asJsonObject = new JsonParser().parse(streamReader).getAsJsonObject();
}
final JsonArray results = asJsonObject.getAsJsonArray("results");
final int numFound = results.size();
if (numFound == 0) {
throw new FileNotFoundException("Artifact " + dependency + " not found in Artifactory");
}
final List<MavenArtifact> result = new ArrayList<>(numFound);
for (JsonElement jsonElement : results) {
final JsonObject checksumList = jsonElement.getAsJsonObject().getAsJsonObject("checksums");
final JsonPrimitive sha256Primitive = checksumList.getAsJsonPrimitive("sha256");
final String sha1 = checksumList.getAsJsonPrimitive("sha1").getAsString();
final String sha256 = sha256Primitive == null ? null : sha256Primitive.getAsString();
final String md5 = checksumList.getAsJsonPrimitive("md5").getAsString();
checkHashes(dependency, sha1, sha256, md5);
final String downloadUri = jsonElement.getAsJsonObject().getAsJsonPrimitive("downloadUri").getAsString();
final String path = jsonElement.getAsJsonObject().getAsJsonPrimitive("path").getAsString();
final Matcher pathMatcher = PATH_PATTERN.matcher(path);
if (!pathMatcher.matches()) {
throw new IllegalStateException("Cannot extract the Maven information from the apth retrieved in Artifactory " + path);
}
final String groupId = pathMatcher.group("groupId").replace('/', '.');
final String artifactId = pathMatcher.group("artifactId");
final String version = pathMatcher.group("version");
result.add(new MavenArtifact(groupId, artifactId, version, downloadUri, MavenArtifact.derivePomUrl(artifactId, version, downloadUri)));
}
return result;
}
|
[
"protected",
"List",
"<",
"MavenArtifact",
">",
"processResponse",
"(",
"Dependency",
"dependency",
",",
"HttpURLConnection",
"conn",
")",
"throws",
"IOException",
"{",
"final",
"JsonObject",
"asJsonObject",
";",
"try",
"(",
"final",
"InputStreamReader",
"streamReader",
"=",
"new",
"InputStreamReader",
"(",
"conn",
".",
"getInputStream",
"(",
")",
",",
"StandardCharsets",
".",
"UTF_8",
")",
")",
"{",
"asJsonObject",
"=",
"new",
"JsonParser",
"(",
")",
".",
"parse",
"(",
"streamReader",
")",
".",
"getAsJsonObject",
"(",
")",
";",
"}",
"final",
"JsonArray",
"results",
"=",
"asJsonObject",
".",
"getAsJsonArray",
"(",
"\"results\"",
")",
";",
"final",
"int",
"numFound",
"=",
"results",
".",
"size",
"(",
")",
";",
"if",
"(",
"numFound",
"==",
"0",
")",
"{",
"throw",
"new",
"FileNotFoundException",
"(",
"\"Artifact \"",
"+",
"dependency",
"+",
"\" not found in Artifactory\"",
")",
";",
"}",
"final",
"List",
"<",
"MavenArtifact",
">",
"result",
"=",
"new",
"ArrayList",
"<>",
"(",
"numFound",
")",
";",
"for",
"(",
"JsonElement",
"jsonElement",
":",
"results",
")",
"{",
"final",
"JsonObject",
"checksumList",
"=",
"jsonElement",
".",
"getAsJsonObject",
"(",
")",
".",
"getAsJsonObject",
"(",
"\"checksums\"",
")",
";",
"final",
"JsonPrimitive",
"sha256Primitive",
"=",
"checksumList",
".",
"getAsJsonPrimitive",
"(",
"\"sha256\"",
")",
";",
"final",
"String",
"sha1",
"=",
"checksumList",
".",
"getAsJsonPrimitive",
"(",
"\"sha1\"",
")",
".",
"getAsString",
"(",
")",
";",
"final",
"String",
"sha256",
"=",
"sha256Primitive",
"==",
"null",
"?",
"null",
":",
"sha256Primitive",
".",
"getAsString",
"(",
")",
";",
"final",
"String",
"md5",
"=",
"checksumList",
".",
"getAsJsonPrimitive",
"(",
"\"md5\"",
")",
".",
"getAsString",
"(",
")",
";",
"checkHashes",
"(",
"dependency",
",",
"sha1",
",",
"sha256",
",",
"md5",
")",
";",
"final",
"String",
"downloadUri",
"=",
"jsonElement",
".",
"getAsJsonObject",
"(",
")",
".",
"getAsJsonPrimitive",
"(",
"\"downloadUri\"",
")",
".",
"getAsString",
"(",
")",
";",
"final",
"String",
"path",
"=",
"jsonElement",
".",
"getAsJsonObject",
"(",
")",
".",
"getAsJsonPrimitive",
"(",
"\"path\"",
")",
".",
"getAsString",
"(",
")",
";",
"final",
"Matcher",
"pathMatcher",
"=",
"PATH_PATTERN",
".",
"matcher",
"(",
"path",
")",
";",
"if",
"(",
"!",
"pathMatcher",
".",
"matches",
"(",
")",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"Cannot extract the Maven information from the apth retrieved in Artifactory \"",
"+",
"path",
")",
";",
"}",
"final",
"String",
"groupId",
"=",
"pathMatcher",
".",
"group",
"(",
"\"groupId\"",
")",
".",
"replace",
"(",
"'",
"'",
",",
"'",
"'",
")",
";",
"final",
"String",
"artifactId",
"=",
"pathMatcher",
".",
"group",
"(",
"\"artifactId\"",
")",
";",
"final",
"String",
"version",
"=",
"pathMatcher",
".",
"group",
"(",
"\"version\"",
")",
";",
"result",
".",
"add",
"(",
"new",
"MavenArtifact",
"(",
"groupId",
",",
"artifactId",
",",
"version",
",",
"downloadUri",
",",
"MavenArtifact",
".",
"derivePomUrl",
"(",
"artifactId",
",",
"version",
",",
"downloadUri",
")",
")",
")",
";",
"}",
"return",
"result",
";",
"}"
] |
Process the Artifactory response.
@param dependency the dependency
@param conn the HTTP URL Connection
@return a list of the Maven Artifact information
@throws IOException thrown if there is an I/O error
|
[
"Process",
"the",
"Artifactory",
"response",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/data/artifactory/ArtifactorySearch.java#L196-L234
|
17,726
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/data/artifactory/ArtifactorySearch.java
|
ArtifactorySearch.checkHashes
|
private void checkHashes(Dependency dependency, String sha1, String sha256, String md5) throws FileNotFoundException {
final String md5sum = dependency.getMd5sum();
if (!md5.equals(md5sum)) {
throw new FileNotFoundException("Artifact found by API is not matching the md5 "
+ "of the artifact (repository hash is " + md5 + WHILE_ACTUAL_IS + md5sum + ") !");
}
final String sha1sum = dependency.getSha1sum();
if (!sha1.equals(sha1sum)) {
throw new FileNotFoundException("Artifact found by API is not matching the SHA1 "
+ "of the artifact (repository hash is " + sha1 + WHILE_ACTUAL_IS + sha1sum + ") !");
}
final String sha256sum = dependency.getSha256sum();
if (sha256 != null && !sha256.equals(sha256sum)) {
throw new FileNotFoundException("Artifact found by API is not matching the SHA-256 "
+ "of the artifact (repository hash is " + sha256 + WHILE_ACTUAL_IS + sha256sum + ") !");
}
}
|
java
|
private void checkHashes(Dependency dependency, String sha1, String sha256, String md5) throws FileNotFoundException {
final String md5sum = dependency.getMd5sum();
if (!md5.equals(md5sum)) {
throw new FileNotFoundException("Artifact found by API is not matching the md5 "
+ "of the artifact (repository hash is " + md5 + WHILE_ACTUAL_IS + md5sum + ") !");
}
final String sha1sum = dependency.getSha1sum();
if (!sha1.equals(sha1sum)) {
throw new FileNotFoundException("Artifact found by API is not matching the SHA1 "
+ "of the artifact (repository hash is " + sha1 + WHILE_ACTUAL_IS + sha1sum + ") !");
}
final String sha256sum = dependency.getSha256sum();
if (sha256 != null && !sha256.equals(sha256sum)) {
throw new FileNotFoundException("Artifact found by API is not matching the SHA-256 "
+ "of the artifact (repository hash is " + sha256 + WHILE_ACTUAL_IS + sha256sum + ") !");
}
}
|
[
"private",
"void",
"checkHashes",
"(",
"Dependency",
"dependency",
",",
"String",
"sha1",
",",
"String",
"sha256",
",",
"String",
"md5",
")",
"throws",
"FileNotFoundException",
"{",
"final",
"String",
"md5sum",
"=",
"dependency",
".",
"getMd5sum",
"(",
")",
";",
"if",
"(",
"!",
"md5",
".",
"equals",
"(",
"md5sum",
")",
")",
"{",
"throw",
"new",
"FileNotFoundException",
"(",
"\"Artifact found by API is not matching the md5 \"",
"+",
"\"of the artifact (repository hash is \"",
"+",
"md5",
"+",
"WHILE_ACTUAL_IS",
"+",
"md5sum",
"+",
"\") !\"",
")",
";",
"}",
"final",
"String",
"sha1sum",
"=",
"dependency",
".",
"getSha1sum",
"(",
")",
";",
"if",
"(",
"!",
"sha1",
".",
"equals",
"(",
"sha1sum",
")",
")",
"{",
"throw",
"new",
"FileNotFoundException",
"(",
"\"Artifact found by API is not matching the SHA1 \"",
"+",
"\"of the artifact (repository hash is \"",
"+",
"sha1",
"+",
"WHILE_ACTUAL_IS",
"+",
"sha1sum",
"+",
"\") !\"",
")",
";",
"}",
"final",
"String",
"sha256sum",
"=",
"dependency",
".",
"getSha256sum",
"(",
")",
";",
"if",
"(",
"sha256",
"!=",
"null",
"&&",
"!",
"sha256",
".",
"equals",
"(",
"sha256sum",
")",
")",
"{",
"throw",
"new",
"FileNotFoundException",
"(",
"\"Artifact found by API is not matching the SHA-256 \"",
"+",
"\"of the artifact (repository hash is \"",
"+",
"sha256",
"+",
"WHILE_ACTUAL_IS",
"+",
"sha256sum",
"+",
"\") !\"",
")",
";",
"}",
"}"
] |
Validates the hashes of the dependency.
@param dependency the dependency
@param sha1 the SHA1 checksum
@param sha256 the SHA256 checksum
@param md5 the MD5 checksum
@throws FileNotFoundException thrown if one of the checksums does not
match
|
[
"Validates",
"the",
"hashes",
"of",
"the",
"dependency",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/data/artifactory/ArtifactorySearch.java#L246-L262
|
17,727
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/data/artifactory/ArtifactorySearch.java
|
ArtifactorySearch.preflightRequest
|
public boolean preflightRequest() {
try {
final URL url = buildUrl(Checksum.getSHA1Checksum(UUID.randomUUID().toString()));
final HttpURLConnection connection = connect(url);
if (connection.getResponseCode() != 200) {
LOGGER.warn("Expected 200 result from Artifactory ({}), got {}", url, connection.getResponseCode());
return false;
}
return true;
} catch (IOException e) {
LOGGER.error("Cannot connect to Artifactory", e);
return false;
}
}
|
java
|
public boolean preflightRequest() {
try {
final URL url = buildUrl(Checksum.getSHA1Checksum(UUID.randomUUID().toString()));
final HttpURLConnection connection = connect(url);
if (connection.getResponseCode() != 200) {
LOGGER.warn("Expected 200 result from Artifactory ({}), got {}", url, connection.getResponseCode());
return false;
}
return true;
} catch (IOException e) {
LOGGER.error("Cannot connect to Artifactory", e);
return false;
}
}
|
[
"public",
"boolean",
"preflightRequest",
"(",
")",
"{",
"try",
"{",
"final",
"URL",
"url",
"=",
"buildUrl",
"(",
"Checksum",
".",
"getSHA1Checksum",
"(",
"UUID",
".",
"randomUUID",
"(",
")",
".",
"toString",
"(",
")",
")",
")",
";",
"final",
"HttpURLConnection",
"connection",
"=",
"connect",
"(",
"url",
")",
";",
"if",
"(",
"connection",
".",
"getResponseCode",
"(",
")",
"!=",
"200",
")",
"{",
"LOGGER",
".",
"warn",
"(",
"\"Expected 200 result from Artifactory ({}), got {}\"",
",",
"url",
",",
"connection",
".",
"getResponseCode",
"(",
")",
")",
";",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"LOGGER",
".",
"error",
"(",
"\"Cannot connect to Artifactory\"",
",",
"e",
")",
";",
"return",
"false",
";",
"}",
"}"
] |
Performs a pre-flight request to ensure the Artifactory service is
reachable.
@return <code>true</code> if Artifactory could be reached; otherwise
<code>false</code>.
|
[
"Performs",
"a",
"pre",
"-",
"flight",
"request",
"to",
"ensure",
"the",
"Artifactory",
"service",
"is",
"reachable",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/data/artifactory/ArtifactorySearch.java#L271-L285
|
17,728
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/xml/assembly/GrokParser.java
|
GrokParser.parse
|
@SuppressFBWarnings(justification = "try with resources will clean up the input stream", value = {"OBL_UNSATISFIED_OBLIGATION"})
public AssemblyData parse(File file) throws GrokParseException {
try (FileInputStream fis = new FileInputStream(file)) {
return parse(fis);
} catch (IOException ex) {
LOGGER.debug("", ex);
throw new GrokParseException(ex);
}
}
|
java
|
@SuppressFBWarnings(justification = "try with resources will clean up the input stream", value = {"OBL_UNSATISFIED_OBLIGATION"})
public AssemblyData parse(File file) throws GrokParseException {
try (FileInputStream fis = new FileInputStream(file)) {
return parse(fis);
} catch (IOException ex) {
LOGGER.debug("", ex);
throw new GrokParseException(ex);
}
}
|
[
"@",
"SuppressFBWarnings",
"(",
"justification",
"=",
"\"try with resources will clean up the input stream\"",
",",
"value",
"=",
"{",
"\"OBL_UNSATISFIED_OBLIGATION\"",
"}",
")",
"public",
"AssemblyData",
"parse",
"(",
"File",
"file",
")",
"throws",
"GrokParseException",
"{",
"try",
"(",
"FileInputStream",
"fis",
"=",
"new",
"FileInputStream",
"(",
"file",
")",
")",
"{",
"return",
"parse",
"(",
"fis",
")",
";",
"}",
"catch",
"(",
"IOException",
"ex",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"\"",
",",
"ex",
")",
";",
"throw",
"new",
"GrokParseException",
"(",
"ex",
")",
";",
"}",
"}"
] |
Parses the given XML file and returns the assembly data.
@param file an XML file containing assembly data
@return the assembly data
@throws GrokParseException thrown if the XML file cannot be parsed
|
[
"Parses",
"the",
"given",
"XML",
"file",
"and",
"returns",
"the",
"assembly",
"data",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/xml/assembly/GrokParser.java#L66-L74
|
17,729
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/xml/assembly/GrokParser.java
|
GrokParser.parse
|
public AssemblyData parse(InputStream inputStream) throws GrokParseException {
try (InputStream schema = FileUtils.getResourceAsStream(GROK_SCHEMA)) {
final GrokHandler handler = new GrokHandler();
final SAXParser saxParser = XmlUtils.buildSecureSaxParser(schema);
final XMLReader xmlReader = saxParser.getXMLReader();
xmlReader.setErrorHandler(new GrokErrorHandler());
xmlReader.setContentHandler(handler);
try (Reader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8)) {
final InputSource in = new InputSource(reader);
xmlReader.parse(in);
return handler.getAssemblyData();
}
} catch (ParserConfigurationException | FileNotFoundException ex) {
LOGGER.debug("", ex);
throw new GrokParseException(ex);
} catch (SAXException ex) {
if (ex.getMessage().contains("Cannot find the declaration of element 'assembly'.")) {
throw new GrokParseException("Malformed grok xml?", ex);
} else {
LOGGER.debug("", ex);
throw new GrokParseException(ex);
}
} catch (IOException ex) {
LOGGER.debug("", ex);
throw new GrokParseException(ex);
}
}
|
java
|
public AssemblyData parse(InputStream inputStream) throws GrokParseException {
try (InputStream schema = FileUtils.getResourceAsStream(GROK_SCHEMA)) {
final GrokHandler handler = new GrokHandler();
final SAXParser saxParser = XmlUtils.buildSecureSaxParser(schema);
final XMLReader xmlReader = saxParser.getXMLReader();
xmlReader.setErrorHandler(new GrokErrorHandler());
xmlReader.setContentHandler(handler);
try (Reader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8)) {
final InputSource in = new InputSource(reader);
xmlReader.parse(in);
return handler.getAssemblyData();
}
} catch (ParserConfigurationException | FileNotFoundException ex) {
LOGGER.debug("", ex);
throw new GrokParseException(ex);
} catch (SAXException ex) {
if (ex.getMessage().contains("Cannot find the declaration of element 'assembly'.")) {
throw new GrokParseException("Malformed grok xml?", ex);
} else {
LOGGER.debug("", ex);
throw new GrokParseException(ex);
}
} catch (IOException ex) {
LOGGER.debug("", ex);
throw new GrokParseException(ex);
}
}
|
[
"public",
"AssemblyData",
"parse",
"(",
"InputStream",
"inputStream",
")",
"throws",
"GrokParseException",
"{",
"try",
"(",
"InputStream",
"schema",
"=",
"FileUtils",
".",
"getResourceAsStream",
"(",
"GROK_SCHEMA",
")",
")",
"{",
"final",
"GrokHandler",
"handler",
"=",
"new",
"GrokHandler",
"(",
")",
";",
"final",
"SAXParser",
"saxParser",
"=",
"XmlUtils",
".",
"buildSecureSaxParser",
"(",
"schema",
")",
";",
"final",
"XMLReader",
"xmlReader",
"=",
"saxParser",
".",
"getXMLReader",
"(",
")",
";",
"xmlReader",
".",
"setErrorHandler",
"(",
"new",
"GrokErrorHandler",
"(",
")",
")",
";",
"xmlReader",
".",
"setContentHandler",
"(",
"handler",
")",
";",
"try",
"(",
"Reader",
"reader",
"=",
"new",
"InputStreamReader",
"(",
"inputStream",
",",
"StandardCharsets",
".",
"UTF_8",
")",
")",
"{",
"final",
"InputSource",
"in",
"=",
"new",
"InputSource",
"(",
"reader",
")",
";",
"xmlReader",
".",
"parse",
"(",
"in",
")",
";",
"return",
"handler",
".",
"getAssemblyData",
"(",
")",
";",
"}",
"}",
"catch",
"(",
"ParserConfigurationException",
"|",
"FileNotFoundException",
"ex",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"\"",
",",
"ex",
")",
";",
"throw",
"new",
"GrokParseException",
"(",
"ex",
")",
";",
"}",
"catch",
"(",
"SAXException",
"ex",
")",
"{",
"if",
"(",
"ex",
".",
"getMessage",
"(",
")",
".",
"contains",
"(",
"\"Cannot find the declaration of element 'assembly'.\"",
")",
")",
"{",
"throw",
"new",
"GrokParseException",
"(",
"\"Malformed grok xml?\"",
",",
"ex",
")",
";",
"}",
"else",
"{",
"LOGGER",
".",
"debug",
"(",
"\"\"",
",",
"ex",
")",
";",
"throw",
"new",
"GrokParseException",
"(",
"ex",
")",
";",
"}",
"}",
"catch",
"(",
"IOException",
"ex",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"\"",
",",
"ex",
")",
";",
"throw",
"new",
"GrokParseException",
"(",
"ex",
")",
";",
"}",
"}"
] |
Parses the given XML stream and returns the contained assembly data.
@param inputStream an InputStream containing assembly data
@return the assembly data
@throws GrokParseException thrown if the XML cannot be parsed
|
[
"Parses",
"the",
"given",
"XML",
"stream",
"and",
"returns",
"the",
"contained",
"assembly",
"data",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/xml/assembly/GrokParser.java#L83-L109
|
17,730
|
jeremylong/DependencyCheck
|
maven/src/main/java/org/owasp/dependencycheck/maven/UpdateMojo.java
|
UpdateMojo.runCheck
|
@Override
protected void runCheck() throws MojoExecutionException, MojoFailureException {
try (Engine engine = initializeEngine()) {
try {
if (!engine.getSettings().getBoolean(Settings.KEYS.AUTO_UPDATE)) {
engine.getSettings().setBoolean(Settings.KEYS.AUTO_UPDATE, true);
}
} catch (InvalidSettingException ex) {
engine.getSettings().setBoolean(Settings.KEYS.AUTO_UPDATE, true);
}
engine.doUpdates();
} catch (DatabaseException ex) {
if (getLog().isDebugEnabled()) {
getLog().debug("Database connection error", ex);
}
final String msg = "An exception occurred connecting to the local database. Please see the log file for more details.";
if (this.isFailOnError()) {
throw new MojoExecutionException(msg, ex);
}
getLog().error(msg);
} catch (UpdateException ex) {
final String msg = "An exception occurred while downloading updates. Please see the log file for more details.";
if (this.isFailOnError()) {
throw new MojoExecutionException(msg, ex);
}
getLog().error(msg);
}
}
|
java
|
@Override
protected void runCheck() throws MojoExecutionException, MojoFailureException {
try (Engine engine = initializeEngine()) {
try {
if (!engine.getSettings().getBoolean(Settings.KEYS.AUTO_UPDATE)) {
engine.getSettings().setBoolean(Settings.KEYS.AUTO_UPDATE, true);
}
} catch (InvalidSettingException ex) {
engine.getSettings().setBoolean(Settings.KEYS.AUTO_UPDATE, true);
}
engine.doUpdates();
} catch (DatabaseException ex) {
if (getLog().isDebugEnabled()) {
getLog().debug("Database connection error", ex);
}
final String msg = "An exception occurred connecting to the local database. Please see the log file for more details.";
if (this.isFailOnError()) {
throw new MojoExecutionException(msg, ex);
}
getLog().error(msg);
} catch (UpdateException ex) {
final String msg = "An exception occurred while downloading updates. Please see the log file for more details.";
if (this.isFailOnError()) {
throw new MojoExecutionException(msg, ex);
}
getLog().error(msg);
}
}
|
[
"@",
"Override",
"protected",
"void",
"runCheck",
"(",
")",
"throws",
"MojoExecutionException",
",",
"MojoFailureException",
"{",
"try",
"(",
"Engine",
"engine",
"=",
"initializeEngine",
"(",
")",
")",
"{",
"try",
"{",
"if",
"(",
"!",
"engine",
".",
"getSettings",
"(",
")",
".",
"getBoolean",
"(",
"Settings",
".",
"KEYS",
".",
"AUTO_UPDATE",
")",
")",
"{",
"engine",
".",
"getSettings",
"(",
")",
".",
"setBoolean",
"(",
"Settings",
".",
"KEYS",
".",
"AUTO_UPDATE",
",",
"true",
")",
";",
"}",
"}",
"catch",
"(",
"InvalidSettingException",
"ex",
")",
"{",
"engine",
".",
"getSettings",
"(",
")",
".",
"setBoolean",
"(",
"Settings",
".",
"KEYS",
".",
"AUTO_UPDATE",
",",
"true",
")",
";",
"}",
"engine",
".",
"doUpdates",
"(",
")",
";",
"}",
"catch",
"(",
"DatabaseException",
"ex",
")",
"{",
"if",
"(",
"getLog",
"(",
")",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"getLog",
"(",
")",
".",
"debug",
"(",
"\"Database connection error\"",
",",
"ex",
")",
";",
"}",
"final",
"String",
"msg",
"=",
"\"An exception occurred connecting to the local database. Please see the log file for more details.\"",
";",
"if",
"(",
"this",
".",
"isFailOnError",
"(",
")",
")",
"{",
"throw",
"new",
"MojoExecutionException",
"(",
"msg",
",",
"ex",
")",
";",
"}",
"getLog",
"(",
")",
".",
"error",
"(",
"msg",
")",
";",
"}",
"catch",
"(",
"UpdateException",
"ex",
")",
"{",
"final",
"String",
"msg",
"=",
"\"An exception occurred while downloading updates. Please see the log file for more details.\"",
";",
"if",
"(",
"this",
".",
"isFailOnError",
"(",
")",
")",
"{",
"throw",
"new",
"MojoExecutionException",
"(",
"msg",
",",
"ex",
")",
";",
"}",
"getLog",
"(",
")",
".",
"error",
"(",
"msg",
")",
";",
"}",
"}"
] |
Executes the dependency-check engine on the project's dependencies and
generates the report.
@throws MojoExecutionException thrown if there is an exception executing
the goal
@throws MojoFailureException thrown if dependency-check is configured to
fail the build
|
[
"Executes",
"the",
"dependency",
"-",
"check",
"engine",
"on",
"the",
"project",
"s",
"dependencies",
"and",
"generates",
"the",
"report",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/maven/src/main/java/org/owasp/dependencycheck/maven/UpdateMojo.java#L68-L95
|
17,731
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/analyzer/AbstractNpmAnalyzer.java
|
AbstractNpmAnalyzer.createDependency
|
protected Dependency createDependency(Dependency dependency, String name, String version, String scope) {
final Dependency nodeModule = new Dependency(new File(dependency.getActualFile() + "?" + name), true);
nodeModule.setEcosystem(NPM_DEPENDENCY_ECOSYSTEM);
//this is virtual - the sha1 is purely for the hyperlink in the final html report
nodeModule.setSha1sum(Checksum.getSHA1Checksum(String.format("%s:%s", name, version)));
nodeModule.setSha256sum(Checksum.getSHA256Checksum(String.format("%s:%s", name, version)));
nodeModule.setMd5sum(Checksum.getMD5Checksum(String.format("%s:%s", name, version)));
nodeModule.addEvidence(EvidenceType.PRODUCT, "package.json", "name", name, Confidence.HIGHEST);
nodeModule.addEvidence(EvidenceType.VENDOR, "package.json", "name", name, Confidence.HIGH);
if (!StringUtils.isBlank(version)) {
nodeModule.addEvidence(EvidenceType.VERSION, "package.json", "version", version, Confidence.HIGHEST);
nodeModule.setVersion(version);
}
if (dependency.getName() != null) {
nodeModule.addProjectReference(dependency.getName() + ": " + scope);
} else {
nodeModule.addProjectReference(dependency.getDisplayFileName() + ": " + scope);
}
nodeModule.setName(name);
//TODO - we can likely create a valid CPE as a low confidence guess using cpe:2.3:a:[name]_project:[name]:[version]
//(and add a targetSw of npm/node)
Identifier id;
try {
final PackageURL purl = PackageURLBuilder.aPackageURL().withType(StandardTypes.NPM)
.withName(name).withVersion(version).build();
id = new PurlIdentifier(purl, Confidence.HIGHEST);
} catch (MalformedPackageURLException ex) {
LOGGER.debug("Unable to generate Purl - using a generic identifier instead " + ex.getMessage());
id = new GenericIdentifier(String.format("npm:%s@%s", dependency.getName(), version), Confidence.HIGHEST);
}
nodeModule.addSoftwareIdentifier(id);
return nodeModule;
}
|
java
|
protected Dependency createDependency(Dependency dependency, String name, String version, String scope) {
final Dependency nodeModule = new Dependency(new File(dependency.getActualFile() + "?" + name), true);
nodeModule.setEcosystem(NPM_DEPENDENCY_ECOSYSTEM);
//this is virtual - the sha1 is purely for the hyperlink in the final html report
nodeModule.setSha1sum(Checksum.getSHA1Checksum(String.format("%s:%s", name, version)));
nodeModule.setSha256sum(Checksum.getSHA256Checksum(String.format("%s:%s", name, version)));
nodeModule.setMd5sum(Checksum.getMD5Checksum(String.format("%s:%s", name, version)));
nodeModule.addEvidence(EvidenceType.PRODUCT, "package.json", "name", name, Confidence.HIGHEST);
nodeModule.addEvidence(EvidenceType.VENDOR, "package.json", "name", name, Confidence.HIGH);
if (!StringUtils.isBlank(version)) {
nodeModule.addEvidence(EvidenceType.VERSION, "package.json", "version", version, Confidence.HIGHEST);
nodeModule.setVersion(version);
}
if (dependency.getName() != null) {
nodeModule.addProjectReference(dependency.getName() + ": " + scope);
} else {
nodeModule.addProjectReference(dependency.getDisplayFileName() + ": " + scope);
}
nodeModule.setName(name);
//TODO - we can likely create a valid CPE as a low confidence guess using cpe:2.3:a:[name]_project:[name]:[version]
//(and add a targetSw of npm/node)
Identifier id;
try {
final PackageURL purl = PackageURLBuilder.aPackageURL().withType(StandardTypes.NPM)
.withName(name).withVersion(version).build();
id = new PurlIdentifier(purl, Confidence.HIGHEST);
} catch (MalformedPackageURLException ex) {
LOGGER.debug("Unable to generate Purl - using a generic identifier instead " + ex.getMessage());
id = new GenericIdentifier(String.format("npm:%s@%s", dependency.getName(), version), Confidence.HIGHEST);
}
nodeModule.addSoftwareIdentifier(id);
return nodeModule;
}
|
[
"protected",
"Dependency",
"createDependency",
"(",
"Dependency",
"dependency",
",",
"String",
"name",
",",
"String",
"version",
",",
"String",
"scope",
")",
"{",
"final",
"Dependency",
"nodeModule",
"=",
"new",
"Dependency",
"(",
"new",
"File",
"(",
"dependency",
".",
"getActualFile",
"(",
")",
"+",
"\"?\"",
"+",
"name",
")",
",",
"true",
")",
";",
"nodeModule",
".",
"setEcosystem",
"(",
"NPM_DEPENDENCY_ECOSYSTEM",
")",
";",
"//this is virtual - the sha1 is purely for the hyperlink in the final html report",
"nodeModule",
".",
"setSha1sum",
"(",
"Checksum",
".",
"getSHA1Checksum",
"(",
"String",
".",
"format",
"(",
"\"%s:%s\"",
",",
"name",
",",
"version",
")",
")",
")",
";",
"nodeModule",
".",
"setSha256sum",
"(",
"Checksum",
".",
"getSHA256Checksum",
"(",
"String",
".",
"format",
"(",
"\"%s:%s\"",
",",
"name",
",",
"version",
")",
")",
")",
";",
"nodeModule",
".",
"setMd5sum",
"(",
"Checksum",
".",
"getMD5Checksum",
"(",
"String",
".",
"format",
"(",
"\"%s:%s\"",
",",
"name",
",",
"version",
")",
")",
")",
";",
"nodeModule",
".",
"addEvidence",
"(",
"EvidenceType",
".",
"PRODUCT",
",",
"\"package.json\"",
",",
"\"name\"",
",",
"name",
",",
"Confidence",
".",
"HIGHEST",
")",
";",
"nodeModule",
".",
"addEvidence",
"(",
"EvidenceType",
".",
"VENDOR",
",",
"\"package.json\"",
",",
"\"name\"",
",",
"name",
",",
"Confidence",
".",
"HIGH",
")",
";",
"if",
"(",
"!",
"StringUtils",
".",
"isBlank",
"(",
"version",
")",
")",
"{",
"nodeModule",
".",
"addEvidence",
"(",
"EvidenceType",
".",
"VERSION",
",",
"\"package.json\"",
",",
"\"version\"",
",",
"version",
",",
"Confidence",
".",
"HIGHEST",
")",
";",
"nodeModule",
".",
"setVersion",
"(",
"version",
")",
";",
"}",
"if",
"(",
"dependency",
".",
"getName",
"(",
")",
"!=",
"null",
")",
"{",
"nodeModule",
".",
"addProjectReference",
"(",
"dependency",
".",
"getName",
"(",
")",
"+",
"\": \"",
"+",
"scope",
")",
";",
"}",
"else",
"{",
"nodeModule",
".",
"addProjectReference",
"(",
"dependency",
".",
"getDisplayFileName",
"(",
")",
"+",
"\": \"",
"+",
"scope",
")",
";",
"}",
"nodeModule",
".",
"setName",
"(",
"name",
")",
";",
"//TODO - we can likely create a valid CPE as a low confidence guess using cpe:2.3:a:[name]_project:[name]:[version]",
"//(and add a targetSw of npm/node)",
"Identifier",
"id",
";",
"try",
"{",
"final",
"PackageURL",
"purl",
"=",
"PackageURLBuilder",
".",
"aPackageURL",
"(",
")",
".",
"withType",
"(",
"StandardTypes",
".",
"NPM",
")",
".",
"withName",
"(",
"name",
")",
".",
"withVersion",
"(",
"version",
")",
".",
"build",
"(",
")",
";",
"id",
"=",
"new",
"PurlIdentifier",
"(",
"purl",
",",
"Confidence",
".",
"HIGHEST",
")",
";",
"}",
"catch",
"(",
"MalformedPackageURLException",
"ex",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"Unable to generate Purl - using a generic identifier instead \"",
"+",
"ex",
".",
"getMessage",
"(",
")",
")",
";",
"id",
"=",
"new",
"GenericIdentifier",
"(",
"String",
".",
"format",
"(",
"\"npm:%s@%s\"",
",",
"dependency",
".",
"getName",
"(",
")",
",",
"version",
")",
",",
"Confidence",
".",
"HIGHEST",
")",
";",
"}",
"nodeModule",
".",
"addSoftwareIdentifier",
"(",
"id",
")",
";",
"return",
"nodeModule",
";",
"}"
] |
Construct a dependency object.
@param dependency the parent dependency
@param name the name of the dependency to create
@param version the version of the dependency to create
@param scope the scope of the dependency being created
@return the generated dependency
|
[
"Construct",
"a",
"dependency",
"object",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/analyzer/AbstractNpmAnalyzer.java#L127-L160
|
17,732
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/xml/pom/PomUtils.java
|
PomUtils.readPom
|
public static Model readPom(File file) throws AnalysisException {
//noinspection CaughtExceptionImmediatelyRethrown
try {
final PomParser parser = new PomParser();
final Model model = parser.parse(file);
if (model == null) {
throw new AnalysisException(String.format("Unable to parse pom '%s'", file.getPath()));
}
return model;
} catch (AnalysisException ex) {
throw ex;
} catch (PomParseException ex) {
LOGGER.warn("Unable to parse pom '{}'", file.getPath());
//todo remove test code for intermittent error.
try {
final File target = new File("~/Projects/DependencyCheck/core/target/");
if (target.isDirectory()) {
FileUtils.copyFile(file, target);
LOGGER.info("Unparsable pom was copied to {}", target.toString());
}
} catch (IOException ex1) {
throw new UnexpectedAnalysisException(ex1);
}
LOGGER.debug("", ex);
throw new AnalysisException(ex);
} catch (Throwable ex) {
LOGGER.warn("Unexpected error during parsing of the pom '{}'", file.getPath());
LOGGER.debug("", ex);
throw new AnalysisException(ex);
}
}
|
java
|
public static Model readPom(File file) throws AnalysisException {
//noinspection CaughtExceptionImmediatelyRethrown
try {
final PomParser parser = new PomParser();
final Model model = parser.parse(file);
if (model == null) {
throw new AnalysisException(String.format("Unable to parse pom '%s'", file.getPath()));
}
return model;
} catch (AnalysisException ex) {
throw ex;
} catch (PomParseException ex) {
LOGGER.warn("Unable to parse pom '{}'", file.getPath());
//todo remove test code for intermittent error.
try {
final File target = new File("~/Projects/DependencyCheck/core/target/");
if (target.isDirectory()) {
FileUtils.copyFile(file, target);
LOGGER.info("Unparsable pom was copied to {}", target.toString());
}
} catch (IOException ex1) {
throw new UnexpectedAnalysisException(ex1);
}
LOGGER.debug("", ex);
throw new AnalysisException(ex);
} catch (Throwable ex) {
LOGGER.warn("Unexpected error during parsing of the pom '{}'", file.getPath());
LOGGER.debug("", ex);
throw new AnalysisException(ex);
}
}
|
[
"public",
"static",
"Model",
"readPom",
"(",
"File",
"file",
")",
"throws",
"AnalysisException",
"{",
"//noinspection CaughtExceptionImmediatelyRethrown",
"try",
"{",
"final",
"PomParser",
"parser",
"=",
"new",
"PomParser",
"(",
")",
";",
"final",
"Model",
"model",
"=",
"parser",
".",
"parse",
"(",
"file",
")",
";",
"if",
"(",
"model",
"==",
"null",
")",
"{",
"throw",
"new",
"AnalysisException",
"(",
"String",
".",
"format",
"(",
"\"Unable to parse pom '%s'\"",
",",
"file",
".",
"getPath",
"(",
")",
")",
")",
";",
"}",
"return",
"model",
";",
"}",
"catch",
"(",
"AnalysisException",
"ex",
")",
"{",
"throw",
"ex",
";",
"}",
"catch",
"(",
"PomParseException",
"ex",
")",
"{",
"LOGGER",
".",
"warn",
"(",
"\"Unable to parse pom '{}'\"",
",",
"file",
".",
"getPath",
"(",
")",
")",
";",
"//todo remove test code for intermittent error.",
"try",
"{",
"final",
"File",
"target",
"=",
"new",
"File",
"(",
"\"~/Projects/DependencyCheck/core/target/\"",
")",
";",
"if",
"(",
"target",
".",
"isDirectory",
"(",
")",
")",
"{",
"FileUtils",
".",
"copyFile",
"(",
"file",
",",
"target",
")",
";",
"LOGGER",
".",
"info",
"(",
"\"Unparsable pom was copied to {}\"",
",",
"target",
".",
"toString",
"(",
")",
")",
";",
"}",
"}",
"catch",
"(",
"IOException",
"ex1",
")",
"{",
"throw",
"new",
"UnexpectedAnalysisException",
"(",
"ex1",
")",
";",
"}",
"LOGGER",
".",
"debug",
"(",
"\"\"",
",",
"ex",
")",
";",
"throw",
"new",
"AnalysisException",
"(",
"ex",
")",
";",
"}",
"catch",
"(",
"Throwable",
"ex",
")",
"{",
"LOGGER",
".",
"warn",
"(",
"\"Unexpected error during parsing of the pom '{}'\"",
",",
"file",
".",
"getPath",
"(",
")",
")",
";",
"LOGGER",
".",
"debug",
"(",
"\"\"",
",",
"ex",
")",
";",
"throw",
"new",
"AnalysisException",
"(",
"ex",
")",
";",
"}",
"}"
] |
Reads in the specified POM and converts it to a Model.
@param file the pom.xml file
@return returns an object representation of the POM
@throws AnalysisException is thrown if there is an exception extracting
or parsing the POM {@link Model} object
|
[
"Reads",
"in",
"the",
"specified",
"POM",
"and",
"converts",
"it",
"to",
"a",
"Model",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/xml/pom/PomUtils.java#L59-L89
|
17,733
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/xml/pom/PomUtils.java
|
PomUtils.readPom
|
public static Model readPom(String path, JarFile jar) throws AnalysisException {
final ZipEntry entry = jar.getEntry(path);
Model model = null;
if (entry != null) { //should never be null
//noinspection CaughtExceptionImmediatelyRethrown
try {
final PomParser parser = new PomParser();
model = parser.parse(jar.getInputStream(entry));
if (model == null) {
throw new AnalysisException(String.format("Unable to parse pom '%s/%s'", jar.getName(), path));
}
} catch (AnalysisException ex) {
throw ex;
} catch (SecurityException ex) {
LOGGER.warn("Unable to parse pom '{}' in jar '{}'; invalid signature", path, jar.getName());
LOGGER.debug("", ex);
throw new AnalysisException(ex);
} catch (IOException ex) {
LOGGER.warn("Unable to parse pom '{}' in jar '{}' (IO Exception)", path, jar.getName());
LOGGER.debug("", ex);
throw new AnalysisException(ex);
} catch (Throwable ex) {
LOGGER.warn("Unexpected error during parsing of the pom '{}' in jar '{}'", path, jar.getName());
LOGGER.debug("", ex);
throw new AnalysisException(ex);
}
}
return model;
}
|
java
|
public static Model readPom(String path, JarFile jar) throws AnalysisException {
final ZipEntry entry = jar.getEntry(path);
Model model = null;
if (entry != null) { //should never be null
//noinspection CaughtExceptionImmediatelyRethrown
try {
final PomParser parser = new PomParser();
model = parser.parse(jar.getInputStream(entry));
if (model == null) {
throw new AnalysisException(String.format("Unable to parse pom '%s/%s'", jar.getName(), path));
}
} catch (AnalysisException ex) {
throw ex;
} catch (SecurityException ex) {
LOGGER.warn("Unable to parse pom '{}' in jar '{}'; invalid signature", path, jar.getName());
LOGGER.debug("", ex);
throw new AnalysisException(ex);
} catch (IOException ex) {
LOGGER.warn("Unable to parse pom '{}' in jar '{}' (IO Exception)", path, jar.getName());
LOGGER.debug("", ex);
throw new AnalysisException(ex);
} catch (Throwable ex) {
LOGGER.warn("Unexpected error during parsing of the pom '{}' in jar '{}'", path, jar.getName());
LOGGER.debug("", ex);
throw new AnalysisException(ex);
}
}
return model;
}
|
[
"public",
"static",
"Model",
"readPom",
"(",
"String",
"path",
",",
"JarFile",
"jar",
")",
"throws",
"AnalysisException",
"{",
"final",
"ZipEntry",
"entry",
"=",
"jar",
".",
"getEntry",
"(",
"path",
")",
";",
"Model",
"model",
"=",
"null",
";",
"if",
"(",
"entry",
"!=",
"null",
")",
"{",
"//should never be null",
"//noinspection CaughtExceptionImmediatelyRethrown",
"try",
"{",
"final",
"PomParser",
"parser",
"=",
"new",
"PomParser",
"(",
")",
";",
"model",
"=",
"parser",
".",
"parse",
"(",
"jar",
".",
"getInputStream",
"(",
"entry",
")",
")",
";",
"if",
"(",
"model",
"==",
"null",
")",
"{",
"throw",
"new",
"AnalysisException",
"(",
"String",
".",
"format",
"(",
"\"Unable to parse pom '%s/%s'\"",
",",
"jar",
".",
"getName",
"(",
")",
",",
"path",
")",
")",
";",
"}",
"}",
"catch",
"(",
"AnalysisException",
"ex",
")",
"{",
"throw",
"ex",
";",
"}",
"catch",
"(",
"SecurityException",
"ex",
")",
"{",
"LOGGER",
".",
"warn",
"(",
"\"Unable to parse pom '{}' in jar '{}'; invalid signature\"",
",",
"path",
",",
"jar",
".",
"getName",
"(",
")",
")",
";",
"LOGGER",
".",
"debug",
"(",
"\"\"",
",",
"ex",
")",
";",
"throw",
"new",
"AnalysisException",
"(",
"ex",
")",
";",
"}",
"catch",
"(",
"IOException",
"ex",
")",
"{",
"LOGGER",
".",
"warn",
"(",
"\"Unable to parse pom '{}' in jar '{}' (IO Exception)\"",
",",
"path",
",",
"jar",
".",
"getName",
"(",
")",
")",
";",
"LOGGER",
".",
"debug",
"(",
"\"\"",
",",
"ex",
")",
";",
"throw",
"new",
"AnalysisException",
"(",
"ex",
")",
";",
"}",
"catch",
"(",
"Throwable",
"ex",
")",
"{",
"LOGGER",
".",
"warn",
"(",
"\"Unexpected error during parsing of the pom '{}' in jar '{}'\"",
",",
"path",
",",
"jar",
".",
"getName",
"(",
")",
")",
";",
"LOGGER",
".",
"debug",
"(",
"\"\"",
",",
"ex",
")",
";",
"throw",
"new",
"AnalysisException",
"(",
"ex",
")",
";",
"}",
"}",
"return",
"model",
";",
"}"
] |
Retrieves the specified POM from a jar file and converts it to a Model.
@param path the path to the pom.xml file within the jar file
@param jar the jar file to extract the pom from
@return returns an object representation of the POM
@throws AnalysisException is thrown if there is an exception extracting
or parsing the POM {@link Model} object
|
[
"Retrieves",
"the",
"specified",
"POM",
"from",
"a",
"jar",
"file",
"and",
"converts",
"it",
"to",
"a",
"Model",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/xml/pom/PomUtils.java#L100-L128
|
17,734
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/xml/pom/PomUtils.java
|
PomUtils.analyzePOM
|
public static void analyzePOM(Dependency dependency, File pomFile) throws AnalysisException {
final Model pom = PomUtils.readPom(pomFile);
JarAnalyzer.setPomEvidence(dependency, pom, null, true);
}
|
java
|
public static void analyzePOM(Dependency dependency, File pomFile) throws AnalysisException {
final Model pom = PomUtils.readPom(pomFile);
JarAnalyzer.setPomEvidence(dependency, pom, null, true);
}
|
[
"public",
"static",
"void",
"analyzePOM",
"(",
"Dependency",
"dependency",
",",
"File",
"pomFile",
")",
"throws",
"AnalysisException",
"{",
"final",
"Model",
"pom",
"=",
"PomUtils",
".",
"readPom",
"(",
"pomFile",
")",
";",
"JarAnalyzer",
".",
"setPomEvidence",
"(",
"dependency",
",",
"pom",
",",
"null",
",",
"true",
")",
";",
"}"
] |
Reads in the pom file and adds elements as evidence to the given
dependency.
@param dependency the dependency being analyzed
@param pomFile the pom file to read
@throws AnalysisException is thrown if there is an exception parsing the
pom
|
[
"Reads",
"in",
"the",
"pom",
"file",
"and",
"adds",
"elements",
"as",
"evidence",
"to",
"the",
"given",
"dependency",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/xml/pom/PomUtils.java#L139-L142
|
17,735
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/analyzer/AbstractSuppressionAnalyzer.java
|
AbstractSuppressionAnalyzer.prepareAnalyzer
|
@Override
public synchronized void prepareAnalyzer(Engine engine) throws InitializationException {
if (rules.isEmpty()) {
try {
loadSuppressionBaseData();
} catch (SuppressionParseException ex) {
throw new InitializationException("Error initializing the suppression analyzer: " + ex.getLocalizedMessage(), ex, true);
}
try {
loadSuppressionData();
} catch (SuppressionParseException ex) {
throw new InitializationException("Warn initializing the suppression analyzer: " + ex.getLocalizedMessage(), ex, false);
}
}
}
|
java
|
@Override
public synchronized void prepareAnalyzer(Engine engine) throws InitializationException {
if (rules.isEmpty()) {
try {
loadSuppressionBaseData();
} catch (SuppressionParseException ex) {
throw new InitializationException("Error initializing the suppression analyzer: " + ex.getLocalizedMessage(), ex, true);
}
try {
loadSuppressionData();
} catch (SuppressionParseException ex) {
throw new InitializationException("Warn initializing the suppression analyzer: " + ex.getLocalizedMessage(), ex, false);
}
}
}
|
[
"@",
"Override",
"public",
"synchronized",
"void",
"prepareAnalyzer",
"(",
"Engine",
"engine",
")",
"throws",
"InitializationException",
"{",
"if",
"(",
"rules",
".",
"isEmpty",
"(",
")",
")",
"{",
"try",
"{",
"loadSuppressionBaseData",
"(",
")",
";",
"}",
"catch",
"(",
"SuppressionParseException",
"ex",
")",
"{",
"throw",
"new",
"InitializationException",
"(",
"\"Error initializing the suppression analyzer: \"",
"+",
"ex",
".",
"getLocalizedMessage",
"(",
")",
",",
"ex",
",",
"true",
")",
";",
"}",
"try",
"{",
"loadSuppressionData",
"(",
")",
";",
"}",
"catch",
"(",
"SuppressionParseException",
"ex",
")",
"{",
"throw",
"new",
"InitializationException",
"(",
"\"Warn initializing the suppression analyzer: \"",
"+",
"ex",
".",
"getLocalizedMessage",
"(",
")",
",",
"ex",
",",
"false",
")",
";",
"}",
"}",
"}"
] |
The prepare method loads the suppression XML file.
@param engine a reference the dependency-check engine
@throws InitializationException thrown if there is an exception
|
[
"The",
"prepare",
"method",
"loads",
"the",
"suppression",
"XML",
"file",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/analyzer/AbstractSuppressionAnalyzer.java#L91-L106
|
17,736
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/data/nvdcve/DriverLoader.java
|
DriverLoader.cleanup
|
public static void cleanup(Driver driver) {
try {
DriverManager.deregisterDriver(driver);
} catch (SQLException ex) {
LOGGER.debug("An error occurred unloading the database driver", ex);
} catch (Throwable unexpected) {
LOGGER.debug("An unexpected throwable occurred unloading the database driver", unexpected);
}
}
|
java
|
public static void cleanup(Driver driver) {
try {
DriverManager.deregisterDriver(driver);
} catch (SQLException ex) {
LOGGER.debug("An error occurred unloading the database driver", ex);
} catch (Throwable unexpected) {
LOGGER.debug("An unexpected throwable occurred unloading the database driver", unexpected);
}
}
|
[
"public",
"static",
"void",
"cleanup",
"(",
"Driver",
"driver",
")",
"{",
"try",
"{",
"DriverManager",
".",
"deregisterDriver",
"(",
"driver",
")",
";",
"}",
"catch",
"(",
"SQLException",
"ex",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"An error occurred unloading the database driver\"",
",",
"ex",
")",
";",
"}",
"catch",
"(",
"Throwable",
"unexpected",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"An unexpected throwable occurred unloading the database driver\"",
",",
"unexpected",
")",
";",
"}",
"}"
] |
De-registers the driver.
@param driver the driver to de-register
|
[
"De",
"-",
"registers",
"the",
"driver",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/data/nvdcve/DriverLoader.java#L55-L63
|
17,737
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/data/nvdcve/DriverLoader.java
|
DriverLoader.load
|
public static Driver load(String className) throws DriverLoadException {
final ClassLoader loader = DriverLoader.class.getClassLoader();
return load(className, loader);
}
|
java
|
public static Driver load(String className) throws DriverLoadException {
final ClassLoader loader = DriverLoader.class.getClassLoader();
return load(className, loader);
}
|
[
"public",
"static",
"Driver",
"load",
"(",
"String",
"className",
")",
"throws",
"DriverLoadException",
"{",
"final",
"ClassLoader",
"loader",
"=",
"DriverLoader",
".",
"class",
".",
"getClassLoader",
"(",
")",
";",
"return",
"load",
"(",
"className",
",",
"loader",
")",
";",
"}"
] |
Loads the specified class using the system class loader and registers the
driver with the driver manager.
@param className the fully qualified name of the desired class
@return the loaded Driver
@throws DriverLoadException thrown if the driver cannot be loaded
|
[
"Loads",
"the",
"specified",
"class",
"using",
"the",
"system",
"class",
"loader",
"and",
"registers",
"the",
"driver",
"with",
"the",
"driver",
"manager",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/data/nvdcve/DriverLoader.java#L79-L82
|
17,738
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/data/nvdcve/DriverLoader.java
|
DriverLoader.load
|
@SuppressWarnings("StringSplitter")
public static Driver load(String className, String pathToDriver) throws DriverLoadException {
final ClassLoader parent = ClassLoader.getSystemClassLoader();
final List<URL> urls = new ArrayList<>();
final String[] paths = pathToDriver.split(File.pathSeparator);
for (String path : paths) {
final File file = new File(path);
if (file.isDirectory()) {
final File[] files = file.listFiles();
if (files != null) {
for (File f : files) {
try {
urls.add(f.toURI().toURL());
} catch (MalformedURLException ex) {
LOGGER.debug("Unable to load database driver '{}'; invalid path provided '{}'",
className, f.getAbsoluteFile(), ex);
throw new DriverLoadException("Unable to load database driver. Invalid path provided", ex);
}
}
}
} else if (file.exists()) {
try {
urls.add(file.toURI().toURL());
} catch (MalformedURLException ex) {
LOGGER.debug("Unable to load database driver '{}'; invalid path provided '{}'",
className, file.getAbsoluteFile(), ex);
throw new DriverLoadException("Unable to load database driver. Invalid path provided", ex);
}
}
}
final URLClassLoader loader = AccessController.doPrivileged(new PrivilegedAction<URLClassLoader>() {
@Override
public URLClassLoader run() {
return new URLClassLoader(urls.toArray(new URL[urls.size()]), parent);
}
});
return load(className, loader);
}
|
java
|
@SuppressWarnings("StringSplitter")
public static Driver load(String className, String pathToDriver) throws DriverLoadException {
final ClassLoader parent = ClassLoader.getSystemClassLoader();
final List<URL> urls = new ArrayList<>();
final String[] paths = pathToDriver.split(File.pathSeparator);
for (String path : paths) {
final File file = new File(path);
if (file.isDirectory()) {
final File[] files = file.listFiles();
if (files != null) {
for (File f : files) {
try {
urls.add(f.toURI().toURL());
} catch (MalformedURLException ex) {
LOGGER.debug("Unable to load database driver '{}'; invalid path provided '{}'",
className, f.getAbsoluteFile(), ex);
throw new DriverLoadException("Unable to load database driver. Invalid path provided", ex);
}
}
}
} else if (file.exists()) {
try {
urls.add(file.toURI().toURL());
} catch (MalformedURLException ex) {
LOGGER.debug("Unable to load database driver '{}'; invalid path provided '{}'",
className, file.getAbsoluteFile(), ex);
throw new DriverLoadException("Unable to load database driver. Invalid path provided", ex);
}
}
}
final URLClassLoader loader = AccessController.doPrivileged(new PrivilegedAction<URLClassLoader>() {
@Override
public URLClassLoader run() {
return new URLClassLoader(urls.toArray(new URL[urls.size()]), parent);
}
});
return load(className, loader);
}
|
[
"@",
"SuppressWarnings",
"(",
"\"StringSplitter\"",
")",
"public",
"static",
"Driver",
"load",
"(",
"String",
"className",
",",
"String",
"pathToDriver",
")",
"throws",
"DriverLoadException",
"{",
"final",
"ClassLoader",
"parent",
"=",
"ClassLoader",
".",
"getSystemClassLoader",
"(",
")",
";",
"final",
"List",
"<",
"URL",
">",
"urls",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"final",
"String",
"[",
"]",
"paths",
"=",
"pathToDriver",
".",
"split",
"(",
"File",
".",
"pathSeparator",
")",
";",
"for",
"(",
"String",
"path",
":",
"paths",
")",
"{",
"final",
"File",
"file",
"=",
"new",
"File",
"(",
"path",
")",
";",
"if",
"(",
"file",
".",
"isDirectory",
"(",
")",
")",
"{",
"final",
"File",
"[",
"]",
"files",
"=",
"file",
".",
"listFiles",
"(",
")",
";",
"if",
"(",
"files",
"!=",
"null",
")",
"{",
"for",
"(",
"File",
"f",
":",
"files",
")",
"{",
"try",
"{",
"urls",
".",
"add",
"(",
"f",
".",
"toURI",
"(",
")",
".",
"toURL",
"(",
")",
")",
";",
"}",
"catch",
"(",
"MalformedURLException",
"ex",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"Unable to load database driver '{}'; invalid path provided '{}'\"",
",",
"className",
",",
"f",
".",
"getAbsoluteFile",
"(",
")",
",",
"ex",
")",
";",
"throw",
"new",
"DriverLoadException",
"(",
"\"Unable to load database driver. Invalid path provided\"",
",",
"ex",
")",
";",
"}",
"}",
"}",
"}",
"else",
"if",
"(",
"file",
".",
"exists",
"(",
")",
")",
"{",
"try",
"{",
"urls",
".",
"add",
"(",
"file",
".",
"toURI",
"(",
")",
".",
"toURL",
"(",
")",
")",
";",
"}",
"catch",
"(",
"MalformedURLException",
"ex",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"Unable to load database driver '{}'; invalid path provided '{}'\"",
",",
"className",
",",
"file",
".",
"getAbsoluteFile",
"(",
")",
",",
"ex",
")",
";",
"throw",
"new",
"DriverLoadException",
"(",
"\"Unable to load database driver. Invalid path provided\"",
",",
"ex",
")",
";",
"}",
"}",
"}",
"final",
"URLClassLoader",
"loader",
"=",
"AccessController",
".",
"doPrivileged",
"(",
"new",
"PrivilegedAction",
"<",
"URLClassLoader",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"URLClassLoader",
"run",
"(",
")",
"{",
"return",
"new",
"URLClassLoader",
"(",
"urls",
".",
"toArray",
"(",
"new",
"URL",
"[",
"urls",
".",
"size",
"(",
")",
"]",
")",
",",
"parent",
")",
";",
"}",
"}",
")",
";",
"return",
"load",
"(",
"className",
",",
"loader",
")",
";",
"}"
] |
Loads the specified class by registering the supplied paths to the class
loader and then registers the driver with the driver manager. The
pathToDriver argument is added to the class loader so that an external
driver can be loaded. Note, the pathToDriver can contain a semi-colon
separated list of paths so any dependencies can be added as needed. If a
path in the pathToDriver argument is a directory all files in the
directory are added to the class path.
@param className the fully qualified name of the desired class
@param pathToDriver the path to the JAR file containing the driver; note,
this can be a semi-colon separated list of paths
@return the loaded Driver
@throws DriverLoadException thrown if the driver cannot be loaded
|
[
"Loads",
"the",
"specified",
"class",
"by",
"registering",
"the",
"supplied",
"paths",
"to",
"the",
"class",
"loader",
"and",
"then",
"registers",
"the",
"driver",
"with",
"the",
"driver",
"manager",
".",
"The",
"pathToDriver",
"argument",
"is",
"added",
"to",
"the",
"class",
"loader",
"so",
"that",
"an",
"external",
"driver",
"can",
"be",
"loaded",
".",
"Note",
"the",
"pathToDriver",
"can",
"contain",
"a",
"semi",
"-",
"colon",
"separated",
"list",
"of",
"paths",
"so",
"any",
"dependencies",
"can",
"be",
"added",
"as",
"needed",
".",
"If",
"a",
"path",
"in",
"the",
"pathToDriver",
"argument",
"is",
"a",
"directory",
"all",
"files",
"in",
"the",
"directory",
"are",
"added",
"to",
"the",
"class",
"path",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/data/nvdcve/DriverLoader.java#L99-L137
|
17,739
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/data/nvdcve/DriverLoader.java
|
DriverLoader.load
|
private static Driver load(String className, ClassLoader loader) throws DriverLoadException {
try {
final Class<?> c = Class.forName(className, true, loader);
//final Class c = loader.loadClass(className);
final Driver driver = (Driver) c.getDeclaredConstructor().newInstance();
//TODO add usage count so we don't de-register a driver that is in use.
final Driver shim = new DriverShim(driver);
//using the DriverShim to get around the fact that the DriverManager won't register a driver not in the base class path
DriverManager.registerDriver(shim);
return shim;
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException
| NoSuchMethodException | SecurityException | IllegalArgumentException | InvocationTargetException ex) {
final String msg = String.format("Unable to load database driver '%s'", className);
LOGGER.debug(msg, ex);
throw new DriverLoadException(msg, ex);
}
}
|
java
|
private static Driver load(String className, ClassLoader loader) throws DriverLoadException {
try {
final Class<?> c = Class.forName(className, true, loader);
//final Class c = loader.loadClass(className);
final Driver driver = (Driver) c.getDeclaredConstructor().newInstance();
//TODO add usage count so we don't de-register a driver that is in use.
final Driver shim = new DriverShim(driver);
//using the DriverShim to get around the fact that the DriverManager won't register a driver not in the base class path
DriverManager.registerDriver(shim);
return shim;
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException
| NoSuchMethodException | SecurityException | IllegalArgumentException | InvocationTargetException ex) {
final String msg = String.format("Unable to load database driver '%s'", className);
LOGGER.debug(msg, ex);
throw new DriverLoadException(msg, ex);
}
}
|
[
"private",
"static",
"Driver",
"load",
"(",
"String",
"className",
",",
"ClassLoader",
"loader",
")",
"throws",
"DriverLoadException",
"{",
"try",
"{",
"final",
"Class",
"<",
"?",
">",
"c",
"=",
"Class",
".",
"forName",
"(",
"className",
",",
"true",
",",
"loader",
")",
";",
"//final Class c = loader.loadClass(className);",
"final",
"Driver",
"driver",
"=",
"(",
"Driver",
")",
"c",
".",
"getDeclaredConstructor",
"(",
")",
".",
"newInstance",
"(",
")",
";",
"//TODO add usage count so we don't de-register a driver that is in use.",
"final",
"Driver",
"shim",
"=",
"new",
"DriverShim",
"(",
"driver",
")",
";",
"//using the DriverShim to get around the fact that the DriverManager won't register a driver not in the base class path",
"DriverManager",
".",
"registerDriver",
"(",
"shim",
")",
";",
"return",
"shim",
";",
"}",
"catch",
"(",
"ClassNotFoundException",
"|",
"InstantiationException",
"|",
"IllegalAccessException",
"|",
"SQLException",
"|",
"NoSuchMethodException",
"|",
"SecurityException",
"|",
"IllegalArgumentException",
"|",
"InvocationTargetException",
"ex",
")",
"{",
"final",
"String",
"msg",
"=",
"String",
".",
"format",
"(",
"\"Unable to load database driver '%s'\"",
",",
"className",
")",
";",
"LOGGER",
".",
"debug",
"(",
"msg",
",",
"ex",
")",
";",
"throw",
"new",
"DriverLoadException",
"(",
"msg",
",",
"ex",
")",
";",
"}",
"}"
] |
Loads the specified class using the supplied class loader and registers
the driver with the driver manager.
@param className the fully qualified name of the desired class
@param loader the class loader to use when loading the driver
@return the loaded Driver
@throws DriverLoadException thrown if the driver cannot be loaded
|
[
"Loads",
"the",
"specified",
"class",
"using",
"the",
"supplied",
"class",
"loader",
"and",
"registers",
"the",
"driver",
"with",
"the",
"driver",
"manager",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/data/nvdcve/DriverLoader.java#L148-L165
|
17,740
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/reporting/ReportGenerator.java
|
ReportGenerator.createContext
|
private VelocityContext createContext(String applicationName, List<Dependency> dependencies,
List<Analyzer> analyzers, DatabaseProperties properties) {
final DateTime dt = new DateTime();
final DateTimeFormatter dateFormat = DateTimeFormat.forPattern("MMM d, yyyy 'at' HH:mm:ss z");
final DateTimeFormatter dateFormatXML = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
final String scanDate = dateFormat.print(dt);
final String scanDateXML = dateFormatXML.print(dt);
final VelocityContext ctxt = new VelocityContext();
ctxt.put("applicationName", applicationName);
ctxt.put("dependencies", dependencies);
ctxt.put("analyzers", analyzers);
ctxt.put("properties", properties);
ctxt.put("scanDate", scanDate);
ctxt.put("scanDateXML", scanDateXML);
ctxt.put("enc", new EscapeTool());
ctxt.put("rpt", new ReportTool());
ctxt.put("WordUtils", new WordUtils());
ctxt.put("VENDOR", EvidenceType.VENDOR);
ctxt.put("PRODUCT", EvidenceType.PRODUCT);
ctxt.put("VERSION", EvidenceType.VERSION);
ctxt.put("version", settings.getString(Settings.KEYS.APPLICATION_VERSION, "Unknown"));
return ctxt;
}
|
java
|
private VelocityContext createContext(String applicationName, List<Dependency> dependencies,
List<Analyzer> analyzers, DatabaseProperties properties) {
final DateTime dt = new DateTime();
final DateTimeFormatter dateFormat = DateTimeFormat.forPattern("MMM d, yyyy 'at' HH:mm:ss z");
final DateTimeFormatter dateFormatXML = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
final String scanDate = dateFormat.print(dt);
final String scanDateXML = dateFormatXML.print(dt);
final VelocityContext ctxt = new VelocityContext();
ctxt.put("applicationName", applicationName);
ctxt.put("dependencies", dependencies);
ctxt.put("analyzers", analyzers);
ctxt.put("properties", properties);
ctxt.put("scanDate", scanDate);
ctxt.put("scanDateXML", scanDateXML);
ctxt.put("enc", new EscapeTool());
ctxt.put("rpt", new ReportTool());
ctxt.put("WordUtils", new WordUtils());
ctxt.put("VENDOR", EvidenceType.VENDOR);
ctxt.put("PRODUCT", EvidenceType.PRODUCT);
ctxt.put("VERSION", EvidenceType.VERSION);
ctxt.put("version", settings.getString(Settings.KEYS.APPLICATION_VERSION, "Unknown"));
return ctxt;
}
|
[
"private",
"VelocityContext",
"createContext",
"(",
"String",
"applicationName",
",",
"List",
"<",
"Dependency",
">",
"dependencies",
",",
"List",
"<",
"Analyzer",
">",
"analyzers",
",",
"DatabaseProperties",
"properties",
")",
"{",
"final",
"DateTime",
"dt",
"=",
"new",
"DateTime",
"(",
")",
";",
"final",
"DateTimeFormatter",
"dateFormat",
"=",
"DateTimeFormat",
".",
"forPattern",
"(",
"\"MMM d, yyyy 'at' HH:mm:ss z\"",
")",
";",
"final",
"DateTimeFormatter",
"dateFormatXML",
"=",
"DateTimeFormat",
".",
"forPattern",
"(",
"\"yyyy-MM-dd'T'HH:mm:ss.SSSZ\"",
")",
";",
"final",
"String",
"scanDate",
"=",
"dateFormat",
".",
"print",
"(",
"dt",
")",
";",
"final",
"String",
"scanDateXML",
"=",
"dateFormatXML",
".",
"print",
"(",
"dt",
")",
";",
"final",
"VelocityContext",
"ctxt",
"=",
"new",
"VelocityContext",
"(",
")",
";",
"ctxt",
".",
"put",
"(",
"\"applicationName\"",
",",
"applicationName",
")",
";",
"ctxt",
".",
"put",
"(",
"\"dependencies\"",
",",
"dependencies",
")",
";",
"ctxt",
".",
"put",
"(",
"\"analyzers\"",
",",
"analyzers",
")",
";",
"ctxt",
".",
"put",
"(",
"\"properties\"",
",",
"properties",
")",
";",
"ctxt",
".",
"put",
"(",
"\"scanDate\"",
",",
"scanDate",
")",
";",
"ctxt",
".",
"put",
"(",
"\"scanDateXML\"",
",",
"scanDateXML",
")",
";",
"ctxt",
".",
"put",
"(",
"\"enc\"",
",",
"new",
"EscapeTool",
"(",
")",
")",
";",
"ctxt",
".",
"put",
"(",
"\"rpt\"",
",",
"new",
"ReportTool",
"(",
")",
")",
";",
"ctxt",
".",
"put",
"(",
"\"WordUtils\"",
",",
"new",
"WordUtils",
"(",
")",
")",
";",
"ctxt",
".",
"put",
"(",
"\"VENDOR\"",
",",
"EvidenceType",
".",
"VENDOR",
")",
";",
"ctxt",
".",
"put",
"(",
"\"PRODUCT\"",
",",
"EvidenceType",
".",
"PRODUCT",
")",
";",
"ctxt",
".",
"put",
"(",
"\"VERSION\"",
",",
"EvidenceType",
".",
"VERSION",
")",
";",
"ctxt",
".",
"put",
"(",
"\"version\"",
",",
"settings",
".",
"getString",
"(",
"Settings",
".",
"KEYS",
".",
"APPLICATION_VERSION",
",",
"\"Unknown\"",
")",
")",
";",
"return",
"ctxt",
";",
"}"
] |
Constructs the velocity context used to generate the dependency-check
reports.
@param applicationName the application name being analyzed
@param dependencies the list of dependencies
@param analyzers the list of analyzers used
@param properties the database properties (containing timestamps of the
NVD CVE data)
@return the velocity context
|
[
"Constructs",
"the",
"velocity",
"context",
"used",
"to",
"generate",
"the",
"dependency",
"-",
"check",
"reports",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/reporting/ReportGenerator.java#L183-L207
|
17,741
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/reporting/ReportGenerator.java
|
ReportGenerator.write
|
public void write(String outputLocation, String format) throws ReportException {
Format reportFormat = null;
try {
reportFormat = Format.valueOf(format.toUpperCase());
} catch (IllegalArgumentException ex) {
LOGGER.trace("ignore this exception", ex);
}
if (reportFormat != null) {
write(outputLocation, reportFormat);
} else {
final File out = getReportFile(outputLocation, null);
if (out.isDirectory()) {
throw new ReportException("Unable to write non-standard VSL output to a directory, please specify a file name");
}
processTemplate(format, out);
}
}
|
java
|
public void write(String outputLocation, String format) throws ReportException {
Format reportFormat = null;
try {
reportFormat = Format.valueOf(format.toUpperCase());
} catch (IllegalArgumentException ex) {
LOGGER.trace("ignore this exception", ex);
}
if (reportFormat != null) {
write(outputLocation, reportFormat);
} else {
final File out = getReportFile(outputLocation, null);
if (out.isDirectory()) {
throw new ReportException("Unable to write non-standard VSL output to a directory, please specify a file name");
}
processTemplate(format, out);
}
}
|
[
"public",
"void",
"write",
"(",
"String",
"outputLocation",
",",
"String",
"format",
")",
"throws",
"ReportException",
"{",
"Format",
"reportFormat",
"=",
"null",
";",
"try",
"{",
"reportFormat",
"=",
"Format",
".",
"valueOf",
"(",
"format",
".",
"toUpperCase",
"(",
")",
")",
";",
"}",
"catch",
"(",
"IllegalArgumentException",
"ex",
")",
"{",
"LOGGER",
".",
"trace",
"(",
"\"ignore this exception\"",
",",
"ex",
")",
";",
"}",
"if",
"(",
"reportFormat",
"!=",
"null",
")",
"{",
"write",
"(",
"outputLocation",
",",
"reportFormat",
")",
";",
"}",
"else",
"{",
"final",
"File",
"out",
"=",
"getReportFile",
"(",
"outputLocation",
",",
"null",
")",
";",
"if",
"(",
"out",
".",
"isDirectory",
"(",
")",
")",
"{",
"throw",
"new",
"ReportException",
"(",
"\"Unable to write non-standard VSL output to a directory, please specify a file name\"",
")",
";",
"}",
"processTemplate",
"(",
"format",
",",
"out",
")",
";",
"}",
"}"
] |
Writes the dependency-check report to the given output location.
@param outputLocation the path where the reports should be written
@param format the format the report should be written in (XML, HTML,
JSON, CSV, ALL) or even the path to a custom velocity template (either
fully qualified or the template name on the class path).
@throws ReportException is thrown if there is an error creating out the
reports
|
[
"Writes",
"the",
"dependency",
"-",
"check",
"report",
"to",
"the",
"given",
"output",
"location",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/reporting/ReportGenerator.java#L219-L237
|
17,742
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/reporting/ReportGenerator.java
|
ReportGenerator.getReportFile
|
protected File getReportFile(String outputLocation, Format format) {
File outFile = new File(outputLocation);
if (outFile.getParentFile() == null) {
outFile = new File(".", outputLocation);
}
final String pathToCheck = outputLocation.toLowerCase();
if (format == Format.XML && !pathToCheck.endsWith(".xml")) {
return new File(outFile, "dependency-check-report.xml");
}
if (format == Format.HTML && !pathToCheck.endsWith(".html") && !pathToCheck.endsWith(".htm")) {
return new File(outFile, "dependency-check-report.html");
}
if (format == Format.JSON && !pathToCheck.endsWith(".json")) {
return new File(outFile, "dependency-check-report.json");
}
if (format == Format.CSV && !pathToCheck.endsWith(".csv")) {
return new File(outFile, "dependency-check-report.csv");
}
if (format == Format.JUNIT && !pathToCheck.endsWith(".xml")) {
return new File(outFile, "dependency-check-junit.xml");
}
return outFile;
}
|
java
|
protected File getReportFile(String outputLocation, Format format) {
File outFile = new File(outputLocation);
if (outFile.getParentFile() == null) {
outFile = new File(".", outputLocation);
}
final String pathToCheck = outputLocation.toLowerCase();
if (format == Format.XML && !pathToCheck.endsWith(".xml")) {
return new File(outFile, "dependency-check-report.xml");
}
if (format == Format.HTML && !pathToCheck.endsWith(".html") && !pathToCheck.endsWith(".htm")) {
return new File(outFile, "dependency-check-report.html");
}
if (format == Format.JSON && !pathToCheck.endsWith(".json")) {
return new File(outFile, "dependency-check-report.json");
}
if (format == Format.CSV && !pathToCheck.endsWith(".csv")) {
return new File(outFile, "dependency-check-report.csv");
}
if (format == Format.JUNIT && !pathToCheck.endsWith(".xml")) {
return new File(outFile, "dependency-check-junit.xml");
}
return outFile;
}
|
[
"protected",
"File",
"getReportFile",
"(",
"String",
"outputLocation",
",",
"Format",
"format",
")",
"{",
"File",
"outFile",
"=",
"new",
"File",
"(",
"outputLocation",
")",
";",
"if",
"(",
"outFile",
".",
"getParentFile",
"(",
")",
"==",
"null",
")",
"{",
"outFile",
"=",
"new",
"File",
"(",
"\".\"",
",",
"outputLocation",
")",
";",
"}",
"final",
"String",
"pathToCheck",
"=",
"outputLocation",
".",
"toLowerCase",
"(",
")",
";",
"if",
"(",
"format",
"==",
"Format",
".",
"XML",
"&&",
"!",
"pathToCheck",
".",
"endsWith",
"(",
"\".xml\"",
")",
")",
"{",
"return",
"new",
"File",
"(",
"outFile",
",",
"\"dependency-check-report.xml\"",
")",
";",
"}",
"if",
"(",
"format",
"==",
"Format",
".",
"HTML",
"&&",
"!",
"pathToCheck",
".",
"endsWith",
"(",
"\".html\"",
")",
"&&",
"!",
"pathToCheck",
".",
"endsWith",
"(",
"\".htm\"",
")",
")",
"{",
"return",
"new",
"File",
"(",
"outFile",
",",
"\"dependency-check-report.html\"",
")",
";",
"}",
"if",
"(",
"format",
"==",
"Format",
".",
"JSON",
"&&",
"!",
"pathToCheck",
".",
"endsWith",
"(",
"\".json\"",
")",
")",
"{",
"return",
"new",
"File",
"(",
"outFile",
",",
"\"dependency-check-report.json\"",
")",
";",
"}",
"if",
"(",
"format",
"==",
"Format",
".",
"CSV",
"&&",
"!",
"pathToCheck",
".",
"endsWith",
"(",
"\".csv\"",
")",
")",
"{",
"return",
"new",
"File",
"(",
"outFile",
",",
"\"dependency-check-report.csv\"",
")",
";",
"}",
"if",
"(",
"format",
"==",
"Format",
".",
"JUNIT",
"&&",
"!",
"pathToCheck",
".",
"endsWith",
"(",
"\".xml\"",
")",
")",
"{",
"return",
"new",
"File",
"(",
"outFile",
",",
"\"dependency-check-junit.xml\"",
")",
";",
"}",
"return",
"outFile",
";",
"}"
] |
Determines the report file name based on the give output location and
format. If the output location contains a full file name that has the
correct extension for the given report type then the output location is
returned. However, if the output location is a directory, this method
will generate the correct name for the given output format.
@param outputLocation the specified output location
@param format the report format
@return the report File
|
[
"Determines",
"the",
"report",
"file",
"name",
"based",
"on",
"the",
"give",
"output",
"location",
"and",
"format",
".",
"If",
"the",
"output",
"location",
"contains",
"a",
"full",
"file",
"name",
"that",
"has",
"the",
"correct",
"extension",
"for",
"the",
"given",
"report",
"type",
"then",
"the",
"output",
"location",
"is",
"returned",
".",
"However",
"if",
"the",
"output",
"location",
"is",
"a",
"directory",
"this",
"method",
"will",
"generate",
"the",
"correct",
"name",
"for",
"the",
"given",
"output",
"format",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/reporting/ReportGenerator.java#L275-L297
|
17,743
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/reporting/ReportGenerator.java
|
ReportGenerator.ensureParentDirectoryExists
|
private void ensureParentDirectoryExists(File file) throws ReportException {
if (!file.getParentFile().exists()) {
final boolean created = file.getParentFile().mkdirs();
if (!created) {
final String msg = String.format("Unable to create directory '%s'.", file.getParentFile().getAbsolutePath());
throw new ReportException(msg);
}
}
}
|
java
|
private void ensureParentDirectoryExists(File file) throws ReportException {
if (!file.getParentFile().exists()) {
final boolean created = file.getParentFile().mkdirs();
if (!created) {
final String msg = String.format("Unable to create directory '%s'.", file.getParentFile().getAbsolutePath());
throw new ReportException(msg);
}
}
}
|
[
"private",
"void",
"ensureParentDirectoryExists",
"(",
"File",
"file",
")",
"throws",
"ReportException",
"{",
"if",
"(",
"!",
"file",
".",
"getParentFile",
"(",
")",
".",
"exists",
"(",
")",
")",
"{",
"final",
"boolean",
"created",
"=",
"file",
".",
"getParentFile",
"(",
")",
".",
"mkdirs",
"(",
")",
";",
"if",
"(",
"!",
"created",
")",
"{",
"final",
"String",
"msg",
"=",
"String",
".",
"format",
"(",
"\"Unable to create directory '%s'.\"",
",",
"file",
".",
"getParentFile",
"(",
")",
".",
"getAbsolutePath",
"(",
")",
")",
";",
"throw",
"new",
"ReportException",
"(",
"msg",
")",
";",
"}",
"}",
"}"
] |
Validates that the given file's parent directory exists. If the directory
does not exist an attempt to create the necessary path is made; if that
fails a ReportException will be raised.
@param file the file or directory directory
@throws ReportException thrown if the parent directory does not exist and
cannot be created
|
[
"Validates",
"that",
"the",
"given",
"file",
"s",
"parent",
"directory",
"exists",
".",
"If",
"the",
"directory",
"does",
"not",
"exist",
"an",
"attempt",
"to",
"create",
"the",
"necessary",
"path",
"is",
"made",
";",
"if",
"that",
"fails",
"a",
"ReportException",
"will",
"be",
"raised",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/reporting/ReportGenerator.java#L384-L392
|
17,744
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/reporting/ReportGenerator.java
|
ReportGenerator.pretifyJson
|
private void pretifyJson(String pathToJson) throws ReportException {
final String outputPath = pathToJson + ".pretty";
final File in = new File(pathToJson);
final File out = new File(outputPath);
try (JsonReader reader = new JsonReader(new InputStreamReader(new FileInputStream(in), StandardCharsets.UTF_8));
JsonWriter writer = new JsonWriter(new OutputStreamWriter(new FileOutputStream(out), StandardCharsets.UTF_8))) {
prettyPrint(reader, writer);
} catch (IOException ex) {
LOGGER.debug("Malformed JSON?", ex);
throw new ReportException("Unable to generate json report", ex);
}
if (out.isFile() && in.isFile() && in.delete()) {
try {
org.apache.commons.io.FileUtils.moveFile(out, in);
} catch (IOException ex) {
LOGGER.error("Unable to generate pretty report, caused by: {}", ex.getMessage());
}
}
}
|
java
|
private void pretifyJson(String pathToJson) throws ReportException {
final String outputPath = pathToJson + ".pretty";
final File in = new File(pathToJson);
final File out = new File(outputPath);
try (JsonReader reader = new JsonReader(new InputStreamReader(new FileInputStream(in), StandardCharsets.UTF_8));
JsonWriter writer = new JsonWriter(new OutputStreamWriter(new FileOutputStream(out), StandardCharsets.UTF_8))) {
prettyPrint(reader, writer);
} catch (IOException ex) {
LOGGER.debug("Malformed JSON?", ex);
throw new ReportException("Unable to generate json report", ex);
}
if (out.isFile() && in.isFile() && in.delete()) {
try {
org.apache.commons.io.FileUtils.moveFile(out, in);
} catch (IOException ex) {
LOGGER.error("Unable to generate pretty report, caused by: {}", ex.getMessage());
}
}
}
|
[
"private",
"void",
"pretifyJson",
"(",
"String",
"pathToJson",
")",
"throws",
"ReportException",
"{",
"final",
"String",
"outputPath",
"=",
"pathToJson",
"+",
"\".pretty\"",
";",
"final",
"File",
"in",
"=",
"new",
"File",
"(",
"pathToJson",
")",
";",
"final",
"File",
"out",
"=",
"new",
"File",
"(",
"outputPath",
")",
";",
"try",
"(",
"JsonReader",
"reader",
"=",
"new",
"JsonReader",
"(",
"new",
"InputStreamReader",
"(",
"new",
"FileInputStream",
"(",
"in",
")",
",",
"StandardCharsets",
".",
"UTF_8",
")",
")",
";",
"JsonWriter",
"writer",
"=",
"new",
"JsonWriter",
"(",
"new",
"OutputStreamWriter",
"(",
"new",
"FileOutputStream",
"(",
"out",
")",
",",
"StandardCharsets",
".",
"UTF_8",
")",
")",
")",
"{",
"prettyPrint",
"(",
"reader",
",",
"writer",
")",
";",
"}",
"catch",
"(",
"IOException",
"ex",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"Malformed JSON?\"",
",",
"ex",
")",
";",
"throw",
"new",
"ReportException",
"(",
"\"Unable to generate json report\"",
",",
"ex",
")",
";",
"}",
"if",
"(",
"out",
".",
"isFile",
"(",
")",
"&&",
"in",
".",
"isFile",
"(",
")",
"&&",
"in",
".",
"delete",
"(",
")",
")",
"{",
"try",
"{",
"org",
".",
"apache",
".",
"commons",
".",
"io",
".",
"FileUtils",
".",
"moveFile",
"(",
"out",
",",
"in",
")",
";",
"}",
"catch",
"(",
"IOException",
"ex",
")",
"{",
"LOGGER",
".",
"error",
"(",
"\"Unable to generate pretty report, caused by: {}\"",
",",
"ex",
".",
"getMessage",
"(",
")",
")",
";",
"}",
"}",
"}"
] |
Reformats the given JSON file.
@param pathToJson the path to the JSON file to be reformatted
@throws ReportException thrown if the given JSON file is malformed
|
[
"Reformats",
"the",
"given",
"JSON",
"file",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/reporting/ReportGenerator.java#L400-L418
|
17,745
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/reporting/ReportGenerator.java
|
ReportGenerator.prettyPrint
|
private static void prettyPrint(JsonReader reader, JsonWriter writer) throws IOException {
writer.setIndent(" ");
while (true) {
final JsonToken token = reader.peek();
switch (token) {
case BEGIN_ARRAY:
reader.beginArray();
writer.beginArray();
break;
case END_ARRAY:
reader.endArray();
writer.endArray();
break;
case BEGIN_OBJECT:
reader.beginObject();
writer.beginObject();
break;
case END_OBJECT:
reader.endObject();
writer.endObject();
break;
case NAME:
final String name = reader.nextName();
writer.name(name);
break;
case STRING:
final String s = reader.nextString();
writer.value(s);
break;
case NUMBER:
final String n = reader.nextString();
writer.value(new BigDecimal(n));
break;
case BOOLEAN:
final boolean b = reader.nextBoolean();
writer.value(b);
break;
case NULL:
reader.nextNull();
writer.nullValue();
break;
case END_DOCUMENT:
return;
default:
LOGGER.debug("Unexpected JSON toekn {}", token.toString());
break;
}
}
}
|
java
|
private static void prettyPrint(JsonReader reader, JsonWriter writer) throws IOException {
writer.setIndent(" ");
while (true) {
final JsonToken token = reader.peek();
switch (token) {
case BEGIN_ARRAY:
reader.beginArray();
writer.beginArray();
break;
case END_ARRAY:
reader.endArray();
writer.endArray();
break;
case BEGIN_OBJECT:
reader.beginObject();
writer.beginObject();
break;
case END_OBJECT:
reader.endObject();
writer.endObject();
break;
case NAME:
final String name = reader.nextName();
writer.name(name);
break;
case STRING:
final String s = reader.nextString();
writer.value(s);
break;
case NUMBER:
final String n = reader.nextString();
writer.value(new BigDecimal(n));
break;
case BOOLEAN:
final boolean b = reader.nextBoolean();
writer.value(b);
break;
case NULL:
reader.nextNull();
writer.nullValue();
break;
case END_DOCUMENT:
return;
default:
LOGGER.debug("Unexpected JSON toekn {}", token.toString());
break;
}
}
}
|
[
"private",
"static",
"void",
"prettyPrint",
"(",
"JsonReader",
"reader",
",",
"JsonWriter",
"writer",
")",
"throws",
"IOException",
"{",
"writer",
".",
"setIndent",
"(",
"\" \"",
")",
";",
"while",
"(",
"true",
")",
"{",
"final",
"JsonToken",
"token",
"=",
"reader",
".",
"peek",
"(",
")",
";",
"switch",
"(",
"token",
")",
"{",
"case",
"BEGIN_ARRAY",
":",
"reader",
".",
"beginArray",
"(",
")",
";",
"writer",
".",
"beginArray",
"(",
")",
";",
"break",
";",
"case",
"END_ARRAY",
":",
"reader",
".",
"endArray",
"(",
")",
";",
"writer",
".",
"endArray",
"(",
")",
";",
"break",
";",
"case",
"BEGIN_OBJECT",
":",
"reader",
".",
"beginObject",
"(",
")",
";",
"writer",
".",
"beginObject",
"(",
")",
";",
"break",
";",
"case",
"END_OBJECT",
":",
"reader",
".",
"endObject",
"(",
")",
";",
"writer",
".",
"endObject",
"(",
")",
";",
"break",
";",
"case",
"NAME",
":",
"final",
"String",
"name",
"=",
"reader",
".",
"nextName",
"(",
")",
";",
"writer",
".",
"name",
"(",
"name",
")",
";",
"break",
";",
"case",
"STRING",
":",
"final",
"String",
"s",
"=",
"reader",
".",
"nextString",
"(",
")",
";",
"writer",
".",
"value",
"(",
"s",
")",
";",
"break",
";",
"case",
"NUMBER",
":",
"final",
"String",
"n",
"=",
"reader",
".",
"nextString",
"(",
")",
";",
"writer",
".",
"value",
"(",
"new",
"BigDecimal",
"(",
"n",
")",
")",
";",
"break",
";",
"case",
"BOOLEAN",
":",
"final",
"boolean",
"b",
"=",
"reader",
".",
"nextBoolean",
"(",
")",
";",
"writer",
".",
"value",
"(",
"b",
")",
";",
"break",
";",
"case",
"NULL",
":",
"reader",
".",
"nextNull",
"(",
")",
";",
"writer",
".",
"nullValue",
"(",
")",
";",
"break",
";",
"case",
"END_DOCUMENT",
":",
"return",
";",
"default",
":",
"LOGGER",
".",
"debug",
"(",
"\"Unexpected JSON toekn {}\"",
",",
"token",
".",
"toString",
"(",
")",
")",
";",
"break",
";",
"}",
"}",
"}"
] |
Streams from a json reader to a json writer and performs pretty printing.
This function is copied from https://sites.google.com/site/gson/streaming
@param reader json reader
@param writer json writer
@throws IOException thrown if the json is malformed
|
[
"Streams",
"from",
"a",
"json",
"reader",
"to",
"a",
"json",
"writer",
"and",
"performs",
"pretty",
"printing",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/reporting/ReportGenerator.java#L429-L477
|
17,746
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/analyzer/RubyBundleAuditAnalyzer.java
|
RubyBundleAuditAnalyzer.launchBundleAudit
|
private Process launchBundleAudit(File folder) throws AnalysisException {
if (!folder.isDirectory()) {
throw new AnalysisException(String.format("%s should have been a directory.", folder.getAbsolutePath()));
}
final List<String> args = new ArrayList<>();
final String bundleAuditPath = getSettings().getString(Settings.KEYS.ANALYZER_BUNDLE_AUDIT_PATH);
File bundleAudit = null;
if (bundleAuditPath != null) {
bundleAudit = new File(bundleAuditPath);
if (!bundleAudit.isFile()) {
LOGGER.warn("Supplied `bundleAudit` path is incorrect: {}", bundleAuditPath);
bundleAudit = null;
}
}
args.add(bundleAudit != null && bundleAudit.isFile() ? bundleAudit.getAbsolutePath() : "bundle-audit");
args.add("check");
args.add("--verbose");
final ProcessBuilder builder = new ProcessBuilder(args);
builder.directory(folder);
try {
LOGGER.info("Launching: {} from {}", args, folder);
return builder.start();
} catch (IOException ioe) {
throw new AnalysisException("bundle-audit initialization failure; this error can be ignored if you are not analyzing Ruby. "
+ "Otherwise ensure that bundle-audit is installed and the path to bundle audit is correctly specified", ioe);
}
}
|
java
|
private Process launchBundleAudit(File folder) throws AnalysisException {
if (!folder.isDirectory()) {
throw new AnalysisException(String.format("%s should have been a directory.", folder.getAbsolutePath()));
}
final List<String> args = new ArrayList<>();
final String bundleAuditPath = getSettings().getString(Settings.KEYS.ANALYZER_BUNDLE_AUDIT_PATH);
File bundleAudit = null;
if (bundleAuditPath != null) {
bundleAudit = new File(bundleAuditPath);
if (!bundleAudit.isFile()) {
LOGGER.warn("Supplied `bundleAudit` path is incorrect: {}", bundleAuditPath);
bundleAudit = null;
}
}
args.add(bundleAudit != null && bundleAudit.isFile() ? bundleAudit.getAbsolutePath() : "bundle-audit");
args.add("check");
args.add("--verbose");
final ProcessBuilder builder = new ProcessBuilder(args);
builder.directory(folder);
try {
LOGGER.info("Launching: {} from {}", args, folder);
return builder.start();
} catch (IOException ioe) {
throw new AnalysisException("bundle-audit initialization failure; this error can be ignored if you are not analyzing Ruby. "
+ "Otherwise ensure that bundle-audit is installed and the path to bundle audit is correctly specified", ioe);
}
}
|
[
"private",
"Process",
"launchBundleAudit",
"(",
"File",
"folder",
")",
"throws",
"AnalysisException",
"{",
"if",
"(",
"!",
"folder",
".",
"isDirectory",
"(",
")",
")",
"{",
"throw",
"new",
"AnalysisException",
"(",
"String",
".",
"format",
"(",
"\"%s should have been a directory.\"",
",",
"folder",
".",
"getAbsolutePath",
"(",
")",
")",
")",
";",
"}",
"final",
"List",
"<",
"String",
">",
"args",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"final",
"String",
"bundleAuditPath",
"=",
"getSettings",
"(",
")",
".",
"getString",
"(",
"Settings",
".",
"KEYS",
".",
"ANALYZER_BUNDLE_AUDIT_PATH",
")",
";",
"File",
"bundleAudit",
"=",
"null",
";",
"if",
"(",
"bundleAuditPath",
"!=",
"null",
")",
"{",
"bundleAudit",
"=",
"new",
"File",
"(",
"bundleAuditPath",
")",
";",
"if",
"(",
"!",
"bundleAudit",
".",
"isFile",
"(",
")",
")",
"{",
"LOGGER",
".",
"warn",
"(",
"\"Supplied `bundleAudit` path is incorrect: {}\"",
",",
"bundleAuditPath",
")",
";",
"bundleAudit",
"=",
"null",
";",
"}",
"}",
"args",
".",
"add",
"(",
"bundleAudit",
"!=",
"null",
"&&",
"bundleAudit",
".",
"isFile",
"(",
")",
"?",
"bundleAudit",
".",
"getAbsolutePath",
"(",
")",
":",
"\"bundle-audit\"",
")",
";",
"args",
".",
"add",
"(",
"\"check\"",
")",
";",
"args",
".",
"add",
"(",
"\"--verbose\"",
")",
";",
"final",
"ProcessBuilder",
"builder",
"=",
"new",
"ProcessBuilder",
"(",
"args",
")",
";",
"builder",
".",
"directory",
"(",
"folder",
")",
";",
"try",
"{",
"LOGGER",
".",
"info",
"(",
"\"Launching: {} from {}\"",
",",
"args",
",",
"folder",
")",
";",
"return",
"builder",
".",
"start",
"(",
")",
";",
"}",
"catch",
"(",
"IOException",
"ioe",
")",
"{",
"throw",
"new",
"AnalysisException",
"(",
"\"bundle-audit initialization failure; this error can be ignored if you are not analyzing Ruby. \"",
"+",
"\"Otherwise ensure that bundle-audit is installed and the path to bundle audit is correctly specified\"",
",",
"ioe",
")",
";",
"}",
"}"
] |
Launch bundle-audit.
@param folder directory that contains bundle audit
@return a handle to the process
@throws AnalysisException thrown when there is an issue launching bundle
audit
|
[
"Launch",
"bundle",
"-",
"audit",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/analyzer/RubyBundleAuditAnalyzer.java#L138-L164
|
17,747
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/analyzer/RubyBundleAuditAnalyzer.java
|
RubyBundleAuditAnalyzer.prepareFileTypeAnalyzer
|
@Override
public void prepareFileTypeAnalyzer(Engine engine) throws InitializationException {
// Now, need to see if bundle-audit actually runs from this location.
if (engine != null) {
this.cvedb = engine.getDatabase();
}
Process process = null;
try {
process = launchBundleAudit(getSettings().getTempDirectory());
} catch (AnalysisException ae) {
setEnabled(false);
final String msg = String.format("Exception from bundle-audit process: %s. Disabling %s", ae.getCause(), ANALYZER_NAME);
throw new InitializationException(msg, ae);
} catch (IOException ex) {
setEnabled(false);
throw new InitializationException("Unable to create temporary file, the Ruby Bundle Audit Analyzer will be disabled", ex);
}
final int exitValue;
try {
exitValue = process.waitFor();
} catch (InterruptedException ex) {
setEnabled(false);
final String msg = String.format("Bundle-audit process was interrupted. Disabling %s", ANALYZER_NAME);
Thread.currentThread().interrupt();
throw new InitializationException(msg);
}
if (0 == exitValue) {
setEnabled(false);
final String msg = String.format("Unexpected exit code from bundle-audit process. Disabling %s: %s", ANALYZER_NAME, exitValue);
throw new InitializationException(msg);
} else {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getErrorStream(), StandardCharsets.UTF_8))) {
if (!reader.ready()) {
LOGGER.warn("Bundle-audit error stream unexpectedly not ready. Disabling {}", ANALYZER_NAME);
setEnabled(false);
throw new InitializationException("Bundle-audit error stream unexpectedly not ready.");
} else {
final String line = reader.readLine();
if (line == null || !line.contains("Errno::ENOENT")) {
LOGGER.warn("Unexpected bundle-audit output. Disabling {}: {}", ANALYZER_NAME, line);
setEnabled(false);
throw new InitializationException("Unexpected bundle-audit output.");
}
}
} catch (UnsupportedEncodingException ex) {
setEnabled(false);
throw new InitializationException("Unexpected bundle-audit encoding.", ex);
} catch (IOException ex) {
setEnabled(false);
throw new InitializationException("Unable to read bundle-audit output.", ex);
}
}
if (isEnabled()) {
LOGGER.info("{} is enabled. It is necessary to manually run \"bundle-audit update\" "
+ "occasionally to keep its database up to date.", ANALYZER_NAME);
}
}
|
java
|
@Override
public void prepareFileTypeAnalyzer(Engine engine) throws InitializationException {
// Now, need to see if bundle-audit actually runs from this location.
if (engine != null) {
this.cvedb = engine.getDatabase();
}
Process process = null;
try {
process = launchBundleAudit(getSettings().getTempDirectory());
} catch (AnalysisException ae) {
setEnabled(false);
final String msg = String.format("Exception from bundle-audit process: %s. Disabling %s", ae.getCause(), ANALYZER_NAME);
throw new InitializationException(msg, ae);
} catch (IOException ex) {
setEnabled(false);
throw new InitializationException("Unable to create temporary file, the Ruby Bundle Audit Analyzer will be disabled", ex);
}
final int exitValue;
try {
exitValue = process.waitFor();
} catch (InterruptedException ex) {
setEnabled(false);
final String msg = String.format("Bundle-audit process was interrupted. Disabling %s", ANALYZER_NAME);
Thread.currentThread().interrupt();
throw new InitializationException(msg);
}
if (0 == exitValue) {
setEnabled(false);
final String msg = String.format("Unexpected exit code from bundle-audit process. Disabling %s: %s", ANALYZER_NAME, exitValue);
throw new InitializationException(msg);
} else {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getErrorStream(), StandardCharsets.UTF_8))) {
if (!reader.ready()) {
LOGGER.warn("Bundle-audit error stream unexpectedly not ready. Disabling {}", ANALYZER_NAME);
setEnabled(false);
throw new InitializationException("Bundle-audit error stream unexpectedly not ready.");
} else {
final String line = reader.readLine();
if (line == null || !line.contains("Errno::ENOENT")) {
LOGGER.warn("Unexpected bundle-audit output. Disabling {}: {}", ANALYZER_NAME, line);
setEnabled(false);
throw new InitializationException("Unexpected bundle-audit output.");
}
}
} catch (UnsupportedEncodingException ex) {
setEnabled(false);
throw new InitializationException("Unexpected bundle-audit encoding.", ex);
} catch (IOException ex) {
setEnabled(false);
throw new InitializationException("Unable to read bundle-audit output.", ex);
}
}
if (isEnabled()) {
LOGGER.info("{} is enabled. It is necessary to manually run \"bundle-audit update\" "
+ "occasionally to keep its database up to date.", ANALYZER_NAME);
}
}
|
[
"@",
"Override",
"public",
"void",
"prepareFileTypeAnalyzer",
"(",
"Engine",
"engine",
")",
"throws",
"InitializationException",
"{",
"// Now, need to see if bundle-audit actually runs from this location.",
"if",
"(",
"engine",
"!=",
"null",
")",
"{",
"this",
".",
"cvedb",
"=",
"engine",
".",
"getDatabase",
"(",
")",
";",
"}",
"Process",
"process",
"=",
"null",
";",
"try",
"{",
"process",
"=",
"launchBundleAudit",
"(",
"getSettings",
"(",
")",
".",
"getTempDirectory",
"(",
")",
")",
";",
"}",
"catch",
"(",
"AnalysisException",
"ae",
")",
"{",
"setEnabled",
"(",
"false",
")",
";",
"final",
"String",
"msg",
"=",
"String",
".",
"format",
"(",
"\"Exception from bundle-audit process: %s. Disabling %s\"",
",",
"ae",
".",
"getCause",
"(",
")",
",",
"ANALYZER_NAME",
")",
";",
"throw",
"new",
"InitializationException",
"(",
"msg",
",",
"ae",
")",
";",
"}",
"catch",
"(",
"IOException",
"ex",
")",
"{",
"setEnabled",
"(",
"false",
")",
";",
"throw",
"new",
"InitializationException",
"(",
"\"Unable to create temporary file, the Ruby Bundle Audit Analyzer will be disabled\"",
",",
"ex",
")",
";",
"}",
"final",
"int",
"exitValue",
";",
"try",
"{",
"exitValue",
"=",
"process",
".",
"waitFor",
"(",
")",
";",
"}",
"catch",
"(",
"InterruptedException",
"ex",
")",
"{",
"setEnabled",
"(",
"false",
")",
";",
"final",
"String",
"msg",
"=",
"String",
".",
"format",
"(",
"\"Bundle-audit process was interrupted. Disabling %s\"",
",",
"ANALYZER_NAME",
")",
";",
"Thread",
".",
"currentThread",
"(",
")",
".",
"interrupt",
"(",
")",
";",
"throw",
"new",
"InitializationException",
"(",
"msg",
")",
";",
"}",
"if",
"(",
"0",
"==",
"exitValue",
")",
"{",
"setEnabled",
"(",
"false",
")",
";",
"final",
"String",
"msg",
"=",
"String",
".",
"format",
"(",
"\"Unexpected exit code from bundle-audit process. Disabling %s: %s\"",
",",
"ANALYZER_NAME",
",",
"exitValue",
")",
";",
"throw",
"new",
"InitializationException",
"(",
"msg",
")",
";",
"}",
"else",
"{",
"try",
"(",
"BufferedReader",
"reader",
"=",
"new",
"BufferedReader",
"(",
"new",
"InputStreamReader",
"(",
"process",
".",
"getErrorStream",
"(",
")",
",",
"StandardCharsets",
".",
"UTF_8",
")",
")",
")",
"{",
"if",
"(",
"!",
"reader",
".",
"ready",
"(",
")",
")",
"{",
"LOGGER",
".",
"warn",
"(",
"\"Bundle-audit error stream unexpectedly not ready. Disabling {}\"",
",",
"ANALYZER_NAME",
")",
";",
"setEnabled",
"(",
"false",
")",
";",
"throw",
"new",
"InitializationException",
"(",
"\"Bundle-audit error stream unexpectedly not ready.\"",
")",
";",
"}",
"else",
"{",
"final",
"String",
"line",
"=",
"reader",
".",
"readLine",
"(",
")",
";",
"if",
"(",
"line",
"==",
"null",
"||",
"!",
"line",
".",
"contains",
"(",
"\"Errno::ENOENT\"",
")",
")",
"{",
"LOGGER",
".",
"warn",
"(",
"\"Unexpected bundle-audit output. Disabling {}: {}\"",
",",
"ANALYZER_NAME",
",",
"line",
")",
";",
"setEnabled",
"(",
"false",
")",
";",
"throw",
"new",
"InitializationException",
"(",
"\"Unexpected bundle-audit output.\"",
")",
";",
"}",
"}",
"}",
"catch",
"(",
"UnsupportedEncodingException",
"ex",
")",
"{",
"setEnabled",
"(",
"false",
")",
";",
"throw",
"new",
"InitializationException",
"(",
"\"Unexpected bundle-audit encoding.\"",
",",
"ex",
")",
";",
"}",
"catch",
"(",
"IOException",
"ex",
")",
"{",
"setEnabled",
"(",
"false",
")",
";",
"throw",
"new",
"InitializationException",
"(",
"\"Unable to read bundle-audit output.\"",
",",
"ex",
")",
";",
"}",
"}",
"if",
"(",
"isEnabled",
"(",
")",
")",
"{",
"LOGGER",
".",
"info",
"(",
"\"{} is enabled. It is necessary to manually run \\\"bundle-audit update\\\" \"",
"+",
"\"occasionally to keep its database up to date.\"",
",",
"ANALYZER_NAME",
")",
";",
"}",
"}"
] |
Initialize the analyzer.
@param engine a reference to the dependency-check engine
@throws InitializationException if anything goes wrong
|
[
"Initialize",
"the",
"analyzer",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/analyzer/RubyBundleAuditAnalyzer.java#L172-L231
|
17,748
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/analyzer/RubyBundleAuditAnalyzer.java
|
RubyBundleAuditAnalyzer.analyzeDependency
|
@Override
protected void analyzeDependency(Dependency dependency, Engine engine)
throws AnalysisException {
if (needToDisableGemspecAnalyzer) {
boolean failed = true;
final String className = RubyGemspecAnalyzer.class.getName();
for (FileTypeAnalyzer analyzer : engine.getFileTypeAnalyzers()) {
if (analyzer instanceof RubyBundlerAnalyzer) {
((RubyBundlerAnalyzer) analyzer).setEnabled(false);
LOGGER.info("Disabled {} to avoid noisy duplicate results.", RubyBundlerAnalyzer.class.getName());
} else if (analyzer instanceof RubyGemspecAnalyzer) {
((RubyGemspecAnalyzer) analyzer).setEnabled(false);
LOGGER.info("Disabled {} to avoid noisy duplicate results.", className);
failed = false;
}
}
if (failed) {
LOGGER.warn("Did not find {}.", className);
}
needToDisableGemspecAnalyzer = false;
}
final File parentFile = dependency.getActualFile().getParentFile();
final Process process = launchBundleAudit(parentFile);
final int exitValue;
try {
exitValue = process.waitFor();
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
throw new AnalysisException("bundle-audit process interrupted", ie);
}
if (exitValue < 0 || exitValue > 1) {
final String msg = String.format("Unexpected exit code from bundle-audit process; exit code: %s", exitValue);
throw new AnalysisException(msg);
}
try {
try (BufferedReader errReader = new BufferedReader(new InputStreamReader(process.getErrorStream(), StandardCharsets.UTF_8))) {
while (errReader.ready()) {
final String error = errReader.readLine();
LOGGER.warn(error);
}
}
try (BufferedReader rdr = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))) {
processBundlerAuditOutput(dependency, engine, rdr);
}
} catch (IOException | CpeValidationException ioe) {
LOGGER.warn("bundle-audit failure", ioe);
}
}
|
java
|
@Override
protected void analyzeDependency(Dependency dependency, Engine engine)
throws AnalysisException {
if (needToDisableGemspecAnalyzer) {
boolean failed = true;
final String className = RubyGemspecAnalyzer.class.getName();
for (FileTypeAnalyzer analyzer : engine.getFileTypeAnalyzers()) {
if (analyzer instanceof RubyBundlerAnalyzer) {
((RubyBundlerAnalyzer) analyzer).setEnabled(false);
LOGGER.info("Disabled {} to avoid noisy duplicate results.", RubyBundlerAnalyzer.class.getName());
} else if (analyzer instanceof RubyGemspecAnalyzer) {
((RubyGemspecAnalyzer) analyzer).setEnabled(false);
LOGGER.info("Disabled {} to avoid noisy duplicate results.", className);
failed = false;
}
}
if (failed) {
LOGGER.warn("Did not find {}.", className);
}
needToDisableGemspecAnalyzer = false;
}
final File parentFile = dependency.getActualFile().getParentFile();
final Process process = launchBundleAudit(parentFile);
final int exitValue;
try {
exitValue = process.waitFor();
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
throw new AnalysisException("bundle-audit process interrupted", ie);
}
if (exitValue < 0 || exitValue > 1) {
final String msg = String.format("Unexpected exit code from bundle-audit process; exit code: %s", exitValue);
throw new AnalysisException(msg);
}
try {
try (BufferedReader errReader = new BufferedReader(new InputStreamReader(process.getErrorStream(), StandardCharsets.UTF_8))) {
while (errReader.ready()) {
final String error = errReader.readLine();
LOGGER.warn(error);
}
}
try (BufferedReader rdr = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))) {
processBundlerAuditOutput(dependency, engine, rdr);
}
} catch (IOException | CpeValidationException ioe) {
LOGGER.warn("bundle-audit failure", ioe);
}
}
|
[
"@",
"Override",
"protected",
"void",
"analyzeDependency",
"(",
"Dependency",
"dependency",
",",
"Engine",
"engine",
")",
"throws",
"AnalysisException",
"{",
"if",
"(",
"needToDisableGemspecAnalyzer",
")",
"{",
"boolean",
"failed",
"=",
"true",
";",
"final",
"String",
"className",
"=",
"RubyGemspecAnalyzer",
".",
"class",
".",
"getName",
"(",
")",
";",
"for",
"(",
"FileTypeAnalyzer",
"analyzer",
":",
"engine",
".",
"getFileTypeAnalyzers",
"(",
")",
")",
"{",
"if",
"(",
"analyzer",
"instanceof",
"RubyBundlerAnalyzer",
")",
"{",
"(",
"(",
"RubyBundlerAnalyzer",
")",
"analyzer",
")",
".",
"setEnabled",
"(",
"false",
")",
";",
"LOGGER",
".",
"info",
"(",
"\"Disabled {} to avoid noisy duplicate results.\"",
",",
"RubyBundlerAnalyzer",
".",
"class",
".",
"getName",
"(",
")",
")",
";",
"}",
"else",
"if",
"(",
"analyzer",
"instanceof",
"RubyGemspecAnalyzer",
")",
"{",
"(",
"(",
"RubyGemspecAnalyzer",
")",
"analyzer",
")",
".",
"setEnabled",
"(",
"false",
")",
";",
"LOGGER",
".",
"info",
"(",
"\"Disabled {} to avoid noisy duplicate results.\"",
",",
"className",
")",
";",
"failed",
"=",
"false",
";",
"}",
"}",
"if",
"(",
"failed",
")",
"{",
"LOGGER",
".",
"warn",
"(",
"\"Did not find {}.\"",
",",
"className",
")",
";",
"}",
"needToDisableGemspecAnalyzer",
"=",
"false",
";",
"}",
"final",
"File",
"parentFile",
"=",
"dependency",
".",
"getActualFile",
"(",
")",
".",
"getParentFile",
"(",
")",
";",
"final",
"Process",
"process",
"=",
"launchBundleAudit",
"(",
"parentFile",
")",
";",
"final",
"int",
"exitValue",
";",
"try",
"{",
"exitValue",
"=",
"process",
".",
"waitFor",
"(",
")",
";",
"}",
"catch",
"(",
"InterruptedException",
"ie",
")",
"{",
"Thread",
".",
"currentThread",
"(",
")",
".",
"interrupt",
"(",
")",
";",
"throw",
"new",
"AnalysisException",
"(",
"\"bundle-audit process interrupted\"",
",",
"ie",
")",
";",
"}",
"if",
"(",
"exitValue",
"<",
"0",
"||",
"exitValue",
">",
"1",
")",
"{",
"final",
"String",
"msg",
"=",
"String",
".",
"format",
"(",
"\"Unexpected exit code from bundle-audit process; exit code: %s\"",
",",
"exitValue",
")",
";",
"throw",
"new",
"AnalysisException",
"(",
"msg",
")",
";",
"}",
"try",
"{",
"try",
"(",
"BufferedReader",
"errReader",
"=",
"new",
"BufferedReader",
"(",
"new",
"InputStreamReader",
"(",
"process",
".",
"getErrorStream",
"(",
")",
",",
"StandardCharsets",
".",
"UTF_8",
")",
")",
")",
"{",
"while",
"(",
"errReader",
".",
"ready",
"(",
")",
")",
"{",
"final",
"String",
"error",
"=",
"errReader",
".",
"readLine",
"(",
")",
";",
"LOGGER",
".",
"warn",
"(",
"error",
")",
";",
"}",
"}",
"try",
"(",
"BufferedReader",
"rdr",
"=",
"new",
"BufferedReader",
"(",
"new",
"InputStreamReader",
"(",
"process",
".",
"getInputStream",
"(",
")",
",",
"StandardCharsets",
".",
"UTF_8",
")",
")",
")",
"{",
"processBundlerAuditOutput",
"(",
"dependency",
",",
"engine",
",",
"rdr",
")",
";",
"}",
"}",
"catch",
"(",
"IOException",
"|",
"CpeValidationException",
"ioe",
")",
"{",
"LOGGER",
".",
"warn",
"(",
"\"bundle-audit failure\"",
",",
"ioe",
")",
";",
"}",
"}"
] |
Determines if the analyzer can analyze the given file type.
@param dependency the dependency to determine if it can analyze
@param engine the dependency-check engine
@throws AnalysisException thrown if there is an analysis exception.
|
[
"Determines",
"if",
"the",
"analyzer",
"can",
"analyze",
"the",
"given",
"file",
"type",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/analyzer/RubyBundleAuditAnalyzer.java#L271-L318
|
17,749
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/analyzer/RubyBundleAuditAnalyzer.java
|
RubyBundleAuditAnalyzer.processBundlerAuditOutput
|
private void processBundlerAuditOutput(Dependency original, Engine engine, BufferedReader rdr) throws IOException, CpeValidationException {
final String parentName = original.getActualFile().getParentFile().getName();
final String fileName = original.getFileName();
final String filePath = original.getFilePath();
Dependency dependency = null;
Vulnerability vulnerability = null;
String gem = null;
final Map<String, Dependency> map = new HashMap<>();
boolean appendToDescription = false;
while (rdr.ready()) {
final String nextLine = rdr.readLine();
if (null == nextLine) {
break;
} else if (nextLine.startsWith(NAME)) {
appendToDescription = false;
gem = nextLine.substring(NAME.length());
if (!map.containsKey(gem)) {
map.put(gem, createDependencyForGem(engine, parentName, fileName, filePath, gem));
}
dependency = map.get(gem);
LOGGER.debug("bundle-audit ({}): {}", parentName, nextLine);
} else if (nextLine.startsWith(VERSION)) {
vulnerability = createVulnerability(parentName, dependency, gem, nextLine);
} else if (nextLine.startsWith(ADVISORY)) {
setVulnerabilityName(parentName, dependency, vulnerability, nextLine);
} else if (nextLine.startsWith(CRITICALITY)) {
addCriticalityToVulnerability(parentName, vulnerability, nextLine);
} else if (nextLine.startsWith("URL: ")) {
addReferenceToVulnerability(parentName, vulnerability, nextLine);
} else if (nextLine.startsWith("Description:")) {
appendToDescription = true;
if (null != vulnerability) {
vulnerability.setDescription("*** Vulnerability obtained from bundle-audit verbose report. "
+ "Title link may not work. CPE below is guessed. CVSS score is estimated (-1.0 "
+ " indicates unknown). See link below for full details. *** ");
}
} else if (appendToDescription && null != vulnerability) {
vulnerability.setDescription(vulnerability.getDescription() + nextLine + "\n");
}
}
}
|
java
|
private void processBundlerAuditOutput(Dependency original, Engine engine, BufferedReader rdr) throws IOException, CpeValidationException {
final String parentName = original.getActualFile().getParentFile().getName();
final String fileName = original.getFileName();
final String filePath = original.getFilePath();
Dependency dependency = null;
Vulnerability vulnerability = null;
String gem = null;
final Map<String, Dependency> map = new HashMap<>();
boolean appendToDescription = false;
while (rdr.ready()) {
final String nextLine = rdr.readLine();
if (null == nextLine) {
break;
} else if (nextLine.startsWith(NAME)) {
appendToDescription = false;
gem = nextLine.substring(NAME.length());
if (!map.containsKey(gem)) {
map.put(gem, createDependencyForGem(engine, parentName, fileName, filePath, gem));
}
dependency = map.get(gem);
LOGGER.debug("bundle-audit ({}): {}", parentName, nextLine);
} else if (nextLine.startsWith(VERSION)) {
vulnerability = createVulnerability(parentName, dependency, gem, nextLine);
} else if (nextLine.startsWith(ADVISORY)) {
setVulnerabilityName(parentName, dependency, vulnerability, nextLine);
} else if (nextLine.startsWith(CRITICALITY)) {
addCriticalityToVulnerability(parentName, vulnerability, nextLine);
} else if (nextLine.startsWith("URL: ")) {
addReferenceToVulnerability(parentName, vulnerability, nextLine);
} else if (nextLine.startsWith("Description:")) {
appendToDescription = true;
if (null != vulnerability) {
vulnerability.setDescription("*** Vulnerability obtained from bundle-audit verbose report. "
+ "Title link may not work. CPE below is guessed. CVSS score is estimated (-1.0 "
+ " indicates unknown). See link below for full details. *** ");
}
} else if (appendToDescription && null != vulnerability) {
vulnerability.setDescription(vulnerability.getDescription() + nextLine + "\n");
}
}
}
|
[
"private",
"void",
"processBundlerAuditOutput",
"(",
"Dependency",
"original",
",",
"Engine",
"engine",
",",
"BufferedReader",
"rdr",
")",
"throws",
"IOException",
",",
"CpeValidationException",
"{",
"final",
"String",
"parentName",
"=",
"original",
".",
"getActualFile",
"(",
")",
".",
"getParentFile",
"(",
")",
".",
"getName",
"(",
")",
";",
"final",
"String",
"fileName",
"=",
"original",
".",
"getFileName",
"(",
")",
";",
"final",
"String",
"filePath",
"=",
"original",
".",
"getFilePath",
"(",
")",
";",
"Dependency",
"dependency",
"=",
"null",
";",
"Vulnerability",
"vulnerability",
"=",
"null",
";",
"String",
"gem",
"=",
"null",
";",
"final",
"Map",
"<",
"String",
",",
"Dependency",
">",
"map",
"=",
"new",
"HashMap",
"<>",
"(",
")",
";",
"boolean",
"appendToDescription",
"=",
"false",
";",
"while",
"(",
"rdr",
".",
"ready",
"(",
")",
")",
"{",
"final",
"String",
"nextLine",
"=",
"rdr",
".",
"readLine",
"(",
")",
";",
"if",
"(",
"null",
"==",
"nextLine",
")",
"{",
"break",
";",
"}",
"else",
"if",
"(",
"nextLine",
".",
"startsWith",
"(",
"NAME",
")",
")",
"{",
"appendToDescription",
"=",
"false",
";",
"gem",
"=",
"nextLine",
".",
"substring",
"(",
"NAME",
".",
"length",
"(",
")",
")",
";",
"if",
"(",
"!",
"map",
".",
"containsKey",
"(",
"gem",
")",
")",
"{",
"map",
".",
"put",
"(",
"gem",
",",
"createDependencyForGem",
"(",
"engine",
",",
"parentName",
",",
"fileName",
",",
"filePath",
",",
"gem",
")",
")",
";",
"}",
"dependency",
"=",
"map",
".",
"get",
"(",
"gem",
")",
";",
"LOGGER",
".",
"debug",
"(",
"\"bundle-audit ({}): {}\"",
",",
"parentName",
",",
"nextLine",
")",
";",
"}",
"else",
"if",
"(",
"nextLine",
".",
"startsWith",
"(",
"VERSION",
")",
")",
"{",
"vulnerability",
"=",
"createVulnerability",
"(",
"parentName",
",",
"dependency",
",",
"gem",
",",
"nextLine",
")",
";",
"}",
"else",
"if",
"(",
"nextLine",
".",
"startsWith",
"(",
"ADVISORY",
")",
")",
"{",
"setVulnerabilityName",
"(",
"parentName",
",",
"dependency",
",",
"vulnerability",
",",
"nextLine",
")",
";",
"}",
"else",
"if",
"(",
"nextLine",
".",
"startsWith",
"(",
"CRITICALITY",
")",
")",
"{",
"addCriticalityToVulnerability",
"(",
"parentName",
",",
"vulnerability",
",",
"nextLine",
")",
";",
"}",
"else",
"if",
"(",
"nextLine",
".",
"startsWith",
"(",
"\"URL: \"",
")",
")",
"{",
"addReferenceToVulnerability",
"(",
"parentName",
",",
"vulnerability",
",",
"nextLine",
")",
";",
"}",
"else",
"if",
"(",
"nextLine",
".",
"startsWith",
"(",
"\"Description:\"",
")",
")",
"{",
"appendToDescription",
"=",
"true",
";",
"if",
"(",
"null",
"!=",
"vulnerability",
")",
"{",
"vulnerability",
".",
"setDescription",
"(",
"\"*** Vulnerability obtained from bundle-audit verbose report. \"",
"+",
"\"Title link may not work. CPE below is guessed. CVSS score is estimated (-1.0 \"",
"+",
"\" indicates unknown). See link below for full details. *** \"",
")",
";",
"}",
"}",
"else",
"if",
"(",
"appendToDescription",
"&&",
"null",
"!=",
"vulnerability",
")",
"{",
"vulnerability",
".",
"setDescription",
"(",
"vulnerability",
".",
"getDescription",
"(",
")",
"+",
"nextLine",
"+",
"\"\\n\"",
")",
";",
"}",
"}",
"}"
] |
Processes the bundler audit output.
@param original the dependency
@param engine the dependency-check engine
@param rdr the reader of the report
@throws IOException thrown if the report cannot be read
@throws CpeValidationException if there is an error building the
CPE/VulnerableSoftware object
|
[
"Processes",
"the",
"bundler",
"audit",
"output",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/analyzer/RubyBundleAuditAnalyzer.java#L330-L370
|
17,750
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/analyzer/RubyBundleAuditAnalyzer.java
|
RubyBundleAuditAnalyzer.setVulnerabilityName
|
private void setVulnerabilityName(String parentName, Dependency dependency, Vulnerability vulnerability, String nextLine) {
final String advisory = nextLine.substring(ADVISORY.length());
if (null != vulnerability) {
vulnerability.setName(advisory);
}
if (null != dependency) {
dependency.addVulnerability(vulnerability);
}
LOGGER.debug("bundle-audit ({}): {}", parentName, nextLine);
}
|
java
|
private void setVulnerabilityName(String parentName, Dependency dependency, Vulnerability vulnerability, String nextLine) {
final String advisory = nextLine.substring(ADVISORY.length());
if (null != vulnerability) {
vulnerability.setName(advisory);
}
if (null != dependency) {
dependency.addVulnerability(vulnerability);
}
LOGGER.debug("bundle-audit ({}): {}", parentName, nextLine);
}
|
[
"private",
"void",
"setVulnerabilityName",
"(",
"String",
"parentName",
",",
"Dependency",
"dependency",
",",
"Vulnerability",
"vulnerability",
",",
"String",
"nextLine",
")",
"{",
"final",
"String",
"advisory",
"=",
"nextLine",
".",
"substring",
"(",
"ADVISORY",
".",
"length",
"(",
")",
")",
";",
"if",
"(",
"null",
"!=",
"vulnerability",
")",
"{",
"vulnerability",
".",
"setName",
"(",
"advisory",
")",
";",
"}",
"if",
"(",
"null",
"!=",
"dependency",
")",
"{",
"dependency",
".",
"addVulnerability",
"(",
"vulnerability",
")",
";",
"}",
"LOGGER",
".",
"debug",
"(",
"\"bundle-audit ({}): {}\"",
",",
"parentName",
",",
"nextLine",
")",
";",
"}"
] |
Sets the vulnerability name.
@param parentName the parent name
@param dependency the dependency
@param vulnerability the vulnerability
@param nextLine the line to parse
|
[
"Sets",
"the",
"vulnerability",
"name",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/analyzer/RubyBundleAuditAnalyzer.java#L380-L389
|
17,751
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/analyzer/RubyBundleAuditAnalyzer.java
|
RubyBundleAuditAnalyzer.addReferenceToVulnerability
|
private void addReferenceToVulnerability(String parentName, Vulnerability vulnerability, String nextLine) {
final String url = nextLine.substring("URL: ".length());
if (null != vulnerability) {
final Reference ref = new Reference();
ref.setName(vulnerability.getName());
ref.setSource("bundle-audit");
ref.setUrl(url);
vulnerability.getReferences().add(ref);
}
LOGGER.debug("bundle-audit ({}): {}", parentName, nextLine);
}
|
java
|
private void addReferenceToVulnerability(String parentName, Vulnerability vulnerability, String nextLine) {
final String url = nextLine.substring("URL: ".length());
if (null != vulnerability) {
final Reference ref = new Reference();
ref.setName(vulnerability.getName());
ref.setSource("bundle-audit");
ref.setUrl(url);
vulnerability.getReferences().add(ref);
}
LOGGER.debug("bundle-audit ({}): {}", parentName, nextLine);
}
|
[
"private",
"void",
"addReferenceToVulnerability",
"(",
"String",
"parentName",
",",
"Vulnerability",
"vulnerability",
",",
"String",
"nextLine",
")",
"{",
"final",
"String",
"url",
"=",
"nextLine",
".",
"substring",
"(",
"\"URL: \"",
".",
"length",
"(",
")",
")",
";",
"if",
"(",
"null",
"!=",
"vulnerability",
")",
"{",
"final",
"Reference",
"ref",
"=",
"new",
"Reference",
"(",
")",
";",
"ref",
".",
"setName",
"(",
"vulnerability",
".",
"getName",
"(",
")",
")",
";",
"ref",
".",
"setSource",
"(",
"\"bundle-audit\"",
")",
";",
"ref",
".",
"setUrl",
"(",
"url",
")",
";",
"vulnerability",
".",
"getReferences",
"(",
")",
".",
"add",
"(",
"ref",
")",
";",
"}",
"LOGGER",
".",
"debug",
"(",
"\"bundle-audit ({}): {}\"",
",",
"parentName",
",",
"nextLine",
")",
";",
"}"
] |
Adds a reference to the vulnerability.
@param parentName the parent name
@param vulnerability the vulnerability
@param nextLine the line to parse
|
[
"Adds",
"a",
"reference",
"to",
"the",
"vulnerability",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/analyzer/RubyBundleAuditAnalyzer.java#L398-L408
|
17,752
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/analyzer/RubyBundleAuditAnalyzer.java
|
RubyBundleAuditAnalyzer.addCriticalityToVulnerability
|
private void addCriticalityToVulnerability(String parentName, Vulnerability vulnerability, String nextLine) {
if (null != vulnerability) {
final String criticality = nextLine.substring(CRITICALITY.length()).trim();
float score = -1.0f;
Vulnerability v = null;
if (cvedb != null) {
try {
v = cvedb.getVulnerability(vulnerability.getName());
} catch (DatabaseException ex) {
LOGGER.debug("Unable to look up vulnerability {}", vulnerability.getName());
}
}
if (v != null && (v.getCvssV2() != null || v.getCvssV3() != null)) {
if (v.getCvssV2() != null) {
vulnerability.setCvssV2(v.getCvssV2());
}
if (v.getCvssV3() != null) {
vulnerability.setCvssV3(v.getCvssV3());
}
} else {
if ("High".equalsIgnoreCase(criticality)) {
score = 8.5f;
} else if ("Medium".equalsIgnoreCase(criticality)) {
score = 5.5f;
} else if ("Low".equalsIgnoreCase(criticality)) {
score = 2.0f;
}
vulnerability.setCvssV2(new CvssV2(score, "-", "-", "-", "-", "-", "-", criticality));
}
}
LOGGER.debug("bundle-audit ({}): {}", parentName, nextLine);
}
|
java
|
private void addCriticalityToVulnerability(String parentName, Vulnerability vulnerability, String nextLine) {
if (null != vulnerability) {
final String criticality = nextLine.substring(CRITICALITY.length()).trim();
float score = -1.0f;
Vulnerability v = null;
if (cvedb != null) {
try {
v = cvedb.getVulnerability(vulnerability.getName());
} catch (DatabaseException ex) {
LOGGER.debug("Unable to look up vulnerability {}", vulnerability.getName());
}
}
if (v != null && (v.getCvssV2() != null || v.getCvssV3() != null)) {
if (v.getCvssV2() != null) {
vulnerability.setCvssV2(v.getCvssV2());
}
if (v.getCvssV3() != null) {
vulnerability.setCvssV3(v.getCvssV3());
}
} else {
if ("High".equalsIgnoreCase(criticality)) {
score = 8.5f;
} else if ("Medium".equalsIgnoreCase(criticality)) {
score = 5.5f;
} else if ("Low".equalsIgnoreCase(criticality)) {
score = 2.0f;
}
vulnerability.setCvssV2(new CvssV2(score, "-", "-", "-", "-", "-", "-", criticality));
}
}
LOGGER.debug("bundle-audit ({}): {}", parentName, nextLine);
}
|
[
"private",
"void",
"addCriticalityToVulnerability",
"(",
"String",
"parentName",
",",
"Vulnerability",
"vulnerability",
",",
"String",
"nextLine",
")",
"{",
"if",
"(",
"null",
"!=",
"vulnerability",
")",
"{",
"final",
"String",
"criticality",
"=",
"nextLine",
".",
"substring",
"(",
"CRITICALITY",
".",
"length",
"(",
")",
")",
".",
"trim",
"(",
")",
";",
"float",
"score",
"=",
"-",
"1.0f",
";",
"Vulnerability",
"v",
"=",
"null",
";",
"if",
"(",
"cvedb",
"!=",
"null",
")",
"{",
"try",
"{",
"v",
"=",
"cvedb",
".",
"getVulnerability",
"(",
"vulnerability",
".",
"getName",
"(",
")",
")",
";",
"}",
"catch",
"(",
"DatabaseException",
"ex",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"Unable to look up vulnerability {}\"",
",",
"vulnerability",
".",
"getName",
"(",
")",
")",
";",
"}",
"}",
"if",
"(",
"v",
"!=",
"null",
"&&",
"(",
"v",
".",
"getCvssV2",
"(",
")",
"!=",
"null",
"||",
"v",
".",
"getCvssV3",
"(",
")",
"!=",
"null",
")",
")",
"{",
"if",
"(",
"v",
".",
"getCvssV2",
"(",
")",
"!=",
"null",
")",
"{",
"vulnerability",
".",
"setCvssV2",
"(",
"v",
".",
"getCvssV2",
"(",
")",
")",
";",
"}",
"if",
"(",
"v",
".",
"getCvssV3",
"(",
")",
"!=",
"null",
")",
"{",
"vulnerability",
".",
"setCvssV3",
"(",
"v",
".",
"getCvssV3",
"(",
")",
")",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"\"High\"",
".",
"equalsIgnoreCase",
"(",
"criticality",
")",
")",
"{",
"score",
"=",
"8.5f",
";",
"}",
"else",
"if",
"(",
"\"Medium\"",
".",
"equalsIgnoreCase",
"(",
"criticality",
")",
")",
"{",
"score",
"=",
"5.5f",
";",
"}",
"else",
"if",
"(",
"\"Low\"",
".",
"equalsIgnoreCase",
"(",
"criticality",
")",
")",
"{",
"score",
"=",
"2.0f",
";",
"}",
"vulnerability",
".",
"setCvssV2",
"(",
"new",
"CvssV2",
"(",
"score",
",",
"\"-\"",
",",
"\"-\"",
",",
"\"-\"",
",",
"\"-\"",
",",
"\"-\"",
",",
"\"-\"",
",",
"criticality",
")",
")",
";",
"}",
"}",
"LOGGER",
".",
"debug",
"(",
"\"bundle-audit ({}): {}\"",
",",
"parentName",
",",
"nextLine",
")",
";",
"}"
] |
Adds the criticality to the vulnerability
@param parentName the parent name
@param vulnerability the vulnerability
@param nextLine the line to parse
|
[
"Adds",
"the",
"criticality",
"to",
"the",
"vulnerability"
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/analyzer/RubyBundleAuditAnalyzer.java#L417-L448
|
17,753
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/analyzer/RubyBundleAuditAnalyzer.java
|
RubyBundleAuditAnalyzer.createVulnerability
|
private Vulnerability createVulnerability(String parentName, Dependency dependency, String gem, String nextLine) throws CpeValidationException {
Vulnerability vulnerability = null;
if (null != dependency) {
final String version = nextLine.substring(VERSION.length());
dependency.addEvidence(EvidenceType.VERSION,
"bundler-audit",
"Version",
version,
Confidence.HIGHEST);
dependency.setVersion(version);
dependency.setName(gem);
try {
final PackageURL purl = PackageURLBuilder.aPackageURL().withType("gem").withName(dependency.getName())
.withVersion(dependency.getVersion()).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("gem:" + dependency.getName() + "@" + dependency.getVersion(),
Confidence.HIGHEST);
dependency.addSoftwareIdentifier(id);
}
vulnerability = new Vulnerability(); // don't add to dependency until we have name set later
final VulnerableSoftwareBuilder builder = new VulnerableSoftwareBuilder();
final VulnerableSoftware vs = builder.part(Part.APPLICATION)
.vendor(gem)
.product(String.format("%s_project", gem))
.version(version).build();
vulnerability.addVulnerableSoftware(vs);
vulnerability.setMatchedVulnerableSoftware(vs);
vulnerability.setCvssV2(new CvssV2(-1, "-", "-", "-", "-", "-", "-", "unknown"));
}
LOGGER.debug("bundle-audit ({}): {}", parentName, nextLine);
return vulnerability;
}
|
java
|
private Vulnerability createVulnerability(String parentName, Dependency dependency, String gem, String nextLine) throws CpeValidationException {
Vulnerability vulnerability = null;
if (null != dependency) {
final String version = nextLine.substring(VERSION.length());
dependency.addEvidence(EvidenceType.VERSION,
"bundler-audit",
"Version",
version,
Confidence.HIGHEST);
dependency.setVersion(version);
dependency.setName(gem);
try {
final PackageURL purl = PackageURLBuilder.aPackageURL().withType("gem").withName(dependency.getName())
.withVersion(dependency.getVersion()).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("gem:" + dependency.getName() + "@" + dependency.getVersion(),
Confidence.HIGHEST);
dependency.addSoftwareIdentifier(id);
}
vulnerability = new Vulnerability(); // don't add to dependency until we have name set later
final VulnerableSoftwareBuilder builder = new VulnerableSoftwareBuilder();
final VulnerableSoftware vs = builder.part(Part.APPLICATION)
.vendor(gem)
.product(String.format("%s_project", gem))
.version(version).build();
vulnerability.addVulnerableSoftware(vs);
vulnerability.setMatchedVulnerableSoftware(vs);
vulnerability.setCvssV2(new CvssV2(-1, "-", "-", "-", "-", "-", "-", "unknown"));
}
LOGGER.debug("bundle-audit ({}): {}", parentName, nextLine);
return vulnerability;
}
|
[
"private",
"Vulnerability",
"createVulnerability",
"(",
"String",
"parentName",
",",
"Dependency",
"dependency",
",",
"String",
"gem",
",",
"String",
"nextLine",
")",
"throws",
"CpeValidationException",
"{",
"Vulnerability",
"vulnerability",
"=",
"null",
";",
"if",
"(",
"null",
"!=",
"dependency",
")",
"{",
"final",
"String",
"version",
"=",
"nextLine",
".",
"substring",
"(",
"VERSION",
".",
"length",
"(",
")",
")",
";",
"dependency",
".",
"addEvidence",
"(",
"EvidenceType",
".",
"VERSION",
",",
"\"bundler-audit\"",
",",
"\"Version\"",
",",
"version",
",",
"Confidence",
".",
"HIGHEST",
")",
";",
"dependency",
".",
"setVersion",
"(",
"version",
")",
";",
"dependency",
".",
"setName",
"(",
"gem",
")",
";",
"try",
"{",
"final",
"PackageURL",
"purl",
"=",
"PackageURLBuilder",
".",
"aPackageURL",
"(",
")",
".",
"withType",
"(",
"\"gem\"",
")",
".",
"withName",
"(",
"dependency",
".",
"getName",
"(",
")",
")",
".",
"withVersion",
"(",
"dependency",
".",
"getVersion",
"(",
")",
")",
".",
"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",
"(",
"\"gem:\"",
"+",
"dependency",
".",
"getName",
"(",
")",
"+",
"\"@\"",
"+",
"dependency",
".",
"getVersion",
"(",
")",
",",
"Confidence",
".",
"HIGHEST",
")",
";",
"dependency",
".",
"addSoftwareIdentifier",
"(",
"id",
")",
";",
"}",
"vulnerability",
"=",
"new",
"Vulnerability",
"(",
")",
";",
"// don't add to dependency until we have name set later",
"final",
"VulnerableSoftwareBuilder",
"builder",
"=",
"new",
"VulnerableSoftwareBuilder",
"(",
")",
";",
"final",
"VulnerableSoftware",
"vs",
"=",
"builder",
".",
"part",
"(",
"Part",
".",
"APPLICATION",
")",
".",
"vendor",
"(",
"gem",
")",
".",
"product",
"(",
"String",
".",
"format",
"(",
"\"%s_project\"",
",",
"gem",
")",
")",
".",
"version",
"(",
"version",
")",
".",
"build",
"(",
")",
";",
"vulnerability",
".",
"addVulnerableSoftware",
"(",
"vs",
")",
";",
"vulnerability",
".",
"setMatchedVulnerableSoftware",
"(",
"vs",
")",
";",
"vulnerability",
".",
"setCvssV2",
"(",
"new",
"CvssV2",
"(",
"-",
"1",
",",
"\"-\"",
",",
"\"-\"",
",",
"\"-\"",
",",
"\"-\"",
",",
"\"-\"",
",",
"\"-\"",
",",
"\"unknown\"",
")",
")",
";",
"}",
"LOGGER",
".",
"debug",
"(",
"\"bundle-audit ({}): {}\"",
",",
"parentName",
",",
"nextLine",
")",
";",
"return",
"vulnerability",
";",
"}"
] |
Creates a vulnerability.
@param parentName the parent name
@param dependency the dependency
@param gem the gem name
@param nextLine the line to parse
@return the vulnerability
@throws CpeValidationException thrown if there is an error building the
CPE vulnerability object
|
[
"Creates",
"a",
"vulnerability",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/analyzer/RubyBundleAuditAnalyzer.java#L461-L495
|
17,754
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/analyzer/RubyBundleAuditAnalyzer.java
|
RubyBundleAuditAnalyzer.createDependencyForGem
|
private Dependency createDependencyForGem(Engine engine, String parentName, String fileName, String filePath, String gem) throws IOException {
final File gemFile;
try {
gemFile = File.createTempFile(gem, "_Gemfile.lock", getSettings().getTempDirectory());
} catch (IOException ioe) {
throw new IOException("Unable to create temporary gem file");
}
final String displayFileName = String.format("%s%c%s:%s", parentName, File.separatorChar, fileName, gem);
FileUtils.write(gemFile, displayFileName, Charset.defaultCharset()); // unique contents to avoid dependency bundling
final Dependency dependency = new Dependency(gemFile);
dependency.setEcosystem(DEPENDENCY_ECOSYSTEM);
dependency.addEvidence(EvidenceType.PRODUCT, "bundler-audit", "Name", gem, Confidence.HIGHEST);
//TODO add package URL - note, this may require parsing the gemfile.lock and getting the version for each entry
dependency.setDisplayFileName(displayFileName);
dependency.setFileName(fileName);
dependency.setFilePath(filePath);
engine.addDependency(dependency);
return dependency;
}
|
java
|
private Dependency createDependencyForGem(Engine engine, String parentName, String fileName, String filePath, String gem) throws IOException {
final File gemFile;
try {
gemFile = File.createTempFile(gem, "_Gemfile.lock", getSettings().getTempDirectory());
} catch (IOException ioe) {
throw new IOException("Unable to create temporary gem file");
}
final String displayFileName = String.format("%s%c%s:%s", parentName, File.separatorChar, fileName, gem);
FileUtils.write(gemFile, displayFileName, Charset.defaultCharset()); // unique contents to avoid dependency bundling
final Dependency dependency = new Dependency(gemFile);
dependency.setEcosystem(DEPENDENCY_ECOSYSTEM);
dependency.addEvidence(EvidenceType.PRODUCT, "bundler-audit", "Name", gem, Confidence.HIGHEST);
//TODO add package URL - note, this may require parsing the gemfile.lock and getting the version for each entry
dependency.setDisplayFileName(displayFileName);
dependency.setFileName(fileName);
dependency.setFilePath(filePath);
engine.addDependency(dependency);
return dependency;
}
|
[
"private",
"Dependency",
"createDependencyForGem",
"(",
"Engine",
"engine",
",",
"String",
"parentName",
",",
"String",
"fileName",
",",
"String",
"filePath",
",",
"String",
"gem",
")",
"throws",
"IOException",
"{",
"final",
"File",
"gemFile",
";",
"try",
"{",
"gemFile",
"=",
"File",
".",
"createTempFile",
"(",
"gem",
",",
"\"_Gemfile.lock\"",
",",
"getSettings",
"(",
")",
".",
"getTempDirectory",
"(",
")",
")",
";",
"}",
"catch",
"(",
"IOException",
"ioe",
")",
"{",
"throw",
"new",
"IOException",
"(",
"\"Unable to create temporary gem file\"",
")",
";",
"}",
"final",
"String",
"displayFileName",
"=",
"String",
".",
"format",
"(",
"\"%s%c%s:%s\"",
",",
"parentName",
",",
"File",
".",
"separatorChar",
",",
"fileName",
",",
"gem",
")",
";",
"FileUtils",
".",
"write",
"(",
"gemFile",
",",
"displayFileName",
",",
"Charset",
".",
"defaultCharset",
"(",
")",
")",
";",
"// unique contents to avoid dependency bundling",
"final",
"Dependency",
"dependency",
"=",
"new",
"Dependency",
"(",
"gemFile",
")",
";",
"dependency",
".",
"setEcosystem",
"(",
"DEPENDENCY_ECOSYSTEM",
")",
";",
"dependency",
".",
"addEvidence",
"(",
"EvidenceType",
".",
"PRODUCT",
",",
"\"bundler-audit\"",
",",
"\"Name\"",
",",
"gem",
",",
"Confidence",
".",
"HIGHEST",
")",
";",
"//TODO add package URL - note, this may require parsing the gemfile.lock and getting the version for each entry",
"dependency",
".",
"setDisplayFileName",
"(",
"displayFileName",
")",
";",
"dependency",
".",
"setFileName",
"(",
"fileName",
")",
";",
"dependency",
".",
"setFilePath",
"(",
"filePath",
")",
";",
"engine",
".",
"addDependency",
"(",
"dependency",
")",
";",
"return",
"dependency",
";",
"}"
] |
Creates the dependency based off of the gem.
@param engine the engine used for scanning
@param parentName the gem parent
@param fileName the file name
@param filePath the file path
@param gem the gem name
@return the dependency to add
@throws IOException thrown if a temporary gem file could not be written
|
[
"Creates",
"the",
"dependency",
"based",
"off",
"of",
"the",
"gem",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/analyzer/RubyBundleAuditAnalyzer.java#L508-L527
|
17,755
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/xml/hints/HintParser.java
|
HintParser.parseHints
|
@SuppressFBWarnings(justification = "try with resources will clean up the input stream", value = {"OBL_UNSATISFIED_OBLIGATION"})
public void parseHints(File file) throws HintParseException {
try (InputStream fis = new FileInputStream(file)) {
parseHints(fis);
} catch (SAXException | IOException ex) {
LOGGER.debug("", ex);
throw new HintParseException(ex);
}
}
|
java
|
@SuppressFBWarnings(justification = "try with resources will clean up the input stream", value = {"OBL_UNSATISFIED_OBLIGATION"})
public void parseHints(File file) throws HintParseException {
try (InputStream fis = new FileInputStream(file)) {
parseHints(fis);
} catch (SAXException | IOException ex) {
LOGGER.debug("", ex);
throw new HintParseException(ex);
}
}
|
[
"@",
"SuppressFBWarnings",
"(",
"justification",
"=",
"\"try with resources will clean up the input stream\"",
",",
"value",
"=",
"{",
"\"OBL_UNSATISFIED_OBLIGATION\"",
"}",
")",
"public",
"void",
"parseHints",
"(",
"File",
"file",
")",
"throws",
"HintParseException",
"{",
"try",
"(",
"InputStream",
"fis",
"=",
"new",
"FileInputStream",
"(",
"file",
")",
")",
"{",
"parseHints",
"(",
"fis",
")",
";",
"}",
"catch",
"(",
"SAXException",
"|",
"IOException",
"ex",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"\"",
",",
"ex",
")",
";",
"throw",
"new",
"HintParseException",
"(",
"ex",
")",
";",
"}",
"}"
] |
Parses the given XML file and returns a list of the hints contained.
@param file an XML file containing hints
@throws HintParseException thrown if the XML file cannot be parsed
|
[
"Parses",
"the",
"given",
"XML",
"file",
"and",
"returns",
"a",
"list",
"of",
"the",
"hints",
"contained",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/xml/hints/HintParser.java#L120-L128
|
17,756
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/xml/hints/HintParser.java
|
HintParser.parseHints
|
public void parseHints(InputStream inputStream) throws HintParseException, SAXException {
try (
InputStream schemaStream13 = FileUtils.getResourceAsStream(HINT_SCHEMA_1_3);
InputStream schemaStream12 = FileUtils.getResourceAsStream(HINT_SCHEMA_1_2);
InputStream schemaStream11 = FileUtils.getResourceAsStream(HINT_SCHEMA_1_1);) {
final HintHandler handler = new HintHandler();
final SAXParser saxParser = XmlUtils.buildSecureSaxParser(schemaStream13, schemaStream12, schemaStream11);
final XMLReader xmlReader = saxParser.getXMLReader();
xmlReader.setErrorHandler(new HintErrorHandler());
xmlReader.setContentHandler(handler);
try (Reader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8)) {
final InputSource in = new InputSource(reader);
xmlReader.parse(in);
this.hintRules = handler.getHintRules();
this.vendorDuplicatingHintRules = handler.getVendorDuplicatingHintRules();
}
} catch (ParserConfigurationException | FileNotFoundException ex) {
LOGGER.debug("", ex);
throw new HintParseException(ex);
} catch (SAXException ex) {
if (ex.getMessage().contains("Cannot find the declaration of element 'hints'.")) {
throw ex;
} else {
LOGGER.debug("", ex);
throw new HintParseException(ex);
}
} catch (IOException ex) {
LOGGER.debug("", ex);
throw new HintParseException(ex);
}
}
|
java
|
public void parseHints(InputStream inputStream) throws HintParseException, SAXException {
try (
InputStream schemaStream13 = FileUtils.getResourceAsStream(HINT_SCHEMA_1_3);
InputStream schemaStream12 = FileUtils.getResourceAsStream(HINT_SCHEMA_1_2);
InputStream schemaStream11 = FileUtils.getResourceAsStream(HINT_SCHEMA_1_1);) {
final HintHandler handler = new HintHandler();
final SAXParser saxParser = XmlUtils.buildSecureSaxParser(schemaStream13, schemaStream12, schemaStream11);
final XMLReader xmlReader = saxParser.getXMLReader();
xmlReader.setErrorHandler(new HintErrorHandler());
xmlReader.setContentHandler(handler);
try (Reader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8)) {
final InputSource in = new InputSource(reader);
xmlReader.parse(in);
this.hintRules = handler.getHintRules();
this.vendorDuplicatingHintRules = handler.getVendorDuplicatingHintRules();
}
} catch (ParserConfigurationException | FileNotFoundException ex) {
LOGGER.debug("", ex);
throw new HintParseException(ex);
} catch (SAXException ex) {
if (ex.getMessage().contains("Cannot find the declaration of element 'hints'.")) {
throw ex;
} else {
LOGGER.debug("", ex);
throw new HintParseException(ex);
}
} catch (IOException ex) {
LOGGER.debug("", ex);
throw new HintParseException(ex);
}
}
|
[
"public",
"void",
"parseHints",
"(",
"InputStream",
"inputStream",
")",
"throws",
"HintParseException",
",",
"SAXException",
"{",
"try",
"(",
"InputStream",
"schemaStream13",
"=",
"FileUtils",
".",
"getResourceAsStream",
"(",
"HINT_SCHEMA_1_3",
")",
";",
"InputStream",
"schemaStream12",
"=",
"FileUtils",
".",
"getResourceAsStream",
"(",
"HINT_SCHEMA_1_2",
")",
";",
"InputStream",
"schemaStream11",
"=",
"FileUtils",
".",
"getResourceAsStream",
"(",
"HINT_SCHEMA_1_1",
")",
";",
")",
"{",
"final",
"HintHandler",
"handler",
"=",
"new",
"HintHandler",
"(",
")",
";",
"final",
"SAXParser",
"saxParser",
"=",
"XmlUtils",
".",
"buildSecureSaxParser",
"(",
"schemaStream13",
",",
"schemaStream12",
",",
"schemaStream11",
")",
";",
"final",
"XMLReader",
"xmlReader",
"=",
"saxParser",
".",
"getXMLReader",
"(",
")",
";",
"xmlReader",
".",
"setErrorHandler",
"(",
"new",
"HintErrorHandler",
"(",
")",
")",
";",
"xmlReader",
".",
"setContentHandler",
"(",
"handler",
")",
";",
"try",
"(",
"Reader",
"reader",
"=",
"new",
"InputStreamReader",
"(",
"inputStream",
",",
"StandardCharsets",
".",
"UTF_8",
")",
")",
"{",
"final",
"InputSource",
"in",
"=",
"new",
"InputSource",
"(",
"reader",
")",
";",
"xmlReader",
".",
"parse",
"(",
"in",
")",
";",
"this",
".",
"hintRules",
"=",
"handler",
".",
"getHintRules",
"(",
")",
";",
"this",
".",
"vendorDuplicatingHintRules",
"=",
"handler",
".",
"getVendorDuplicatingHintRules",
"(",
")",
";",
"}",
"}",
"catch",
"(",
"ParserConfigurationException",
"|",
"FileNotFoundException",
"ex",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"\"",
",",
"ex",
")",
";",
"throw",
"new",
"HintParseException",
"(",
"ex",
")",
";",
"}",
"catch",
"(",
"SAXException",
"ex",
")",
"{",
"if",
"(",
"ex",
".",
"getMessage",
"(",
")",
".",
"contains",
"(",
"\"Cannot find the declaration of element 'hints'.\"",
")",
")",
"{",
"throw",
"ex",
";",
"}",
"else",
"{",
"LOGGER",
".",
"debug",
"(",
"\"\"",
",",
"ex",
")",
";",
"throw",
"new",
"HintParseException",
"(",
"ex",
")",
";",
"}",
"}",
"catch",
"(",
"IOException",
"ex",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"\"",
",",
"ex",
")",
";",
"throw",
"new",
"HintParseException",
"(",
"ex",
")",
";",
"}",
"}"
] |
Parses the given XML stream and returns a list of the hint rules
contained.
@param inputStream an InputStream containing hint rules
@throws HintParseException thrown if the XML cannot be parsed
@throws SAXException thrown if the XML cannot be parsed
|
[
"Parses",
"the",
"given",
"XML",
"stream",
"and",
"returns",
"a",
"list",
"of",
"the",
"hint",
"rules",
"contained",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/xml/hints/HintParser.java#L138-L168
|
17,757
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/dependency/VulnerableSoftwareBuilder.java
|
VulnerableSoftwareBuilder.reset
|
@Override
protected void reset() {
super.reset();
versionEndExcluding = null;
versionEndIncluding = null;
versionStartExcluding = null;
versionStartIncluding = null;
vulnerable = true;
}
|
java
|
@Override
protected void reset() {
super.reset();
versionEndExcluding = null;
versionEndIncluding = null;
versionStartExcluding = null;
versionStartIncluding = null;
vulnerable = true;
}
|
[
"@",
"Override",
"protected",
"void",
"reset",
"(",
")",
"{",
"super",
".",
"reset",
"(",
")",
";",
"versionEndExcluding",
"=",
"null",
";",
"versionEndIncluding",
"=",
"null",
";",
"versionStartExcluding",
"=",
"null",
";",
"versionStartIncluding",
"=",
"null",
";",
"vulnerable",
"=",
"true",
";",
"}"
] |
Resets the Vulnerable Software Builder to a clean state.
|
[
"Resets",
"the",
"Vulnerable",
"Software",
"Builder",
"to",
"a",
"clean",
"state",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/dependency/VulnerableSoftwareBuilder.java#L80-L88
|
17,758
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/dependency/VulnerableSoftwareBuilder.java
|
VulnerableSoftwareBuilder.cpe
|
public VulnerableSoftwareBuilder cpe(Cpe cpe) {
this.part(cpe.getPart()).wfVendor(cpe.getWellFormedVendor()).wfProduct(cpe.getWellFormedProduct())
.wfVersion(cpe.getWellFormedVersion()).wfUpdate(cpe.getWellFormedUpdate())
.wfEdition(cpe.getWellFormedEdition()).wfLanguage(cpe.getWellFormedLanguage())
.wfSwEdition(cpe.getWellFormedSwEdition()).wfTargetSw(cpe.getWellFormedTargetSw())
.wfTargetHw(cpe.getWellFormedTargetHw()).wfOther(cpe.getWellFormedOther());
return this;
}
|
java
|
public VulnerableSoftwareBuilder cpe(Cpe cpe) {
this.part(cpe.getPart()).wfVendor(cpe.getWellFormedVendor()).wfProduct(cpe.getWellFormedProduct())
.wfVersion(cpe.getWellFormedVersion()).wfUpdate(cpe.getWellFormedUpdate())
.wfEdition(cpe.getWellFormedEdition()).wfLanguage(cpe.getWellFormedLanguage())
.wfSwEdition(cpe.getWellFormedSwEdition()).wfTargetSw(cpe.getWellFormedTargetSw())
.wfTargetHw(cpe.getWellFormedTargetHw()).wfOther(cpe.getWellFormedOther());
return this;
}
|
[
"public",
"VulnerableSoftwareBuilder",
"cpe",
"(",
"Cpe",
"cpe",
")",
"{",
"this",
".",
"part",
"(",
"cpe",
".",
"getPart",
"(",
")",
")",
".",
"wfVendor",
"(",
"cpe",
".",
"getWellFormedVendor",
"(",
")",
")",
".",
"wfProduct",
"(",
"cpe",
".",
"getWellFormedProduct",
"(",
")",
")",
".",
"wfVersion",
"(",
"cpe",
".",
"getWellFormedVersion",
"(",
")",
")",
".",
"wfUpdate",
"(",
"cpe",
".",
"getWellFormedUpdate",
"(",
")",
")",
".",
"wfEdition",
"(",
"cpe",
".",
"getWellFormedEdition",
"(",
")",
")",
".",
"wfLanguage",
"(",
"cpe",
".",
"getWellFormedLanguage",
"(",
")",
")",
".",
"wfSwEdition",
"(",
"cpe",
".",
"getWellFormedSwEdition",
"(",
")",
")",
".",
"wfTargetSw",
"(",
"cpe",
".",
"getWellFormedTargetSw",
"(",
")",
")",
".",
"wfTargetHw",
"(",
"cpe",
".",
"getWellFormedTargetHw",
"(",
")",
")",
".",
"wfOther",
"(",
"cpe",
".",
"getWellFormedOther",
"(",
")",
")",
";",
"return",
"this",
";",
"}"
] |
Adds a base CPE object to build a vulnerable software object from.
@param cpe the base CPE
@return a reference to the builder
|
[
"Adds",
"a",
"base",
"CPE",
"object",
"to",
"build",
"a",
"vulnerable",
"software",
"object",
"from",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/dependency/VulnerableSoftwareBuilder.java#L96-L103
|
17,759
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/analyzer/AnalyzerService.java
|
AnalyzerService.getAnalyzers
|
public List<Analyzer> getAnalyzers(List<AnalysisPhase> phases) {
final List<Analyzer> analyzers = new ArrayList<>();
final Iterator<Analyzer> iterator = service.iterator();
boolean experimentalEnabled = false;
boolean retiredEnabled = false;
try {
experimentalEnabled = settings.getBoolean(Settings.KEYS.ANALYZER_EXPERIMENTAL_ENABLED, false);
retiredEnabled = settings.getBoolean(Settings.KEYS.ANALYZER_RETIRED_ENABLED, false);
} catch (InvalidSettingException ex) {
LOGGER.error("invalid experimental or retired setting", ex);
}
while (iterator.hasNext()) {
final Analyzer a = iterator.next();
if (!phases.contains(a.getAnalysisPhase())) {
continue;
}
if (!experimentalEnabled && a.getClass().isAnnotationPresent(Experimental.class)) {
continue;
}
if (!retiredEnabled && a.getClass().isAnnotationPresent(Retired.class)) {
continue;
}
LOGGER.debug("Loaded Analyzer {}", a.getName());
analyzers.add(a);
}
return analyzers;
}
|
java
|
public List<Analyzer> getAnalyzers(List<AnalysisPhase> phases) {
final List<Analyzer> analyzers = new ArrayList<>();
final Iterator<Analyzer> iterator = service.iterator();
boolean experimentalEnabled = false;
boolean retiredEnabled = false;
try {
experimentalEnabled = settings.getBoolean(Settings.KEYS.ANALYZER_EXPERIMENTAL_ENABLED, false);
retiredEnabled = settings.getBoolean(Settings.KEYS.ANALYZER_RETIRED_ENABLED, false);
} catch (InvalidSettingException ex) {
LOGGER.error("invalid experimental or retired setting", ex);
}
while (iterator.hasNext()) {
final Analyzer a = iterator.next();
if (!phases.contains(a.getAnalysisPhase())) {
continue;
}
if (!experimentalEnabled && a.getClass().isAnnotationPresent(Experimental.class)) {
continue;
}
if (!retiredEnabled && a.getClass().isAnnotationPresent(Retired.class)) {
continue;
}
LOGGER.debug("Loaded Analyzer {}", a.getName());
analyzers.add(a);
}
return analyzers;
}
|
[
"public",
"List",
"<",
"Analyzer",
">",
"getAnalyzers",
"(",
"List",
"<",
"AnalysisPhase",
">",
"phases",
")",
"{",
"final",
"List",
"<",
"Analyzer",
">",
"analyzers",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"final",
"Iterator",
"<",
"Analyzer",
">",
"iterator",
"=",
"service",
".",
"iterator",
"(",
")",
";",
"boolean",
"experimentalEnabled",
"=",
"false",
";",
"boolean",
"retiredEnabled",
"=",
"false",
";",
"try",
"{",
"experimentalEnabled",
"=",
"settings",
".",
"getBoolean",
"(",
"Settings",
".",
"KEYS",
".",
"ANALYZER_EXPERIMENTAL_ENABLED",
",",
"false",
")",
";",
"retiredEnabled",
"=",
"settings",
".",
"getBoolean",
"(",
"Settings",
".",
"KEYS",
".",
"ANALYZER_RETIRED_ENABLED",
",",
"false",
")",
";",
"}",
"catch",
"(",
"InvalidSettingException",
"ex",
")",
"{",
"LOGGER",
".",
"error",
"(",
"\"invalid experimental or retired setting\"",
",",
"ex",
")",
";",
"}",
"while",
"(",
"iterator",
".",
"hasNext",
"(",
")",
")",
"{",
"final",
"Analyzer",
"a",
"=",
"iterator",
".",
"next",
"(",
")",
";",
"if",
"(",
"!",
"phases",
".",
"contains",
"(",
"a",
".",
"getAnalysisPhase",
"(",
")",
")",
")",
"{",
"continue",
";",
"}",
"if",
"(",
"!",
"experimentalEnabled",
"&&",
"a",
".",
"getClass",
"(",
")",
".",
"isAnnotationPresent",
"(",
"Experimental",
".",
"class",
")",
")",
"{",
"continue",
";",
"}",
"if",
"(",
"!",
"retiredEnabled",
"&&",
"a",
".",
"getClass",
"(",
")",
".",
"isAnnotationPresent",
"(",
"Retired",
".",
"class",
")",
")",
"{",
"continue",
";",
"}",
"LOGGER",
".",
"debug",
"(",
"\"Loaded Analyzer {}\"",
",",
"a",
".",
"getName",
"(",
")",
")",
";",
"analyzers",
".",
"add",
"(",
"a",
")",
";",
"}",
"return",
"analyzers",
";",
"}"
] |
Returns a list of all instances of the Analyzer interface that are bound
to one of the given phases.
@param phases the phases to obtain analyzers for
@return a list of Analyzers
|
[
"Returns",
"a",
"list",
"of",
"all",
"instances",
"of",
"the",
"Analyzer",
"interface",
"that",
"are",
"bound",
"to",
"one",
"of",
"the",
"given",
"phases",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/analyzer/AnalyzerService.java#L93-L119
|
17,760
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/data/nodeaudit/NpmAuditParser.java
|
NpmAuditParser.parse
|
public List<Advisory> parse(JSONObject jsonResponse) {
LOGGER.debug("Parsing JSON node");
final List<Advisory> advisories = new ArrayList<>();
final JSONObject jsonAdvisories = jsonResponse.getJSONObject("advisories");
final Iterator<?> keys = jsonAdvisories.keys();
while (keys.hasNext()) {
final String key = (String) keys.next();
final Advisory advisory = parseAdvisory(jsonAdvisories.getJSONObject(key));
advisories.add(advisory);
}
return advisories;
}
|
java
|
public List<Advisory> parse(JSONObject jsonResponse) {
LOGGER.debug("Parsing JSON node");
final List<Advisory> advisories = new ArrayList<>();
final JSONObject jsonAdvisories = jsonResponse.getJSONObject("advisories");
final Iterator<?> keys = jsonAdvisories.keys();
while (keys.hasNext()) {
final String key = (String) keys.next();
final Advisory advisory = parseAdvisory(jsonAdvisories.getJSONObject(key));
advisories.add(advisory);
}
return advisories;
}
|
[
"public",
"List",
"<",
"Advisory",
">",
"parse",
"(",
"JSONObject",
"jsonResponse",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"Parsing JSON node\"",
")",
";",
"final",
"List",
"<",
"Advisory",
">",
"advisories",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"final",
"JSONObject",
"jsonAdvisories",
"=",
"jsonResponse",
".",
"getJSONObject",
"(",
"\"advisories\"",
")",
";",
"final",
"Iterator",
"<",
"?",
">",
"keys",
"=",
"jsonAdvisories",
".",
"keys",
"(",
")",
";",
"while",
"(",
"keys",
".",
"hasNext",
"(",
")",
")",
"{",
"final",
"String",
"key",
"=",
"(",
"String",
")",
"keys",
".",
"next",
"(",
")",
";",
"final",
"Advisory",
"advisory",
"=",
"parseAdvisory",
"(",
"jsonAdvisories",
".",
"getJSONObject",
"(",
"key",
")",
")",
";",
"advisories",
".",
"add",
"(",
"advisory",
")",
";",
"}",
"return",
"advisories",
";",
"}"
] |
Parses the JSON response from the NPM Audit API.
@param jsonResponse the JSON node to parse
@return an AdvisoryResults object
|
[
"Parses",
"the",
"JSON",
"response",
"from",
"the",
"NPM",
"Audit",
"API",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/data/nodeaudit/NpmAuditParser.java#L47-L58
|
17,761
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/data/nodeaudit/NpmAuditParser.java
|
NpmAuditParser.parseAdvisory
|
private Advisory parseAdvisory(JSONObject object) {
final Advisory advisory = new Advisory();
advisory.setId(object.getInt("id"));
advisory.setOverview(object.optString("overview", null));
advisory.setReferences(object.optString("references", null));
advisory.setCreated(object.optString("created", null));
advisory.setUpdated(object.optString("updated", null));
advisory.setRecommendation(object.optString("recommendation", null));
advisory.setTitle(object.optString("title", null));
//advisory.setFoundBy(object.optString("author", null));
//advisory.setReportedBy(object.optString("author", null));
advisory.setModuleName(object.optString("module_name", null));
advisory.setVulnerableVersions(object.optString("vulnerable_versions", null));
advisory.setPatchedVersions(object.optString("patched_versions", null));
advisory.setAccess(object.optString("access", null));
advisory.setSeverity(object.optString("severity", null));
advisory.setCwe(object.optString("cwe", null));
final JSONArray findings = object.optJSONArray("findings");
for (int i = 0; i < findings.length(); i++) {
final JSONObject finding = findings.getJSONObject(i);
final String version = finding.optString("version", null);
final JSONArray paths = finding.optJSONArray("paths");
for (int j = 0; j < paths.length(); j++) {
final String path = paths.getString(j);
if (path != null && path.equals(advisory.getModuleName())) {
advisory.setVersion(version);
}
}
}
final JSONArray jsonCves = object.optJSONArray("cves");
final List<String> stringCves = new ArrayList<>();
if (jsonCves != null) {
for (int j = 0; j < jsonCves.length(); j++) {
stringCves.add(jsonCves.getString(j));
}
advisory.setCves(stringCves);
}
return advisory;
}
|
java
|
private Advisory parseAdvisory(JSONObject object) {
final Advisory advisory = new Advisory();
advisory.setId(object.getInt("id"));
advisory.setOverview(object.optString("overview", null));
advisory.setReferences(object.optString("references", null));
advisory.setCreated(object.optString("created", null));
advisory.setUpdated(object.optString("updated", null));
advisory.setRecommendation(object.optString("recommendation", null));
advisory.setTitle(object.optString("title", null));
//advisory.setFoundBy(object.optString("author", null));
//advisory.setReportedBy(object.optString("author", null));
advisory.setModuleName(object.optString("module_name", null));
advisory.setVulnerableVersions(object.optString("vulnerable_versions", null));
advisory.setPatchedVersions(object.optString("patched_versions", null));
advisory.setAccess(object.optString("access", null));
advisory.setSeverity(object.optString("severity", null));
advisory.setCwe(object.optString("cwe", null));
final JSONArray findings = object.optJSONArray("findings");
for (int i = 0; i < findings.length(); i++) {
final JSONObject finding = findings.getJSONObject(i);
final String version = finding.optString("version", null);
final JSONArray paths = finding.optJSONArray("paths");
for (int j = 0; j < paths.length(); j++) {
final String path = paths.getString(j);
if (path != null && path.equals(advisory.getModuleName())) {
advisory.setVersion(version);
}
}
}
final JSONArray jsonCves = object.optJSONArray("cves");
final List<String> stringCves = new ArrayList<>();
if (jsonCves != null) {
for (int j = 0; j < jsonCves.length(); j++) {
stringCves.add(jsonCves.getString(j));
}
advisory.setCves(stringCves);
}
return advisory;
}
|
[
"private",
"Advisory",
"parseAdvisory",
"(",
"JSONObject",
"object",
")",
"{",
"final",
"Advisory",
"advisory",
"=",
"new",
"Advisory",
"(",
")",
";",
"advisory",
".",
"setId",
"(",
"object",
".",
"getInt",
"(",
"\"id\"",
")",
")",
";",
"advisory",
".",
"setOverview",
"(",
"object",
".",
"optString",
"(",
"\"overview\"",
",",
"null",
")",
")",
";",
"advisory",
".",
"setReferences",
"(",
"object",
".",
"optString",
"(",
"\"references\"",
",",
"null",
")",
")",
";",
"advisory",
".",
"setCreated",
"(",
"object",
".",
"optString",
"(",
"\"created\"",
",",
"null",
")",
")",
";",
"advisory",
".",
"setUpdated",
"(",
"object",
".",
"optString",
"(",
"\"updated\"",
",",
"null",
")",
")",
";",
"advisory",
".",
"setRecommendation",
"(",
"object",
".",
"optString",
"(",
"\"recommendation\"",
",",
"null",
")",
")",
";",
"advisory",
".",
"setTitle",
"(",
"object",
".",
"optString",
"(",
"\"title\"",
",",
"null",
")",
")",
";",
"//advisory.setFoundBy(object.optString(\"author\", null));",
"//advisory.setReportedBy(object.optString(\"author\", null));",
"advisory",
".",
"setModuleName",
"(",
"object",
".",
"optString",
"(",
"\"module_name\"",
",",
"null",
")",
")",
";",
"advisory",
".",
"setVulnerableVersions",
"(",
"object",
".",
"optString",
"(",
"\"vulnerable_versions\"",
",",
"null",
")",
")",
";",
"advisory",
".",
"setPatchedVersions",
"(",
"object",
".",
"optString",
"(",
"\"patched_versions\"",
",",
"null",
")",
")",
";",
"advisory",
".",
"setAccess",
"(",
"object",
".",
"optString",
"(",
"\"access\"",
",",
"null",
")",
")",
";",
"advisory",
".",
"setSeverity",
"(",
"object",
".",
"optString",
"(",
"\"severity\"",
",",
"null",
")",
")",
";",
"advisory",
".",
"setCwe",
"(",
"object",
".",
"optString",
"(",
"\"cwe\"",
",",
"null",
")",
")",
";",
"final",
"JSONArray",
"findings",
"=",
"object",
".",
"optJSONArray",
"(",
"\"findings\"",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"findings",
".",
"length",
"(",
")",
";",
"i",
"++",
")",
"{",
"final",
"JSONObject",
"finding",
"=",
"findings",
".",
"getJSONObject",
"(",
"i",
")",
";",
"final",
"String",
"version",
"=",
"finding",
".",
"optString",
"(",
"\"version\"",
",",
"null",
")",
";",
"final",
"JSONArray",
"paths",
"=",
"finding",
".",
"optJSONArray",
"(",
"\"paths\"",
")",
";",
"for",
"(",
"int",
"j",
"=",
"0",
";",
"j",
"<",
"paths",
".",
"length",
"(",
")",
";",
"j",
"++",
")",
"{",
"final",
"String",
"path",
"=",
"paths",
".",
"getString",
"(",
"j",
")",
";",
"if",
"(",
"path",
"!=",
"null",
"&&",
"path",
".",
"equals",
"(",
"advisory",
".",
"getModuleName",
"(",
")",
")",
")",
"{",
"advisory",
".",
"setVersion",
"(",
"version",
")",
";",
"}",
"}",
"}",
"final",
"JSONArray",
"jsonCves",
"=",
"object",
".",
"optJSONArray",
"(",
"\"cves\"",
")",
";",
"final",
"List",
"<",
"String",
">",
"stringCves",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"if",
"(",
"jsonCves",
"!=",
"null",
")",
"{",
"for",
"(",
"int",
"j",
"=",
"0",
";",
"j",
"<",
"jsonCves",
".",
"length",
"(",
")",
";",
"j",
"++",
")",
"{",
"stringCves",
".",
"add",
"(",
"jsonCves",
".",
"getString",
"(",
"j",
")",
")",
";",
"}",
"advisory",
".",
"setCves",
"(",
"stringCves",
")",
";",
"}",
"return",
"advisory",
";",
"}"
] |
Parses the advisory from Node Audit.
@param object the JSON object containing the advisory
@return the Advisory object
|
[
"Parses",
"the",
"advisory",
"from",
"Node",
"Audit",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/data/nodeaudit/NpmAuditParser.java#L66-L106
|
17,762
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/utils/DependencyVersion.java
|
DependencyVersion.matchesAtLeastThreeLevels
|
public boolean matchesAtLeastThreeLevels(DependencyVersion version) {
if (version == null) {
return false;
}
if (Math.abs(this.versionParts.size() - version.versionParts.size()) >= 3) {
return false;
}
final int max = (this.versionParts.size() < version.versionParts.size())
? this.versionParts.size() : version.versionParts.size();
boolean ret = true;
for (int i = 0; i < max; i++) {
final String thisVersion = this.versionParts.get(i);
final String otherVersion = version.getVersionParts().get(i);
if (i >= 3) {
if (thisVersion.compareToIgnoreCase(otherVersion) >= 0) {
ret = false;
break;
}
} else if (!thisVersion.equals(otherVersion)) {
ret = false;
break;
}
}
return ret;
}
|
java
|
public boolean matchesAtLeastThreeLevels(DependencyVersion version) {
if (version == null) {
return false;
}
if (Math.abs(this.versionParts.size() - version.versionParts.size()) >= 3) {
return false;
}
final int max = (this.versionParts.size() < version.versionParts.size())
? this.versionParts.size() : version.versionParts.size();
boolean ret = true;
for (int i = 0; i < max; i++) {
final String thisVersion = this.versionParts.get(i);
final String otherVersion = version.getVersionParts().get(i);
if (i >= 3) {
if (thisVersion.compareToIgnoreCase(otherVersion) >= 0) {
ret = false;
break;
}
} else if (!thisVersion.equals(otherVersion)) {
ret = false;
break;
}
}
return ret;
}
|
[
"public",
"boolean",
"matchesAtLeastThreeLevels",
"(",
"DependencyVersion",
"version",
")",
"{",
"if",
"(",
"version",
"==",
"null",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"Math",
".",
"abs",
"(",
"this",
".",
"versionParts",
".",
"size",
"(",
")",
"-",
"version",
".",
"versionParts",
".",
"size",
"(",
")",
")",
">=",
"3",
")",
"{",
"return",
"false",
";",
"}",
"final",
"int",
"max",
"=",
"(",
"this",
".",
"versionParts",
".",
"size",
"(",
")",
"<",
"version",
".",
"versionParts",
".",
"size",
"(",
")",
")",
"?",
"this",
".",
"versionParts",
".",
"size",
"(",
")",
":",
"version",
".",
"versionParts",
".",
"size",
"(",
")",
";",
"boolean",
"ret",
"=",
"true",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"max",
";",
"i",
"++",
")",
"{",
"final",
"String",
"thisVersion",
"=",
"this",
".",
"versionParts",
".",
"get",
"(",
"i",
")",
";",
"final",
"String",
"otherVersion",
"=",
"version",
".",
"getVersionParts",
"(",
")",
".",
"get",
"(",
"i",
")",
";",
"if",
"(",
"i",
">=",
"3",
")",
"{",
"if",
"(",
"thisVersion",
".",
"compareToIgnoreCase",
"(",
"otherVersion",
")",
">=",
"0",
")",
"{",
"ret",
"=",
"false",
";",
"break",
";",
"}",
"}",
"else",
"if",
"(",
"!",
"thisVersion",
".",
"equals",
"(",
"otherVersion",
")",
")",
"{",
"ret",
"=",
"false",
";",
"break",
";",
"}",
"}",
"return",
"ret",
";",
"}"
] |
Determines if the three most major major version parts are identical. For
instances, if version 1.2.3.4 was compared to 1.2.3 this function would
return true.
@param version the version number to compare
@return true if the first three major parts of the version are identical
|
[
"Determines",
"if",
"the",
"three",
"most",
"major",
"major",
"version",
"parts",
"are",
"identical",
".",
"For",
"instances",
"if",
"version",
"1",
".",
"2",
".",
"3",
".",
"4",
"was",
"compared",
"to",
"1",
".",
"2",
".",
"3",
"this",
"function",
"would",
"return",
"true",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/utils/DependencyVersion.java#L203-L230
|
17,763
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/xml/suppression/SuppressionParser.java
|
SuppressionParser.parseSuppressionRules
|
@SuppressFBWarnings(justification = "try with resource will clenaup the resources", value = {"OBL_UNSATISFIED_OBLIGATION"})
public List<SuppressionRule> parseSuppressionRules(File file) throws SuppressionParseException {
try (FileInputStream fis = new FileInputStream(file)) {
return parseSuppressionRules(fis);
} catch (SAXException | IOException ex) {
LOGGER.debug("", ex);
throw new SuppressionParseException(ex);
}
}
|
java
|
@SuppressFBWarnings(justification = "try with resource will clenaup the resources", value = {"OBL_UNSATISFIED_OBLIGATION"})
public List<SuppressionRule> parseSuppressionRules(File file) throws SuppressionParseException {
try (FileInputStream fis = new FileInputStream(file)) {
return parseSuppressionRules(fis);
} catch (SAXException | IOException ex) {
LOGGER.debug("", ex);
throw new SuppressionParseException(ex);
}
}
|
[
"@",
"SuppressFBWarnings",
"(",
"justification",
"=",
"\"try with resource will clenaup the resources\"",
",",
"value",
"=",
"{",
"\"OBL_UNSATISFIED_OBLIGATION\"",
"}",
")",
"public",
"List",
"<",
"SuppressionRule",
">",
"parseSuppressionRules",
"(",
"File",
"file",
")",
"throws",
"SuppressionParseException",
"{",
"try",
"(",
"FileInputStream",
"fis",
"=",
"new",
"FileInputStream",
"(",
"file",
")",
")",
"{",
"return",
"parseSuppressionRules",
"(",
"fis",
")",
";",
"}",
"catch",
"(",
"SAXException",
"|",
"IOException",
"ex",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"\"",
",",
"ex",
")",
";",
"throw",
"new",
"SuppressionParseException",
"(",
"ex",
")",
";",
"}",
"}"
] |
Parses the given XML file and returns a list of the suppression rules
contained.
@param file an XML file containing suppression rules
@return a list of suppression rules
@throws SuppressionParseException thrown if the XML file cannot be parsed
|
[
"Parses",
"the",
"given",
"XML",
"file",
"and",
"returns",
"a",
"list",
"of",
"the",
"suppression",
"rules",
"contained",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/xml/suppression/SuppressionParser.java#L76-L84
|
17,764
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/xml/suppression/SuppressionParser.java
|
SuppressionParser.parseSuppressionRules
|
public List<SuppressionRule> parseSuppressionRules(InputStream inputStream) throws SuppressionParseException, SAXException {
try (
InputStream schemaStream12 = FileUtils.getResourceAsStream(SUPPRESSION_SCHEMA_1_2);
InputStream schemaStream11 = FileUtils.getResourceAsStream(SUPPRESSION_SCHEMA_1_1);
InputStream schemaStream10 = FileUtils.getResourceAsStream(SUPPRESSION_SCHEMA_1_0);) {
final SuppressionHandler handler = new SuppressionHandler();
final SAXParser saxParser = XmlUtils.buildSecureSaxParser(schemaStream12, schemaStream11, schemaStream10);
final XMLReader xmlReader = saxParser.getXMLReader();
xmlReader.setErrorHandler(new SuppressionErrorHandler());
xmlReader.setContentHandler(handler);
try (Reader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8)) {
final InputSource in = new InputSource(reader);
xmlReader.parse(in);
return handler.getSuppressionRules();
}
} catch (ParserConfigurationException | FileNotFoundException ex) {
LOGGER.debug("", ex);
throw new SuppressionParseException(ex);
} catch (SAXException ex) {
if (ex.getMessage().contains("Cannot find the declaration of element 'suppressions'.")) {
throw ex;
} else {
LOGGER.debug("", ex);
throw new SuppressionParseException(ex);
}
} catch (IOException ex) {
LOGGER.debug("", ex);
throw new SuppressionParseException(ex);
}
}
|
java
|
public List<SuppressionRule> parseSuppressionRules(InputStream inputStream) throws SuppressionParseException, SAXException {
try (
InputStream schemaStream12 = FileUtils.getResourceAsStream(SUPPRESSION_SCHEMA_1_2);
InputStream schemaStream11 = FileUtils.getResourceAsStream(SUPPRESSION_SCHEMA_1_1);
InputStream schemaStream10 = FileUtils.getResourceAsStream(SUPPRESSION_SCHEMA_1_0);) {
final SuppressionHandler handler = new SuppressionHandler();
final SAXParser saxParser = XmlUtils.buildSecureSaxParser(schemaStream12, schemaStream11, schemaStream10);
final XMLReader xmlReader = saxParser.getXMLReader();
xmlReader.setErrorHandler(new SuppressionErrorHandler());
xmlReader.setContentHandler(handler);
try (Reader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8)) {
final InputSource in = new InputSource(reader);
xmlReader.parse(in);
return handler.getSuppressionRules();
}
} catch (ParserConfigurationException | FileNotFoundException ex) {
LOGGER.debug("", ex);
throw new SuppressionParseException(ex);
} catch (SAXException ex) {
if (ex.getMessage().contains("Cannot find the declaration of element 'suppressions'.")) {
throw ex;
} else {
LOGGER.debug("", ex);
throw new SuppressionParseException(ex);
}
} catch (IOException ex) {
LOGGER.debug("", ex);
throw new SuppressionParseException(ex);
}
}
|
[
"public",
"List",
"<",
"SuppressionRule",
">",
"parseSuppressionRules",
"(",
"InputStream",
"inputStream",
")",
"throws",
"SuppressionParseException",
",",
"SAXException",
"{",
"try",
"(",
"InputStream",
"schemaStream12",
"=",
"FileUtils",
".",
"getResourceAsStream",
"(",
"SUPPRESSION_SCHEMA_1_2",
")",
";",
"InputStream",
"schemaStream11",
"=",
"FileUtils",
".",
"getResourceAsStream",
"(",
"SUPPRESSION_SCHEMA_1_1",
")",
";",
"InputStream",
"schemaStream10",
"=",
"FileUtils",
".",
"getResourceAsStream",
"(",
"SUPPRESSION_SCHEMA_1_0",
")",
";",
")",
"{",
"final",
"SuppressionHandler",
"handler",
"=",
"new",
"SuppressionHandler",
"(",
")",
";",
"final",
"SAXParser",
"saxParser",
"=",
"XmlUtils",
".",
"buildSecureSaxParser",
"(",
"schemaStream12",
",",
"schemaStream11",
",",
"schemaStream10",
")",
";",
"final",
"XMLReader",
"xmlReader",
"=",
"saxParser",
".",
"getXMLReader",
"(",
")",
";",
"xmlReader",
".",
"setErrorHandler",
"(",
"new",
"SuppressionErrorHandler",
"(",
")",
")",
";",
"xmlReader",
".",
"setContentHandler",
"(",
"handler",
")",
";",
"try",
"(",
"Reader",
"reader",
"=",
"new",
"InputStreamReader",
"(",
"inputStream",
",",
"StandardCharsets",
".",
"UTF_8",
")",
")",
"{",
"final",
"InputSource",
"in",
"=",
"new",
"InputSource",
"(",
"reader",
")",
";",
"xmlReader",
".",
"parse",
"(",
"in",
")",
";",
"return",
"handler",
".",
"getSuppressionRules",
"(",
")",
";",
"}",
"}",
"catch",
"(",
"ParserConfigurationException",
"|",
"FileNotFoundException",
"ex",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"\"",
",",
"ex",
")",
";",
"throw",
"new",
"SuppressionParseException",
"(",
"ex",
")",
";",
"}",
"catch",
"(",
"SAXException",
"ex",
")",
"{",
"if",
"(",
"ex",
".",
"getMessage",
"(",
")",
".",
"contains",
"(",
"\"Cannot find the declaration of element 'suppressions'.\"",
")",
")",
"{",
"throw",
"ex",
";",
"}",
"else",
"{",
"LOGGER",
".",
"debug",
"(",
"\"\"",
",",
"ex",
")",
";",
"throw",
"new",
"SuppressionParseException",
"(",
"ex",
")",
";",
"}",
"}",
"catch",
"(",
"IOException",
"ex",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"\"",
",",
"ex",
")",
";",
"throw",
"new",
"SuppressionParseException",
"(",
"ex",
")",
";",
"}",
"}"
] |
Parses the given XML stream and returns a list of the suppression rules
contained.
@param inputStream an InputStream containing suppression rules
@return a list of suppression rules
@throws SuppressionParseException thrown if the XML cannot be parsed
@throws SAXException thrown if the XML cannot be parsed
|
[
"Parses",
"the",
"given",
"XML",
"stream",
"and",
"returns",
"a",
"list",
"of",
"the",
"suppression",
"rules",
"contained",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/xml/suppression/SuppressionParser.java#L95-L124
|
17,765
|
jeremylong/DependencyCheck
|
utils/src/main/java/org/owasp/dependencycheck/utils/HttpResourceConnection.java
|
HttpResourceConnection.fetch
|
public InputStream fetch(URL url) throws DownloadFailedException {
if ("file".equalsIgnoreCase(url.getProtocol())) {
final File file;
try {
file = new File(url.toURI());
} catch (URISyntaxException ex) {
final String msg = format("Download failed, unable to locate '%s'", url.toString());
throw new DownloadFailedException(msg);
}
if (file.exists()) {
try {
return new FileInputStream(file);
} catch (IOException ex) {
final String msg = format("Download failed, unable to rerieve '%s'", url.toString());
throw new DownloadFailedException(msg, ex);
}
} else {
final String msg = format("Download failed, file ('%s') does not exist", url.toString());
throw new DownloadFailedException(msg);
}
} else {
if (connection != null) {
LOGGER.warn("HTTP URL Connection was not properly closed");
connection.disconnect();
connection = null;
}
connection = obtainConnection(url);
final String encoding = connection.getContentEncoding();
try {
if (encoding != null && "gzip".equalsIgnoreCase(encoding)) {
return new GZIPInputStream(connection.getInputStream());
} else if (encoding != null && "deflate".equalsIgnoreCase(encoding)) {
return new InflaterInputStream(connection.getInputStream());
} else {
return connection.getInputStream();
}
} catch (IOException ex) {
checkForCommonExceptionTypes(ex);
final String msg = format("Error retrieving '%s'%nConnection Timeout: %d%nEncoding: %s%n",
url.toString(), connection.getConnectTimeout(), encoding);
throw new DownloadFailedException(msg, ex);
} catch (Exception ex) {
final String msg = format("Unexpected exception retrieving '%s'%nConnection Timeout: %d%nEncoding: %s%n",
url.toString(), connection.getConnectTimeout(), encoding);
throw new DownloadFailedException(msg, ex);
}
}
}
|
java
|
public InputStream fetch(URL url) throws DownloadFailedException {
if ("file".equalsIgnoreCase(url.getProtocol())) {
final File file;
try {
file = new File(url.toURI());
} catch (URISyntaxException ex) {
final String msg = format("Download failed, unable to locate '%s'", url.toString());
throw new DownloadFailedException(msg);
}
if (file.exists()) {
try {
return new FileInputStream(file);
} catch (IOException ex) {
final String msg = format("Download failed, unable to rerieve '%s'", url.toString());
throw new DownloadFailedException(msg, ex);
}
} else {
final String msg = format("Download failed, file ('%s') does not exist", url.toString());
throw new DownloadFailedException(msg);
}
} else {
if (connection != null) {
LOGGER.warn("HTTP URL Connection was not properly closed");
connection.disconnect();
connection = null;
}
connection = obtainConnection(url);
final String encoding = connection.getContentEncoding();
try {
if (encoding != null && "gzip".equalsIgnoreCase(encoding)) {
return new GZIPInputStream(connection.getInputStream());
} else if (encoding != null && "deflate".equalsIgnoreCase(encoding)) {
return new InflaterInputStream(connection.getInputStream());
} else {
return connection.getInputStream();
}
} catch (IOException ex) {
checkForCommonExceptionTypes(ex);
final String msg = format("Error retrieving '%s'%nConnection Timeout: %d%nEncoding: %s%n",
url.toString(), connection.getConnectTimeout(), encoding);
throw new DownloadFailedException(msg, ex);
} catch (Exception ex) {
final String msg = format("Unexpected exception retrieving '%s'%nConnection Timeout: %d%nEncoding: %s%n",
url.toString(), connection.getConnectTimeout(), encoding);
throw new DownloadFailedException(msg, ex);
}
}
}
|
[
"public",
"InputStream",
"fetch",
"(",
"URL",
"url",
")",
"throws",
"DownloadFailedException",
"{",
"if",
"(",
"\"file\"",
".",
"equalsIgnoreCase",
"(",
"url",
".",
"getProtocol",
"(",
")",
")",
")",
"{",
"final",
"File",
"file",
";",
"try",
"{",
"file",
"=",
"new",
"File",
"(",
"url",
".",
"toURI",
"(",
")",
")",
";",
"}",
"catch",
"(",
"URISyntaxException",
"ex",
")",
"{",
"final",
"String",
"msg",
"=",
"format",
"(",
"\"Download failed, unable to locate '%s'\"",
",",
"url",
".",
"toString",
"(",
")",
")",
";",
"throw",
"new",
"DownloadFailedException",
"(",
"msg",
")",
";",
"}",
"if",
"(",
"file",
".",
"exists",
"(",
")",
")",
"{",
"try",
"{",
"return",
"new",
"FileInputStream",
"(",
"file",
")",
";",
"}",
"catch",
"(",
"IOException",
"ex",
")",
"{",
"final",
"String",
"msg",
"=",
"format",
"(",
"\"Download failed, unable to rerieve '%s'\"",
",",
"url",
".",
"toString",
"(",
")",
")",
";",
"throw",
"new",
"DownloadFailedException",
"(",
"msg",
",",
"ex",
")",
";",
"}",
"}",
"else",
"{",
"final",
"String",
"msg",
"=",
"format",
"(",
"\"Download failed, file ('%s') does not exist\"",
",",
"url",
".",
"toString",
"(",
")",
")",
";",
"throw",
"new",
"DownloadFailedException",
"(",
"msg",
")",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"connection",
"!=",
"null",
")",
"{",
"LOGGER",
".",
"warn",
"(",
"\"HTTP URL Connection was not properly closed\"",
")",
";",
"connection",
".",
"disconnect",
"(",
")",
";",
"connection",
"=",
"null",
";",
"}",
"connection",
"=",
"obtainConnection",
"(",
"url",
")",
";",
"final",
"String",
"encoding",
"=",
"connection",
".",
"getContentEncoding",
"(",
")",
";",
"try",
"{",
"if",
"(",
"encoding",
"!=",
"null",
"&&",
"\"gzip\"",
".",
"equalsIgnoreCase",
"(",
"encoding",
")",
")",
"{",
"return",
"new",
"GZIPInputStream",
"(",
"connection",
".",
"getInputStream",
"(",
")",
")",
";",
"}",
"else",
"if",
"(",
"encoding",
"!=",
"null",
"&&",
"\"deflate\"",
".",
"equalsIgnoreCase",
"(",
"encoding",
")",
")",
"{",
"return",
"new",
"InflaterInputStream",
"(",
"connection",
".",
"getInputStream",
"(",
")",
")",
";",
"}",
"else",
"{",
"return",
"connection",
".",
"getInputStream",
"(",
")",
";",
"}",
"}",
"catch",
"(",
"IOException",
"ex",
")",
"{",
"checkForCommonExceptionTypes",
"(",
"ex",
")",
";",
"final",
"String",
"msg",
"=",
"format",
"(",
"\"Error retrieving '%s'%nConnection Timeout: %d%nEncoding: %s%n\"",
",",
"url",
".",
"toString",
"(",
")",
",",
"connection",
".",
"getConnectTimeout",
"(",
")",
",",
"encoding",
")",
";",
"throw",
"new",
"DownloadFailedException",
"(",
"msg",
",",
"ex",
")",
";",
"}",
"catch",
"(",
"Exception",
"ex",
")",
"{",
"final",
"String",
"msg",
"=",
"format",
"(",
"\"Unexpected exception retrieving '%s'%nConnection Timeout: %d%nEncoding: %s%n\"",
",",
"url",
".",
"toString",
"(",
")",
",",
"connection",
".",
"getConnectTimeout",
"(",
")",
",",
"encoding",
")",
";",
"throw",
"new",
"DownloadFailedException",
"(",
"msg",
",",
"ex",
")",
";",
"}",
"}",
"}"
] |
Retrieves the resource identified by the given URL and returns the
InputStream.
@param url the URL of the resource to download
@return the stream to read the retrieved content from
@throws org.owasp.dependencycheck.utils.DownloadFailedException is thrown
if there is an error downloading the resource
|
[
"Retrieves",
"the",
"resource",
"identified",
"by",
"the",
"given",
"URL",
"and",
"returns",
"the",
"InputStream",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/utils/src/main/java/org/owasp/dependencycheck/utils/HttpResourceConnection.java#L108-L156
|
17,766
|
jeremylong/DependencyCheck
|
utils/src/main/java/org/owasp/dependencycheck/utils/HttpResourceConnection.java
|
HttpResourceConnection.obtainConnection
|
private HttpURLConnection obtainConnection(URL url) throws DownloadFailedException {
HttpURLConnection conn = null;
try {
LOGGER.debug("Attempting retrieval of {}", url.toString());
conn = connFactory.createHttpURLConnection(url, this.usesProxy);
conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
conn.connect();
int status = conn.getResponseCode();
int redirectCount = 0;
// TODO - should this get replaced by using the conn.setInstanceFollowRedirects(true);
while ((status == HttpURLConnection.HTTP_MOVED_TEMP
|| status == HttpURLConnection.HTTP_MOVED_PERM
|| status == HttpURLConnection.HTTP_SEE_OTHER)
&& MAX_REDIRECT_ATTEMPTS > redirectCount++) {
final String location = conn.getHeaderField("Location");
try {
conn.disconnect();
} finally {
conn = null;
}
LOGGER.debug("Download is being redirected from {} to {}", url.toString(), location);
conn = connFactory.createHttpURLConnection(new URL(location), this.usesProxy);
conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
conn.connect();
status = conn.getResponseCode();
}
if (status != 200) {
try {
conn.disconnect();
} finally {
conn = null;
}
final String msg = format("Error retrieving %s; received response code %s.", url.toString(), status);
LOGGER.error(msg);
throw new DownloadFailedException(msg);
}
} catch (IOException ex) {
try {
if (conn != null) {
conn.disconnect();
}
} finally {
conn = null;
}
if ("Connection reset".equalsIgnoreCase(ex.getMessage())) {
final String msg = format("TLS Connection Reset%nPlease see "
+ "http://jeremylong.github.io/DependencyCheck/data/tlsfailure.html "
+ "for more information regarding how to resolve the issue.");
LOGGER.error(msg);
throw new DownloadFailedException(msg, ex);
}
final String msg = format("Error downloading file %s; unable to connect.", url.toString());
throw new DownloadFailedException(msg, ex);
}
return conn;
}
|
java
|
private HttpURLConnection obtainConnection(URL url) throws DownloadFailedException {
HttpURLConnection conn = null;
try {
LOGGER.debug("Attempting retrieval of {}", url.toString());
conn = connFactory.createHttpURLConnection(url, this.usesProxy);
conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
conn.connect();
int status = conn.getResponseCode();
int redirectCount = 0;
// TODO - should this get replaced by using the conn.setInstanceFollowRedirects(true);
while ((status == HttpURLConnection.HTTP_MOVED_TEMP
|| status == HttpURLConnection.HTTP_MOVED_PERM
|| status == HttpURLConnection.HTTP_SEE_OTHER)
&& MAX_REDIRECT_ATTEMPTS > redirectCount++) {
final String location = conn.getHeaderField("Location");
try {
conn.disconnect();
} finally {
conn = null;
}
LOGGER.debug("Download is being redirected from {} to {}", url.toString(), location);
conn = connFactory.createHttpURLConnection(new URL(location), this.usesProxy);
conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
conn.connect();
status = conn.getResponseCode();
}
if (status != 200) {
try {
conn.disconnect();
} finally {
conn = null;
}
final String msg = format("Error retrieving %s; received response code %s.", url.toString(), status);
LOGGER.error(msg);
throw new DownloadFailedException(msg);
}
} catch (IOException ex) {
try {
if (conn != null) {
conn.disconnect();
}
} finally {
conn = null;
}
if ("Connection reset".equalsIgnoreCase(ex.getMessage())) {
final String msg = format("TLS Connection Reset%nPlease see "
+ "http://jeremylong.github.io/DependencyCheck/data/tlsfailure.html "
+ "for more information regarding how to resolve the issue.");
LOGGER.error(msg);
throw new DownloadFailedException(msg, ex);
}
final String msg = format("Error downloading file %s; unable to connect.", url.toString());
throw new DownloadFailedException(msg, ex);
}
return conn;
}
|
[
"private",
"HttpURLConnection",
"obtainConnection",
"(",
"URL",
"url",
")",
"throws",
"DownloadFailedException",
"{",
"HttpURLConnection",
"conn",
"=",
"null",
";",
"try",
"{",
"LOGGER",
".",
"debug",
"(",
"\"Attempting retrieval of {}\"",
",",
"url",
".",
"toString",
"(",
")",
")",
";",
"conn",
"=",
"connFactory",
".",
"createHttpURLConnection",
"(",
"url",
",",
"this",
".",
"usesProxy",
")",
";",
"conn",
".",
"setRequestProperty",
"(",
"\"Accept-Encoding\"",
",",
"\"gzip, deflate\"",
")",
";",
"conn",
".",
"connect",
"(",
")",
";",
"int",
"status",
"=",
"conn",
".",
"getResponseCode",
"(",
")",
";",
"int",
"redirectCount",
"=",
"0",
";",
"// TODO - should this get replaced by using the conn.setInstanceFollowRedirects(true);",
"while",
"(",
"(",
"status",
"==",
"HttpURLConnection",
".",
"HTTP_MOVED_TEMP",
"||",
"status",
"==",
"HttpURLConnection",
".",
"HTTP_MOVED_PERM",
"||",
"status",
"==",
"HttpURLConnection",
".",
"HTTP_SEE_OTHER",
")",
"&&",
"MAX_REDIRECT_ATTEMPTS",
">",
"redirectCount",
"++",
")",
"{",
"final",
"String",
"location",
"=",
"conn",
".",
"getHeaderField",
"(",
"\"Location\"",
")",
";",
"try",
"{",
"conn",
".",
"disconnect",
"(",
")",
";",
"}",
"finally",
"{",
"conn",
"=",
"null",
";",
"}",
"LOGGER",
".",
"debug",
"(",
"\"Download is being redirected from {} to {}\"",
",",
"url",
".",
"toString",
"(",
")",
",",
"location",
")",
";",
"conn",
"=",
"connFactory",
".",
"createHttpURLConnection",
"(",
"new",
"URL",
"(",
"location",
")",
",",
"this",
".",
"usesProxy",
")",
";",
"conn",
".",
"setRequestProperty",
"(",
"\"Accept-Encoding\"",
",",
"\"gzip, deflate\"",
")",
";",
"conn",
".",
"connect",
"(",
")",
";",
"status",
"=",
"conn",
".",
"getResponseCode",
"(",
")",
";",
"}",
"if",
"(",
"status",
"!=",
"200",
")",
"{",
"try",
"{",
"conn",
".",
"disconnect",
"(",
")",
";",
"}",
"finally",
"{",
"conn",
"=",
"null",
";",
"}",
"final",
"String",
"msg",
"=",
"format",
"(",
"\"Error retrieving %s; received response code %s.\"",
",",
"url",
".",
"toString",
"(",
")",
",",
"status",
")",
";",
"LOGGER",
".",
"error",
"(",
"msg",
")",
";",
"throw",
"new",
"DownloadFailedException",
"(",
"msg",
")",
";",
"}",
"}",
"catch",
"(",
"IOException",
"ex",
")",
"{",
"try",
"{",
"if",
"(",
"conn",
"!=",
"null",
")",
"{",
"conn",
".",
"disconnect",
"(",
")",
";",
"}",
"}",
"finally",
"{",
"conn",
"=",
"null",
";",
"}",
"if",
"(",
"\"Connection reset\"",
".",
"equalsIgnoreCase",
"(",
"ex",
".",
"getMessage",
"(",
")",
")",
")",
"{",
"final",
"String",
"msg",
"=",
"format",
"(",
"\"TLS Connection Reset%nPlease see \"",
"+",
"\"http://jeremylong.github.io/DependencyCheck/data/tlsfailure.html \"",
"+",
"\"for more information regarding how to resolve the issue.\"",
")",
";",
"LOGGER",
".",
"error",
"(",
"msg",
")",
";",
"throw",
"new",
"DownloadFailedException",
"(",
"msg",
",",
"ex",
")",
";",
"}",
"final",
"String",
"msg",
"=",
"format",
"(",
"\"Error downloading file %s; unable to connect.\"",
",",
"url",
".",
"toString",
"(",
")",
")",
";",
"throw",
"new",
"DownloadFailedException",
"(",
"msg",
",",
"ex",
")",
";",
"}",
"return",
"conn",
";",
"}"
] |
Obtains the HTTP URL Connection.
@param url the URL
@return the HTTP URL Connection
@throws DownloadFailedException thrown if there is an error creating the
HTTP URL Connection
|
[
"Obtains",
"the",
"HTTP",
"URL",
"Connection",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/utils/src/main/java/org/owasp/dependencycheck/utils/HttpResourceConnection.java#L166-L221
|
17,767
|
jeremylong/DependencyCheck
|
utils/src/main/java/org/owasp/dependencycheck/utils/HttpResourceConnection.java
|
HttpResourceConnection.isQuickQuery
|
private boolean isQuickQuery() {
boolean quickQuery;
try {
quickQuery = settings.getBoolean(Settings.KEYS.DOWNLOADER_QUICK_QUERY_TIMESTAMP, true);
} catch (InvalidSettingException e) {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Invalid settings : {}", e.getMessage(), e);
}
quickQuery = true;
}
return quickQuery;
}
|
java
|
private boolean isQuickQuery() {
boolean quickQuery;
try {
quickQuery = settings.getBoolean(Settings.KEYS.DOWNLOADER_QUICK_QUERY_TIMESTAMP, true);
} catch (InvalidSettingException e) {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Invalid settings : {}", e.getMessage(), e);
}
quickQuery = true;
}
return quickQuery;
}
|
[
"private",
"boolean",
"isQuickQuery",
"(",
")",
"{",
"boolean",
"quickQuery",
";",
"try",
"{",
"quickQuery",
"=",
"settings",
".",
"getBoolean",
"(",
"Settings",
".",
"KEYS",
".",
"DOWNLOADER_QUICK_QUERY_TIMESTAMP",
",",
"true",
")",
";",
"}",
"catch",
"(",
"InvalidSettingException",
"e",
")",
"{",
"if",
"(",
"LOGGER",
".",
"isTraceEnabled",
"(",
")",
")",
"{",
"LOGGER",
".",
"trace",
"(",
"\"Invalid settings : {}\"",
",",
"e",
".",
"getMessage",
"(",
")",
",",
"e",
")",
";",
"}",
"quickQuery",
"=",
"true",
";",
"}",
"return",
"quickQuery",
";",
"}"
] |
Determines if the HTTP method GET or HEAD should be used to check the
timestamp on external resources.
@return true if configured to use HEAD requests
|
[
"Determines",
"if",
"the",
"HTTP",
"method",
"GET",
"or",
"HEAD",
"should",
"be",
"used",
"to",
"check",
"the",
"timestamp",
"on",
"external",
"resources",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/utils/src/main/java/org/owasp/dependencycheck/utils/HttpResourceConnection.java#L346-L358
|
17,768
|
jeremylong/DependencyCheck
|
utils/src/main/java/org/owasp/dependencycheck/utils/HttpResourceConnection.java
|
HttpResourceConnection.checkForCommonExceptionTypes
|
public void checkForCommonExceptionTypes(IOException ex) throws DownloadFailedException {
Throwable cause = ex;
while (cause != null) {
if (cause instanceof java.net.UnknownHostException) {
final String msg = format("Unable to resolve domain '%s'", cause.getMessage());
LOGGER.error(msg);
throw new DownloadFailedException(msg);
}
if (cause instanceof InvalidAlgorithmParameterException) {
final String keystore = System.getProperty("javax.net.ssl.keyStore");
final String version = System.getProperty("java.version");
final String vendor = System.getProperty("java.vendor");
LOGGER.info("Error making HTTPS request - InvalidAlgorithmParameterException");
LOGGER.info("There appears to be an issue with the installation of Java and the cacerts."
+ "See closed issue #177 here: https://github.com/jeremylong/DependencyCheck/issues/177");
LOGGER.info("Java Info:\njavax.net.ssl.keyStore='{}'\njava.version='{}'\njava.vendor='{}'",
keystore, version, vendor);
throw new DownloadFailedException("Error making HTTPS request. Please see the log for more details.");
}
cause = cause.getCause();
}
}
|
java
|
public void checkForCommonExceptionTypes(IOException ex) throws DownloadFailedException {
Throwable cause = ex;
while (cause != null) {
if (cause instanceof java.net.UnknownHostException) {
final String msg = format("Unable to resolve domain '%s'", cause.getMessage());
LOGGER.error(msg);
throw new DownloadFailedException(msg);
}
if (cause instanceof InvalidAlgorithmParameterException) {
final String keystore = System.getProperty("javax.net.ssl.keyStore");
final String version = System.getProperty("java.version");
final String vendor = System.getProperty("java.vendor");
LOGGER.info("Error making HTTPS request - InvalidAlgorithmParameterException");
LOGGER.info("There appears to be an issue with the installation of Java and the cacerts."
+ "See closed issue #177 here: https://github.com/jeremylong/DependencyCheck/issues/177");
LOGGER.info("Java Info:\njavax.net.ssl.keyStore='{}'\njava.version='{}'\njava.vendor='{}'",
keystore, version, vendor);
throw new DownloadFailedException("Error making HTTPS request. Please see the log for more details.");
}
cause = cause.getCause();
}
}
|
[
"public",
"void",
"checkForCommonExceptionTypes",
"(",
"IOException",
"ex",
")",
"throws",
"DownloadFailedException",
"{",
"Throwable",
"cause",
"=",
"ex",
";",
"while",
"(",
"cause",
"!=",
"null",
")",
"{",
"if",
"(",
"cause",
"instanceof",
"java",
".",
"net",
".",
"UnknownHostException",
")",
"{",
"final",
"String",
"msg",
"=",
"format",
"(",
"\"Unable to resolve domain '%s'\"",
",",
"cause",
".",
"getMessage",
"(",
")",
")",
";",
"LOGGER",
".",
"error",
"(",
"msg",
")",
";",
"throw",
"new",
"DownloadFailedException",
"(",
"msg",
")",
";",
"}",
"if",
"(",
"cause",
"instanceof",
"InvalidAlgorithmParameterException",
")",
"{",
"final",
"String",
"keystore",
"=",
"System",
".",
"getProperty",
"(",
"\"javax.net.ssl.keyStore\"",
")",
";",
"final",
"String",
"version",
"=",
"System",
".",
"getProperty",
"(",
"\"java.version\"",
")",
";",
"final",
"String",
"vendor",
"=",
"System",
".",
"getProperty",
"(",
"\"java.vendor\"",
")",
";",
"LOGGER",
".",
"info",
"(",
"\"Error making HTTPS request - InvalidAlgorithmParameterException\"",
")",
";",
"LOGGER",
".",
"info",
"(",
"\"There appears to be an issue with the installation of Java and the cacerts.\"",
"+",
"\"See closed issue #177 here: https://github.com/jeremylong/DependencyCheck/issues/177\"",
")",
";",
"LOGGER",
".",
"info",
"(",
"\"Java Info:\\njavax.net.ssl.keyStore='{}'\\njava.version='{}'\\njava.vendor='{}'\"",
",",
"keystore",
",",
"version",
",",
"vendor",
")",
";",
"throw",
"new",
"DownloadFailedException",
"(",
"\"Error making HTTPS request. Please see the log for more details.\"",
")",
";",
"}",
"cause",
"=",
"cause",
".",
"getCause",
"(",
")",
";",
"}",
"}"
] |
Analyzes the IOException, logs the appropriate information for debugging
purposes, and then throws a DownloadFailedException that wraps the IO
Exception for common IO Exceptions. This is to provide additional details
to assist in resolution of the exception.
@param ex the original exception
@throws org.owasp.dependencycheck.utils.DownloadFailedException a wrapper
exception that contains the original exception as the cause
|
[
"Analyzes",
"the",
"IOException",
"logs",
"the",
"appropriate",
"information",
"for",
"debugging",
"purposes",
"and",
"then",
"throws",
"a",
"DownloadFailedException",
"that",
"wraps",
"the",
"IO",
"Exception",
"for",
"common",
"IO",
"Exceptions",
".",
"This",
"is",
"to",
"provide",
"additional",
"details",
"to",
"assist",
"in",
"resolution",
"of",
"the",
"exception",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/utils/src/main/java/org/owasp/dependencycheck/utils/HttpResourceConnection.java#L370-L391
|
17,769
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/utils/H2DBCleanupHook.java
|
H2DBCleanupHook.remove
|
@Override
public void remove() {
try {
Runtime.getRuntime().removeShutdownHook(this);
} catch (IllegalStateException ex) {
LOGGER.trace("ignore as we are likely shutting down", ex);
}
}
|
java
|
@Override
public void remove() {
try {
Runtime.getRuntime().removeShutdownHook(this);
} catch (IllegalStateException ex) {
LOGGER.trace("ignore as we are likely shutting down", ex);
}
}
|
[
"@",
"Override",
"public",
"void",
"remove",
"(",
")",
"{",
"try",
"{",
"Runtime",
".",
"getRuntime",
"(",
")",
".",
"removeShutdownHook",
"(",
"this",
")",
";",
"}",
"catch",
"(",
"IllegalStateException",
"ex",
")",
"{",
"LOGGER",
".",
"trace",
"(",
"\"ignore as we are likely shutting down\"",
",",
"ex",
")",
";",
"}",
"}"
] |
Removes the shutdown hook.
|
[
"Removes",
"the",
"shutdown",
"hook",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/utils/H2DBCleanupHook.java#L55-L62
|
17,770
|
jeremylong/DependencyCheck
|
maven/src/main/java/org/owasp/dependencycheck/maven/CheckMojo.java
|
CheckMojo.canGenerateReport
|
@Override
public boolean canGenerateReport() {
populateSettings();
boolean isCapable = false;
for (Artifact a : getProject().getArtifacts()) {
if (!getArtifactScopeExcluded().passes(a.getScope())) {
isCapable = true;
break;
}
}
return isCapable;
}
|
java
|
@Override
public boolean canGenerateReport() {
populateSettings();
boolean isCapable = false;
for (Artifact a : getProject().getArtifacts()) {
if (!getArtifactScopeExcluded().passes(a.getScope())) {
isCapable = true;
break;
}
}
return isCapable;
}
|
[
"@",
"Override",
"public",
"boolean",
"canGenerateReport",
"(",
")",
"{",
"populateSettings",
"(",
")",
";",
"boolean",
"isCapable",
"=",
"false",
";",
"for",
"(",
"Artifact",
"a",
":",
"getProject",
"(",
")",
".",
"getArtifacts",
"(",
")",
")",
"{",
"if",
"(",
"!",
"getArtifactScopeExcluded",
"(",
")",
".",
"passes",
"(",
"a",
".",
"getScope",
"(",
")",
")",
")",
"{",
"isCapable",
"=",
"true",
";",
"break",
";",
"}",
"}",
"return",
"isCapable",
";",
"}"
] |
Returns whether or not a the report can be generated.
@return <code>true</code> if the report can be generated; otherwise
<code>false</code>
|
[
"Returns",
"whether",
"or",
"not",
"a",
"the",
"report",
"can",
"be",
"generated",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/maven/src/main/java/org/owasp/dependencycheck/maven/CheckMojo.java#L58-L69
|
17,771
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/xml/pom/PomProjectInputStream.java
|
PomProjectInputStream.skipToProject
|
private void skipToProject() throws IOException {
final byte[] buffer = new byte[BUFFER_SIZE];
super.mark(BUFFER_SIZE);
int count = super.read(buffer, 0, BUFFER_SIZE);
while (count > 0) {
final int pos = findSequence(PROJECT, buffer);
if (pos >= 0) {
super.reset();
super.skip(pos);
return;
} else if (count - PROJECT.length == 0) {
return;
}
super.reset();
super.skip(count - PROJECT.length);
super.mark(BUFFER_SIZE);
count = super.read(buffer, 0, BUFFER_SIZE);
}
}
|
java
|
private void skipToProject() throws IOException {
final byte[] buffer = new byte[BUFFER_SIZE];
super.mark(BUFFER_SIZE);
int count = super.read(buffer, 0, BUFFER_SIZE);
while (count > 0) {
final int pos = findSequence(PROJECT, buffer);
if (pos >= 0) {
super.reset();
super.skip(pos);
return;
} else if (count - PROJECT.length == 0) {
return;
}
super.reset();
super.skip(count - PROJECT.length);
super.mark(BUFFER_SIZE);
count = super.read(buffer, 0, BUFFER_SIZE);
}
}
|
[
"private",
"void",
"skipToProject",
"(",
")",
"throws",
"IOException",
"{",
"final",
"byte",
"[",
"]",
"buffer",
"=",
"new",
"byte",
"[",
"BUFFER_SIZE",
"]",
";",
"super",
".",
"mark",
"(",
"BUFFER_SIZE",
")",
";",
"int",
"count",
"=",
"super",
".",
"read",
"(",
"buffer",
",",
"0",
",",
"BUFFER_SIZE",
")",
";",
"while",
"(",
"count",
">",
"0",
")",
"{",
"final",
"int",
"pos",
"=",
"findSequence",
"(",
"PROJECT",
",",
"buffer",
")",
";",
"if",
"(",
"pos",
">=",
"0",
")",
"{",
"super",
".",
"reset",
"(",
")",
";",
"super",
".",
"skip",
"(",
"pos",
")",
";",
"return",
";",
"}",
"else",
"if",
"(",
"count",
"-",
"PROJECT",
".",
"length",
"==",
"0",
")",
"{",
"return",
";",
"}",
"super",
".",
"reset",
"(",
")",
";",
"super",
".",
"skip",
"(",
"count",
"-",
"PROJECT",
".",
"length",
")",
";",
"super",
".",
"mark",
"(",
"BUFFER_SIZE",
")",
";",
"count",
"=",
"super",
".",
"read",
"(",
"buffer",
",",
"0",
",",
"BUFFER_SIZE",
")",
";",
"}",
"}"
] |
Skips bytes from the input stream until it finds the <project>
element.
@throws IOException thrown if an I/O error occurs
|
[
"Skips",
"bytes",
"from",
"the",
"input",
"stream",
"until",
"it",
"finds",
"the",
"<",
";",
"project>",
";",
"element",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/xml/pom/PomProjectInputStream.java#L63-L81
|
17,772
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/xml/pom/PomProjectInputStream.java
|
PomProjectInputStream.findSequence
|
protected static int findSequence(byte[] sequence, byte[] buffer) {
int pos = -1;
for (int i = 0; i < buffer.length - sequence.length + 1; i++) {
if (buffer[i] == sequence[0] && testRemaining(sequence, buffer, i)) {
pos = i;
break;
}
}
return pos;
}
|
java
|
protected static int findSequence(byte[] sequence, byte[] buffer) {
int pos = -1;
for (int i = 0; i < buffer.length - sequence.length + 1; i++) {
if (buffer[i] == sequence[0] && testRemaining(sequence, buffer, i)) {
pos = i;
break;
}
}
return pos;
}
|
[
"protected",
"static",
"int",
"findSequence",
"(",
"byte",
"[",
"]",
"sequence",
",",
"byte",
"[",
"]",
"buffer",
")",
"{",
"int",
"pos",
"=",
"-",
"1",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"buffer",
".",
"length",
"-",
"sequence",
".",
"length",
"+",
"1",
";",
"i",
"++",
")",
"{",
"if",
"(",
"buffer",
"[",
"i",
"]",
"==",
"sequence",
"[",
"0",
"]",
"&&",
"testRemaining",
"(",
"sequence",
",",
"buffer",
",",
"i",
")",
")",
"{",
"pos",
"=",
"i",
";",
"break",
";",
"}",
"}",
"return",
"pos",
";",
"}"
] |
Finds the start of the given sequence in the buffer. If not found, -1 is
returned.
@param sequence the sequence to locate
@param buffer the buffer to search
@return the starting position of the sequence in the buffer if found;
otherwise -1
|
[
"Finds",
"the",
"start",
"of",
"the",
"given",
"sequence",
"in",
"the",
"buffer",
".",
"If",
"not",
"found",
"-",
"1",
"is",
"returned",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/xml/pom/PomProjectInputStream.java#L114-L123
|
17,773
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/xml/hints/HintRule.java
|
HintRule.addGivenProduct
|
public void addGivenProduct(String source, String name, String value, boolean regex, Confidence confidence) {
givenProduct.add(new EvidenceMatcher(source, name, value, regex, confidence));
}
|
java
|
public void addGivenProduct(String source, String name, String value, boolean regex, Confidence confidence) {
givenProduct.add(new EvidenceMatcher(source, name, value, regex, confidence));
}
|
[
"public",
"void",
"addGivenProduct",
"(",
"String",
"source",
",",
"String",
"name",
",",
"String",
"value",
",",
"boolean",
"regex",
",",
"Confidence",
"confidence",
")",
"{",
"givenProduct",
".",
"add",
"(",
"new",
"EvidenceMatcher",
"(",
"source",
",",
"name",
",",
"value",
",",
"regex",
",",
"confidence",
")",
")",
";",
"}"
] |
Adds a given product to the list of evidence to matched.
@param source the source of the evidence
@param name the name of the evidence
@param value the value of the evidence
@param regex whether value is a regex
@param confidence the confidence of the evidence
|
[
"Adds",
"a",
"given",
"product",
"to",
"the",
"list",
"of",
"evidence",
"to",
"matched",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/xml/hints/HintRule.java#L106-L108
|
17,774
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/xml/hints/HintRule.java
|
HintRule.addGivenVendor
|
public void addGivenVendor(String source, String name, String value, boolean regex, Confidence confidence) {
givenVendor.add(new EvidenceMatcher(source, name, value, regex, confidence));
}
|
java
|
public void addGivenVendor(String source, String name, String value, boolean regex, Confidence confidence) {
givenVendor.add(new EvidenceMatcher(source, name, value, regex, confidence));
}
|
[
"public",
"void",
"addGivenVendor",
"(",
"String",
"source",
",",
"String",
"name",
",",
"String",
"value",
",",
"boolean",
"regex",
",",
"Confidence",
"confidence",
")",
"{",
"givenVendor",
".",
"add",
"(",
"new",
"EvidenceMatcher",
"(",
"source",
",",
"name",
",",
"value",
",",
"regex",
",",
"confidence",
")",
")",
";",
"}"
] |
Adds a given vendors to the list of evidence to matched.
@param source the source of the evidence
@param name the name of the evidence
@param value the value of the evidence
@param regex whether value is a regex
@param confidence the confidence of the evidence
|
[
"Adds",
"a",
"given",
"vendors",
"to",
"the",
"list",
"of",
"evidence",
"to",
"matched",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/xml/hints/HintRule.java#L128-L130
|
17,775
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/xml/hints/HintRule.java
|
HintRule.addAddProduct
|
public void addAddProduct(String source, String name, String value, Confidence confidence) {
addProduct.add(new Evidence(source, name, value, confidence));
}
|
java
|
public void addAddProduct(String source, String name, String value, Confidence confidence) {
addProduct.add(new Evidence(source, name, value, confidence));
}
|
[
"public",
"void",
"addAddProduct",
"(",
"String",
"source",
",",
"String",
"name",
",",
"String",
"value",
",",
"Confidence",
"confidence",
")",
"{",
"addProduct",
".",
"add",
"(",
"new",
"Evidence",
"(",
"source",
",",
"name",
",",
"value",
",",
"confidence",
")",
")",
";",
"}"
] |
Adds a given product to the list of evidence to add when matched.
@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
|
[
"Adds",
"a",
"given",
"product",
"to",
"the",
"list",
"of",
"evidence",
"to",
"add",
"when",
"matched",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/xml/hints/HintRule.java#L149-L151
|
17,776
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/xml/hints/HintRule.java
|
HintRule.addAddVersion
|
public void addAddVersion(String source, String name, String value, Confidence confidence) {
addVersion.add(new Evidence(source, name, value, confidence));
}
|
java
|
public void addAddVersion(String source, String name, String value, Confidence confidence) {
addVersion.add(new Evidence(source, name, value, confidence));
}
|
[
"public",
"void",
"addAddVersion",
"(",
"String",
"source",
",",
"String",
"name",
",",
"String",
"value",
",",
"Confidence",
"confidence",
")",
"{",
"addVersion",
".",
"add",
"(",
"new",
"Evidence",
"(",
"source",
",",
"name",
",",
"value",
",",
"confidence",
")",
")",
";",
"}"
] |
Adds a given version to the list of evidence to add when matched.
@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
|
[
"Adds",
"a",
"given",
"version",
"to",
"the",
"list",
"of",
"evidence",
"to",
"add",
"when",
"matched",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/xml/hints/HintRule.java#L170-L172
|
17,777
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/xml/hints/HintRule.java
|
HintRule.addAddVendor
|
public void addAddVendor(String source, String name, String value, Confidence confidence) {
addVendor.add(new Evidence(source, name, value, confidence));
}
|
java
|
public void addAddVendor(String source, String name, String value, Confidence confidence) {
addVendor.add(new Evidence(source, name, value, confidence));
}
|
[
"public",
"void",
"addAddVendor",
"(",
"String",
"source",
",",
"String",
"name",
",",
"String",
"value",
",",
"Confidence",
"confidence",
")",
"{",
"addVendor",
".",
"add",
"(",
"new",
"Evidence",
"(",
"source",
",",
"name",
",",
"value",
",",
"confidence",
")",
")",
";",
"}"
] |
Adds a given vendor to the list of evidence to add when matched.
@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
|
[
"Adds",
"a",
"given",
"vendor",
"to",
"the",
"list",
"of",
"evidence",
"to",
"add",
"when",
"matched",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/xml/hints/HintRule.java#L191-L193
|
17,778
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/xml/hints/HintRule.java
|
HintRule.addRemoveVendor
|
public void addRemoveVendor(String source, String name, String value, boolean regex, Confidence confidence) {
removeVendor.add(new EvidenceMatcher(source, name, value, regex, confidence));
}
|
java
|
public void addRemoveVendor(String source, String name, String value, boolean regex, Confidence confidence) {
removeVendor.add(new EvidenceMatcher(source, name, value, regex, confidence));
}
|
[
"public",
"void",
"addRemoveVendor",
"(",
"String",
"source",
",",
"String",
"name",
",",
"String",
"value",
",",
"boolean",
"regex",
",",
"Confidence",
"confidence",
")",
"{",
"removeVendor",
".",
"add",
"(",
"new",
"EvidenceMatcher",
"(",
"source",
",",
"name",
",",
"value",
",",
"regex",
",",
"confidence",
")",
")",
";",
"}"
] |
Adds a given vendor to the list of evidence to remove when matched.
@param source the source of the evidence
@param name the name of the evidence
@param value the value of the evidence
@param regex whether value is a regex
@param confidence the confidence of the evidence
|
[
"Adds",
"a",
"given",
"vendor",
"to",
"the",
"list",
"of",
"evidence",
"to",
"remove",
"when",
"matched",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/xml/hints/HintRule.java#L213-L215
|
17,779
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/xml/hints/HintRule.java
|
HintRule.addRemoveProduct
|
public void addRemoveProduct(String source, String name, String value, boolean regex, Confidence confidence) {
removeProduct.add(new EvidenceMatcher(source, name, value, regex, confidence));
}
|
java
|
public void addRemoveProduct(String source, String name, String value, boolean regex, Confidence confidence) {
removeProduct.add(new EvidenceMatcher(source, name, value, regex, confidence));
}
|
[
"public",
"void",
"addRemoveProduct",
"(",
"String",
"source",
",",
"String",
"name",
",",
"String",
"value",
",",
"boolean",
"regex",
",",
"Confidence",
"confidence",
")",
"{",
"removeProduct",
".",
"add",
"(",
"new",
"EvidenceMatcher",
"(",
"source",
",",
"name",
",",
"value",
",",
"regex",
",",
"confidence",
")",
")",
";",
"}"
] |
Adds a given product to the list of evidence to remove when matched.
@param source the source of the evidence
@param name the name of the evidence
@param value the value of the evidence
@param regex whether value is a regex
@param confidence the confidence of the evidence
|
[
"Adds",
"a",
"given",
"product",
"to",
"the",
"list",
"of",
"evidence",
"to",
"remove",
"when",
"matched",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/xml/hints/HintRule.java#L233-L235
|
17,780
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/xml/hints/HintRule.java
|
HintRule.addRemoveVersion
|
public void addRemoveVersion(String source, String name, String value, boolean regex, Confidence confidence) {
removeVersion.add(new EvidenceMatcher(source, name, value, regex, confidence));
}
|
java
|
public void addRemoveVersion(String source, String name, String value, boolean regex, Confidence confidence) {
removeVersion.add(new EvidenceMatcher(source, name, value, regex, confidence));
}
|
[
"public",
"void",
"addRemoveVersion",
"(",
"String",
"source",
",",
"String",
"name",
",",
"String",
"value",
",",
"boolean",
"regex",
",",
"Confidence",
"confidence",
")",
"{",
"removeVersion",
".",
"add",
"(",
"new",
"EvidenceMatcher",
"(",
"source",
",",
"name",
",",
"value",
",",
"regex",
",",
"confidence",
")",
")",
";",
"}"
] |
Adds a given version to the list of evidence to remove when matched.
@param source the source of the evidence
@param name the name of the evidence
@param value the value of the evidence
@param regex whether value is a regex
@param confidence the confidence of the evidence
|
[
"Adds",
"a",
"given",
"version",
"to",
"the",
"list",
"of",
"evidence",
"to",
"remove",
"when",
"matched",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/xml/hints/HintRule.java#L253-L255
|
17,781
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/xml/hints/HintRule.java
|
HintRule.addGivenVersion
|
public void addGivenVersion(String source, String name, String value, boolean regex, Confidence confidence) {
givenVersion.add(new EvidenceMatcher(source, name, value, regex, confidence));
}
|
java
|
public void addGivenVersion(String source, String name, String value, boolean regex, Confidence confidence) {
givenVersion.add(new EvidenceMatcher(source, name, value, regex, confidence));
}
|
[
"public",
"void",
"addGivenVersion",
"(",
"String",
"source",
",",
"String",
"name",
",",
"String",
"value",
",",
"boolean",
"regex",
",",
"Confidence",
"confidence",
")",
"{",
"givenVersion",
".",
"add",
"(",
"new",
"EvidenceMatcher",
"(",
"source",
",",
"name",
",",
"value",
",",
"regex",
",",
"confidence",
")",
")",
";",
"}"
] |
Adds a given version to the list of evidence to match.
@param source the source of the evidence
@param name the name of the evidence
@param value the value of the evidence
@param regex whether value is a regex
@param confidence the confidence of the evidence
|
[
"Adds",
"a",
"given",
"version",
"to",
"the",
"list",
"of",
"evidence",
"to",
"match",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/xml/hints/HintRule.java#L273-L275
|
17,782
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/utils/ExtractionUtil.java
|
ExtractionUtil.extractFiles
|
public static void extractFiles(File archive, File extractTo, Engine engine) throws ExtractionException {
if (archive == null || extractTo == null) {
return;
}
final String destPath;
try {
destPath = extractTo.getCanonicalPath();
} catch (IOException ex) {
throw new ExtractionException("Unable to extract files to destination path", ex);
}
ZipEntry entry;
try (FileInputStream fis = new FileInputStream(archive);
BufferedInputStream bis = new BufferedInputStream(fis);
ZipInputStream zis = new ZipInputStream(bis)) {
while ((entry = zis.getNextEntry()) != null) {
if (entry.isDirectory()) {
final File d = new File(extractTo, entry.getName());
if (!d.getCanonicalPath().startsWith(destPath)) {
final String msg = String.format(
"Archive (%s) contains a path that would be extracted outside of the target directory.",
archive.getAbsolutePath());
throw new ExtractionException(msg);
}
if (!d.exists() && !d.mkdirs()) {
final String msg = String.format("Unable to create '%s'.", d.getAbsolutePath());
throw new ExtractionException(msg);
}
} else {
final File file = new File(extractTo, entry.getName());
if (engine == null || engine.accept(file)) {
if (!file.getCanonicalPath().startsWith(destPath)) {
final String msg = String.format(
"Archive (%s) contains a file that would be extracted outside of the target directory.",
archive.getAbsolutePath());
throw new ExtractionException(msg);
}
try (FileOutputStream fos = new FileOutputStream(file)) {
IOUtils.copy(zis, fos);
} catch (FileNotFoundException ex) {
LOGGER.debug("", ex);
final String msg = String.format("Unable to find file '%s'.", file.getName());
throw new ExtractionException(msg, ex);
} catch (IOException ex) {
LOGGER.debug("", ex);
final String msg = String.format("IO Exception while parsing file '%s'.", file.getName());
throw new ExtractionException(msg, ex);
}
}
}
}
} catch (IOException ex) {
final String msg = String.format("Exception reading archive '%s'.", archive.getName());
LOGGER.debug("", ex);
throw new ExtractionException(msg, ex);
}
}
|
java
|
public static void extractFiles(File archive, File extractTo, Engine engine) throws ExtractionException {
if (archive == null || extractTo == null) {
return;
}
final String destPath;
try {
destPath = extractTo.getCanonicalPath();
} catch (IOException ex) {
throw new ExtractionException("Unable to extract files to destination path", ex);
}
ZipEntry entry;
try (FileInputStream fis = new FileInputStream(archive);
BufferedInputStream bis = new BufferedInputStream(fis);
ZipInputStream zis = new ZipInputStream(bis)) {
while ((entry = zis.getNextEntry()) != null) {
if (entry.isDirectory()) {
final File d = new File(extractTo, entry.getName());
if (!d.getCanonicalPath().startsWith(destPath)) {
final String msg = String.format(
"Archive (%s) contains a path that would be extracted outside of the target directory.",
archive.getAbsolutePath());
throw new ExtractionException(msg);
}
if (!d.exists() && !d.mkdirs()) {
final String msg = String.format("Unable to create '%s'.", d.getAbsolutePath());
throw new ExtractionException(msg);
}
} else {
final File file = new File(extractTo, entry.getName());
if (engine == null || engine.accept(file)) {
if (!file.getCanonicalPath().startsWith(destPath)) {
final String msg = String.format(
"Archive (%s) contains a file that would be extracted outside of the target directory.",
archive.getAbsolutePath());
throw new ExtractionException(msg);
}
try (FileOutputStream fos = new FileOutputStream(file)) {
IOUtils.copy(zis, fos);
} catch (FileNotFoundException ex) {
LOGGER.debug("", ex);
final String msg = String.format("Unable to find file '%s'.", file.getName());
throw new ExtractionException(msg, ex);
} catch (IOException ex) {
LOGGER.debug("", ex);
final String msg = String.format("IO Exception while parsing file '%s'.", file.getName());
throw new ExtractionException(msg, ex);
}
}
}
}
} catch (IOException ex) {
final String msg = String.format("Exception reading archive '%s'.", archive.getName());
LOGGER.debug("", ex);
throw new ExtractionException(msg, ex);
}
}
|
[
"public",
"static",
"void",
"extractFiles",
"(",
"File",
"archive",
",",
"File",
"extractTo",
",",
"Engine",
"engine",
")",
"throws",
"ExtractionException",
"{",
"if",
"(",
"archive",
"==",
"null",
"||",
"extractTo",
"==",
"null",
")",
"{",
"return",
";",
"}",
"final",
"String",
"destPath",
";",
"try",
"{",
"destPath",
"=",
"extractTo",
".",
"getCanonicalPath",
"(",
")",
";",
"}",
"catch",
"(",
"IOException",
"ex",
")",
"{",
"throw",
"new",
"ExtractionException",
"(",
"\"Unable to extract files to destination path\"",
",",
"ex",
")",
";",
"}",
"ZipEntry",
"entry",
";",
"try",
"(",
"FileInputStream",
"fis",
"=",
"new",
"FileInputStream",
"(",
"archive",
")",
";",
"BufferedInputStream",
"bis",
"=",
"new",
"BufferedInputStream",
"(",
"fis",
")",
";",
"ZipInputStream",
"zis",
"=",
"new",
"ZipInputStream",
"(",
"bis",
")",
")",
"{",
"while",
"(",
"(",
"entry",
"=",
"zis",
".",
"getNextEntry",
"(",
")",
")",
"!=",
"null",
")",
"{",
"if",
"(",
"entry",
".",
"isDirectory",
"(",
")",
")",
"{",
"final",
"File",
"d",
"=",
"new",
"File",
"(",
"extractTo",
",",
"entry",
".",
"getName",
"(",
")",
")",
";",
"if",
"(",
"!",
"d",
".",
"getCanonicalPath",
"(",
")",
".",
"startsWith",
"(",
"destPath",
")",
")",
"{",
"final",
"String",
"msg",
"=",
"String",
".",
"format",
"(",
"\"Archive (%s) contains a path that would be extracted outside of the target directory.\"",
",",
"archive",
".",
"getAbsolutePath",
"(",
")",
")",
";",
"throw",
"new",
"ExtractionException",
"(",
"msg",
")",
";",
"}",
"if",
"(",
"!",
"d",
".",
"exists",
"(",
")",
"&&",
"!",
"d",
".",
"mkdirs",
"(",
")",
")",
"{",
"final",
"String",
"msg",
"=",
"String",
".",
"format",
"(",
"\"Unable to create '%s'.\"",
",",
"d",
".",
"getAbsolutePath",
"(",
")",
")",
";",
"throw",
"new",
"ExtractionException",
"(",
"msg",
")",
";",
"}",
"}",
"else",
"{",
"final",
"File",
"file",
"=",
"new",
"File",
"(",
"extractTo",
",",
"entry",
".",
"getName",
"(",
")",
")",
";",
"if",
"(",
"engine",
"==",
"null",
"||",
"engine",
".",
"accept",
"(",
"file",
")",
")",
"{",
"if",
"(",
"!",
"file",
".",
"getCanonicalPath",
"(",
")",
".",
"startsWith",
"(",
"destPath",
")",
")",
"{",
"final",
"String",
"msg",
"=",
"String",
".",
"format",
"(",
"\"Archive (%s) contains a file that would be extracted outside of the target directory.\"",
",",
"archive",
".",
"getAbsolutePath",
"(",
")",
")",
";",
"throw",
"new",
"ExtractionException",
"(",
"msg",
")",
";",
"}",
"try",
"(",
"FileOutputStream",
"fos",
"=",
"new",
"FileOutputStream",
"(",
"file",
")",
")",
"{",
"IOUtils",
".",
"copy",
"(",
"zis",
",",
"fos",
")",
";",
"}",
"catch",
"(",
"FileNotFoundException",
"ex",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"\"",
",",
"ex",
")",
";",
"final",
"String",
"msg",
"=",
"String",
".",
"format",
"(",
"\"Unable to find file '%s'.\"",
",",
"file",
".",
"getName",
"(",
")",
")",
";",
"throw",
"new",
"ExtractionException",
"(",
"msg",
",",
"ex",
")",
";",
"}",
"catch",
"(",
"IOException",
"ex",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"\"",
",",
"ex",
")",
";",
"final",
"String",
"msg",
"=",
"String",
".",
"format",
"(",
"\"IO Exception while parsing file '%s'.\"",
",",
"file",
".",
"getName",
"(",
")",
")",
";",
"throw",
"new",
"ExtractionException",
"(",
"msg",
",",
"ex",
")",
";",
"}",
"}",
"}",
"}",
"}",
"catch",
"(",
"IOException",
"ex",
")",
"{",
"final",
"String",
"msg",
"=",
"String",
".",
"format",
"(",
"\"Exception reading archive '%s'.\"",
",",
"archive",
".",
"getName",
"(",
")",
")",
";",
"LOGGER",
".",
"debug",
"(",
"\"\"",
",",
"ex",
")",
";",
"throw",
"new",
"ExtractionException",
"(",
"msg",
",",
"ex",
")",
";",
"}",
"}"
] |
Extracts the contents of an archive into the specified directory. The
files are only extracted if they are supported by the analyzers loaded
into the specified engine. If the engine is specified as null then all
files are extracted.
@param archive an archive file such as a WAR or EAR
@param extractTo a directory to extract the contents to
@param engine the scanning engine
@throws ExtractionException thrown if there is an error extracting the
files
|
[
"Extracts",
"the",
"contents",
"of",
"an",
"archive",
"into",
"the",
"specified",
"directory",
".",
"The",
"files",
"are",
"only",
"extracted",
"if",
"they",
"are",
"supported",
"by",
"the",
"analyzers",
"loaded",
"into",
"the",
"specified",
"engine",
".",
"If",
"the",
"engine",
"is",
"specified",
"as",
"null",
"then",
"all",
"files",
"are",
"extracted",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/utils/ExtractionUtil.java#L86-L141
|
17,783
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/utils/ExtractionUtil.java
|
ExtractionUtil.extractArchive
|
private static void extractArchive(ArchiveInputStream input,
File destination, FilenameFilter filter)
throws ArchiveExtractionException {
ArchiveEntry entry;
try {
final String destPath = destination.getCanonicalPath();
while ((entry = input.getNextEntry()) != null) {
if (entry.isDirectory()) {
final File dir = new File(destination, entry.getName());
if (!dir.getCanonicalPath().startsWith(destPath)) {
final String msg = String.format(
"Archive contains a path (%s) that would be extracted outside of the target directory.",
dir.getAbsolutePath());
throw new AnalysisException(msg);
}
if (!dir.exists() && !dir.mkdirs()) {
final String msg = String.format(
"Unable to create directory '%s'.",
dir.getAbsolutePath());
throw new AnalysisException(msg);
}
} else {
extractFile(input, destination, filter, entry);
}
}
} catch (IOException | AnalysisException ex) {
throw new ArchiveExtractionException(ex);
} finally {
FileUtils.close(input);
}
}
|
java
|
private static void extractArchive(ArchiveInputStream input,
File destination, FilenameFilter filter)
throws ArchiveExtractionException {
ArchiveEntry entry;
try {
final String destPath = destination.getCanonicalPath();
while ((entry = input.getNextEntry()) != null) {
if (entry.isDirectory()) {
final File dir = new File(destination, entry.getName());
if (!dir.getCanonicalPath().startsWith(destPath)) {
final String msg = String.format(
"Archive contains a path (%s) that would be extracted outside of the target directory.",
dir.getAbsolutePath());
throw new AnalysisException(msg);
}
if (!dir.exists() && !dir.mkdirs()) {
final String msg = String.format(
"Unable to create directory '%s'.",
dir.getAbsolutePath());
throw new AnalysisException(msg);
}
} else {
extractFile(input, destination, filter, entry);
}
}
} catch (IOException | AnalysisException ex) {
throw new ArchiveExtractionException(ex);
} finally {
FileUtils.close(input);
}
}
|
[
"private",
"static",
"void",
"extractArchive",
"(",
"ArchiveInputStream",
"input",
",",
"File",
"destination",
",",
"FilenameFilter",
"filter",
")",
"throws",
"ArchiveExtractionException",
"{",
"ArchiveEntry",
"entry",
";",
"try",
"{",
"final",
"String",
"destPath",
"=",
"destination",
".",
"getCanonicalPath",
"(",
")",
";",
"while",
"(",
"(",
"entry",
"=",
"input",
".",
"getNextEntry",
"(",
")",
")",
"!=",
"null",
")",
"{",
"if",
"(",
"entry",
".",
"isDirectory",
"(",
")",
")",
"{",
"final",
"File",
"dir",
"=",
"new",
"File",
"(",
"destination",
",",
"entry",
".",
"getName",
"(",
")",
")",
";",
"if",
"(",
"!",
"dir",
".",
"getCanonicalPath",
"(",
")",
".",
"startsWith",
"(",
"destPath",
")",
")",
"{",
"final",
"String",
"msg",
"=",
"String",
".",
"format",
"(",
"\"Archive contains a path (%s) that would be extracted outside of the target directory.\"",
",",
"dir",
".",
"getAbsolutePath",
"(",
")",
")",
";",
"throw",
"new",
"AnalysisException",
"(",
"msg",
")",
";",
"}",
"if",
"(",
"!",
"dir",
".",
"exists",
"(",
")",
"&&",
"!",
"dir",
".",
"mkdirs",
"(",
")",
")",
"{",
"final",
"String",
"msg",
"=",
"String",
".",
"format",
"(",
"\"Unable to create directory '%s'.\"",
",",
"dir",
".",
"getAbsolutePath",
"(",
")",
")",
";",
"throw",
"new",
"AnalysisException",
"(",
"msg",
")",
";",
"}",
"}",
"else",
"{",
"extractFile",
"(",
"input",
",",
"destination",
",",
"filter",
",",
"entry",
")",
";",
"}",
"}",
"}",
"catch",
"(",
"IOException",
"|",
"AnalysisException",
"ex",
")",
"{",
"throw",
"new",
"ArchiveExtractionException",
"(",
"ex",
")",
";",
"}",
"finally",
"{",
"FileUtils",
".",
"close",
"(",
"input",
")",
";",
"}",
"}"
] |
Extracts files from an archive.
@param input the archive to extract files from
@param destination the location to write the files too
@param filter determines which files get extracted
@throws ArchiveExtractionException thrown if there is an exception
extracting files from the archive
|
[
"Extracts",
"files",
"from",
"an",
"archive",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/utils/ExtractionUtil.java#L235-L266
|
17,784
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/utils/ExtractionUtil.java
|
ExtractionUtil.createParentFile
|
private static void createParentFile(final File file) throws ExtractionException {
final File parent = file.getParentFile();
if (!parent.isDirectory() && !parent.mkdirs()) {
final String msg = String.format(
"Unable to build directory '%s'.",
parent.getAbsolutePath());
throw new ExtractionException(msg);
}
}
|
java
|
private static void createParentFile(final File file) throws ExtractionException {
final File parent = file.getParentFile();
if (!parent.isDirectory() && !parent.mkdirs()) {
final String msg = String.format(
"Unable to build directory '%s'.",
parent.getAbsolutePath());
throw new ExtractionException(msg);
}
}
|
[
"private",
"static",
"void",
"createParentFile",
"(",
"final",
"File",
"file",
")",
"throws",
"ExtractionException",
"{",
"final",
"File",
"parent",
"=",
"file",
".",
"getParentFile",
"(",
")",
";",
"if",
"(",
"!",
"parent",
".",
"isDirectory",
"(",
")",
"&&",
"!",
"parent",
".",
"mkdirs",
"(",
")",
")",
"{",
"final",
"String",
"msg",
"=",
"String",
".",
"format",
"(",
"\"Unable to build directory '%s'.\"",
",",
"parent",
".",
"getAbsolutePath",
"(",
")",
")",
";",
"throw",
"new",
"ExtractionException",
"(",
"msg",
")",
";",
"}",
"}"
] |
Ensures the parent path is correctly created on disk so that the file can
be extracted to the correct location.
@param file the file path
@throws ExtractionException thrown if the parent paths could not be
created
|
[
"Ensures",
"the",
"parent",
"path",
"is",
"correctly",
"created",
"on",
"disk",
"so",
"that",
"the",
"file",
"can",
"be",
"extracted",
"to",
"the",
"correct",
"location",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/utils/ExtractionUtil.java#L317-L325
|
17,785
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/utils/ExtractionUtil.java
|
ExtractionUtil.extractGzip
|
public static void extractGzip(File file) throws FileNotFoundException, IOException {
final String originalPath = file.getPath();
final File gzip = new File(originalPath + ".gz");
if (gzip.isFile() && !gzip.delete()) {
LOGGER.debug("Failed to delete initial temporary file when extracting 'gz' {}", gzip.toString());
gzip.deleteOnExit();
}
if (!file.renameTo(gzip)) {
throw new IOException("Unable to rename '" + file.getPath() + "'");
}
final File newFile = new File(originalPath);
try (FileInputStream fis = new FileInputStream(gzip);
GZIPInputStream cin = new GZIPInputStream(fis);
FileOutputStream out = new FileOutputStream(newFile)) {
IOUtils.copy(cin, out);
} finally {
if (gzip.isFile() && !org.apache.commons.io.FileUtils.deleteQuietly(gzip)) {
LOGGER.debug("Failed to delete temporary file when extracting 'gz' {}", gzip.toString());
gzip.deleteOnExit();
}
}
}
|
java
|
public static void extractGzip(File file) throws FileNotFoundException, IOException {
final String originalPath = file.getPath();
final File gzip = new File(originalPath + ".gz");
if (gzip.isFile() && !gzip.delete()) {
LOGGER.debug("Failed to delete initial temporary file when extracting 'gz' {}", gzip.toString());
gzip.deleteOnExit();
}
if (!file.renameTo(gzip)) {
throw new IOException("Unable to rename '" + file.getPath() + "'");
}
final File newFile = new File(originalPath);
try (FileInputStream fis = new FileInputStream(gzip);
GZIPInputStream cin = new GZIPInputStream(fis);
FileOutputStream out = new FileOutputStream(newFile)) {
IOUtils.copy(cin, out);
} finally {
if (gzip.isFile() && !org.apache.commons.io.FileUtils.deleteQuietly(gzip)) {
LOGGER.debug("Failed to delete temporary file when extracting 'gz' {}", gzip.toString());
gzip.deleteOnExit();
}
}
}
|
[
"public",
"static",
"void",
"extractGzip",
"(",
"File",
"file",
")",
"throws",
"FileNotFoundException",
",",
"IOException",
"{",
"final",
"String",
"originalPath",
"=",
"file",
".",
"getPath",
"(",
")",
";",
"final",
"File",
"gzip",
"=",
"new",
"File",
"(",
"originalPath",
"+",
"\".gz\"",
")",
";",
"if",
"(",
"gzip",
".",
"isFile",
"(",
")",
"&&",
"!",
"gzip",
".",
"delete",
"(",
")",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"Failed to delete initial temporary file when extracting 'gz' {}\"",
",",
"gzip",
".",
"toString",
"(",
")",
")",
";",
"gzip",
".",
"deleteOnExit",
"(",
")",
";",
"}",
"if",
"(",
"!",
"file",
".",
"renameTo",
"(",
"gzip",
")",
")",
"{",
"throw",
"new",
"IOException",
"(",
"\"Unable to rename '\"",
"+",
"file",
".",
"getPath",
"(",
")",
"+",
"\"'\"",
")",
";",
"}",
"final",
"File",
"newFile",
"=",
"new",
"File",
"(",
"originalPath",
")",
";",
"try",
"(",
"FileInputStream",
"fis",
"=",
"new",
"FileInputStream",
"(",
"gzip",
")",
";",
"GZIPInputStream",
"cin",
"=",
"new",
"GZIPInputStream",
"(",
"fis",
")",
";",
"FileOutputStream",
"out",
"=",
"new",
"FileOutputStream",
"(",
"newFile",
")",
")",
"{",
"IOUtils",
".",
"copy",
"(",
"cin",
",",
"out",
")",
";",
"}",
"finally",
"{",
"if",
"(",
"gzip",
".",
"isFile",
"(",
")",
"&&",
"!",
"org",
".",
"apache",
".",
"commons",
".",
"io",
".",
"FileUtils",
".",
"deleteQuietly",
"(",
"gzip",
")",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"Failed to delete temporary file when extracting 'gz' {}\"",
",",
"gzip",
".",
"toString",
"(",
")",
")",
";",
"gzip",
".",
"deleteOnExit",
"(",
")",
";",
"}",
"}",
"}"
] |
Extracts the file contained in a gzip archive. The extracted file is
placed in the exact same path as the file specified.
@param file the archive file
@throws FileNotFoundException thrown if the file does not exist
@throws IOException thrown if there is an error extracting the file.
|
[
"Extracts",
"the",
"file",
"contained",
"in",
"a",
"gzip",
"archive",
".",
"The",
"extracted",
"file",
"is",
"placed",
"in",
"the",
"exact",
"same",
"path",
"as",
"the",
"file",
"specified",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/utils/ExtractionUtil.java#L335-L356
|
17,786
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/utils/ExtractionUtil.java
|
ExtractionUtil.extractZip
|
public static void extractZip(File file) throws FileNotFoundException, IOException {
final String originalPath = file.getPath();
final File zip = new File(originalPath + ".zip");
if (zip.isFile() && !zip.delete()) {
LOGGER.debug("Failed to delete initial temporary file when extracting 'zip' {}", zip.toString());
zip.deleteOnExit();
}
if (!file.renameTo(zip)) {
throw new IOException("Unable to rename '" + file.getPath() + "'");
}
final File newFile = new File(originalPath);
try (FileInputStream fis = new FileInputStream(zip);
ZipInputStream cin = new ZipInputStream(fis);
FileOutputStream out = new FileOutputStream(newFile)) {
cin.getNextEntry();
IOUtils.copy(cin, out);
} finally {
if (zip.isFile() && !org.apache.commons.io.FileUtils.deleteQuietly(zip)) {
LOGGER.debug("Failed to delete temporary file when extracting 'zip' {}", zip.toString());
zip.deleteOnExit();
}
}
}
|
java
|
public static void extractZip(File file) throws FileNotFoundException, IOException {
final String originalPath = file.getPath();
final File zip = new File(originalPath + ".zip");
if (zip.isFile() && !zip.delete()) {
LOGGER.debug("Failed to delete initial temporary file when extracting 'zip' {}", zip.toString());
zip.deleteOnExit();
}
if (!file.renameTo(zip)) {
throw new IOException("Unable to rename '" + file.getPath() + "'");
}
final File newFile = new File(originalPath);
try (FileInputStream fis = new FileInputStream(zip);
ZipInputStream cin = new ZipInputStream(fis);
FileOutputStream out = new FileOutputStream(newFile)) {
cin.getNextEntry();
IOUtils.copy(cin, out);
} finally {
if (zip.isFile() && !org.apache.commons.io.FileUtils.deleteQuietly(zip)) {
LOGGER.debug("Failed to delete temporary file when extracting 'zip' {}", zip.toString());
zip.deleteOnExit();
}
}
}
|
[
"public",
"static",
"void",
"extractZip",
"(",
"File",
"file",
")",
"throws",
"FileNotFoundException",
",",
"IOException",
"{",
"final",
"String",
"originalPath",
"=",
"file",
".",
"getPath",
"(",
")",
";",
"final",
"File",
"zip",
"=",
"new",
"File",
"(",
"originalPath",
"+",
"\".zip\"",
")",
";",
"if",
"(",
"zip",
".",
"isFile",
"(",
")",
"&&",
"!",
"zip",
".",
"delete",
"(",
")",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"Failed to delete initial temporary file when extracting 'zip' {}\"",
",",
"zip",
".",
"toString",
"(",
")",
")",
";",
"zip",
".",
"deleteOnExit",
"(",
")",
";",
"}",
"if",
"(",
"!",
"file",
".",
"renameTo",
"(",
"zip",
")",
")",
"{",
"throw",
"new",
"IOException",
"(",
"\"Unable to rename '\"",
"+",
"file",
".",
"getPath",
"(",
")",
"+",
"\"'\"",
")",
";",
"}",
"final",
"File",
"newFile",
"=",
"new",
"File",
"(",
"originalPath",
")",
";",
"try",
"(",
"FileInputStream",
"fis",
"=",
"new",
"FileInputStream",
"(",
"zip",
")",
";",
"ZipInputStream",
"cin",
"=",
"new",
"ZipInputStream",
"(",
"fis",
")",
";",
"FileOutputStream",
"out",
"=",
"new",
"FileOutputStream",
"(",
"newFile",
")",
")",
"{",
"cin",
".",
"getNextEntry",
"(",
")",
";",
"IOUtils",
".",
"copy",
"(",
"cin",
",",
"out",
")",
";",
"}",
"finally",
"{",
"if",
"(",
"zip",
".",
"isFile",
"(",
")",
"&&",
"!",
"org",
".",
"apache",
".",
"commons",
".",
"io",
".",
"FileUtils",
".",
"deleteQuietly",
"(",
"zip",
")",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"Failed to delete temporary file when extracting 'zip' {}\"",
",",
"zip",
".",
"toString",
"(",
")",
")",
";",
"zip",
".",
"deleteOnExit",
"(",
")",
";",
"}",
"}",
"}"
] |
Extracts the file contained in a Zip archive. The extracted file is
placed in the exact same path as the file specified.
@param file the archive file
@throws FileNotFoundException thrown if the file does not exist
@throws IOException thrown if there is an error extracting the file.
|
[
"Extracts",
"the",
"file",
"contained",
"in",
"a",
"Zip",
"archive",
".",
"The",
"extracted",
"file",
"is",
"placed",
"in",
"the",
"exact",
"same",
"path",
"as",
"the",
"file",
"specified",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/utils/ExtractionUtil.java#L366-L388
|
17,787
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/data/nuget/XPathMSBuildProjectParser.java
|
XPathMSBuildProjectParser.parse
|
@Override
public List<NugetPackageReference> parse(InputStream stream) throws MSBuildProjectParseException {
try {
final DocumentBuilder db = XmlUtils.buildSecureDocumentBuilder();
final Document d = db.parse(stream);
final XPath xpath = XPathFactory.newInstance().newXPath();
final List<NugetPackageReference> packages = new ArrayList<>();
final NodeList nodeList = (NodeList) xpath.evaluate("//PackageReference", d, XPathConstants.NODESET);
if (nodeList == null) {
throw new MSBuildProjectParseException("Unable to parse MSBuild project file");
}
for (int i = 0; i < nodeList.getLength(); i++) {
final Node node = nodeList.item(i);
final NamedNodeMap attrs = node.getAttributes();
final Node include = attrs.getNamedItem("Include");
final Node version = attrs.getNamedItem("Version");
if (include != null && version != null) {
final NugetPackageReference npr = new NugetPackageReference();
npr.setId(include.getNodeValue());
npr.setVersion(version.getNodeValue());
packages.add(npr);
}
}
return packages;
} catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException | MSBuildProjectParseException e) {
throw new MSBuildProjectParseException("Unable to parse MSBuild project file", e);
}
}
|
java
|
@Override
public List<NugetPackageReference> parse(InputStream stream) throws MSBuildProjectParseException {
try {
final DocumentBuilder db = XmlUtils.buildSecureDocumentBuilder();
final Document d = db.parse(stream);
final XPath xpath = XPathFactory.newInstance().newXPath();
final List<NugetPackageReference> packages = new ArrayList<>();
final NodeList nodeList = (NodeList) xpath.evaluate("//PackageReference", d, XPathConstants.NODESET);
if (nodeList == null) {
throw new MSBuildProjectParseException("Unable to parse MSBuild project file");
}
for (int i = 0; i < nodeList.getLength(); i++) {
final Node node = nodeList.item(i);
final NamedNodeMap attrs = node.getAttributes();
final Node include = attrs.getNamedItem("Include");
final Node version = attrs.getNamedItem("Version");
if (include != null && version != null) {
final NugetPackageReference npr = new NugetPackageReference();
npr.setId(include.getNodeValue());
npr.setVersion(version.getNodeValue());
packages.add(npr);
}
}
return packages;
} catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException | MSBuildProjectParseException e) {
throw new MSBuildProjectParseException("Unable to parse MSBuild project file", e);
}
}
|
[
"@",
"Override",
"public",
"List",
"<",
"NugetPackageReference",
">",
"parse",
"(",
"InputStream",
"stream",
")",
"throws",
"MSBuildProjectParseException",
"{",
"try",
"{",
"final",
"DocumentBuilder",
"db",
"=",
"XmlUtils",
".",
"buildSecureDocumentBuilder",
"(",
")",
";",
"final",
"Document",
"d",
"=",
"db",
".",
"parse",
"(",
"stream",
")",
";",
"final",
"XPath",
"xpath",
"=",
"XPathFactory",
".",
"newInstance",
"(",
")",
".",
"newXPath",
"(",
")",
";",
"final",
"List",
"<",
"NugetPackageReference",
">",
"packages",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"final",
"NodeList",
"nodeList",
"=",
"(",
"NodeList",
")",
"xpath",
".",
"evaluate",
"(",
"\"//PackageReference\"",
",",
"d",
",",
"XPathConstants",
".",
"NODESET",
")",
";",
"if",
"(",
"nodeList",
"==",
"null",
")",
"{",
"throw",
"new",
"MSBuildProjectParseException",
"(",
"\"Unable to parse MSBuild project file\"",
")",
";",
"}",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"nodeList",
".",
"getLength",
"(",
")",
";",
"i",
"++",
")",
"{",
"final",
"Node",
"node",
"=",
"nodeList",
".",
"item",
"(",
"i",
")",
";",
"final",
"NamedNodeMap",
"attrs",
"=",
"node",
".",
"getAttributes",
"(",
")",
";",
"final",
"Node",
"include",
"=",
"attrs",
".",
"getNamedItem",
"(",
"\"Include\"",
")",
";",
"final",
"Node",
"version",
"=",
"attrs",
".",
"getNamedItem",
"(",
"\"Version\"",
")",
";",
"if",
"(",
"include",
"!=",
"null",
"&&",
"version",
"!=",
"null",
")",
"{",
"final",
"NugetPackageReference",
"npr",
"=",
"new",
"NugetPackageReference",
"(",
")",
";",
"npr",
".",
"setId",
"(",
"include",
".",
"getNodeValue",
"(",
")",
")",
";",
"npr",
".",
"setVersion",
"(",
"version",
".",
"getNodeValue",
"(",
")",
")",
";",
"packages",
".",
"add",
"(",
"npr",
")",
";",
"}",
"}",
"return",
"packages",
";",
"}",
"catch",
"(",
"ParserConfigurationException",
"|",
"SAXException",
"|",
"IOException",
"|",
"XPathExpressionException",
"|",
"MSBuildProjectParseException",
"e",
")",
"{",
"throw",
"new",
"MSBuildProjectParseException",
"(",
"\"Unable to parse MSBuild project file\"",
",",
"e",
")",
";",
"}",
"}"
] |
Parses the given stream for MSBuild PackageReference elements.
@param stream the input stream to parse
@return a collection of discovered NuGet package references
@throws MSBuildProjectParseException if an exception occurs
|
[
"Parses",
"the",
"given",
"stream",
"for",
"MSBuild",
"PackageReference",
"elements",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/data/nuget/XPathMSBuildProjectParser.java#L52-L88
|
17,788
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/analyzer/OpenSSLAnalyzer.java
|
OpenSSLAnalyzer.getOpenSSLVersion
|
protected static String getOpenSSLVersion(long openSSLVersionConstant) {
final long major = openSSLVersionConstant >>> MAJOR_OFFSET;
final long minor = (openSSLVersionConstant & MINOR_MASK) >>> MINOR_OFFSET;
final long fix = (openSSLVersionConstant & FIX_MASK) >>> FIX_OFFSET;
final long patchLevel = (openSSLVersionConstant & PATCH_MASK) >>> PATCH_OFFSET;
final String patch = 0 == patchLevel || patchLevel > NUM_LETTERS ? "" : String.valueOf((char) (patchLevel + 'a' - 1));
final int statusCode = (int) (openSSLVersionConstant & STATUS_MASK);
final String status = 0xf == statusCode ? "" : (0 == statusCode ? "-dev" : "-beta" + statusCode);
return String.format("%d.%d.%d%s%s", major, minor, fix, patch, status);
}
|
java
|
protected static String getOpenSSLVersion(long openSSLVersionConstant) {
final long major = openSSLVersionConstant >>> MAJOR_OFFSET;
final long minor = (openSSLVersionConstant & MINOR_MASK) >>> MINOR_OFFSET;
final long fix = (openSSLVersionConstant & FIX_MASK) >>> FIX_OFFSET;
final long patchLevel = (openSSLVersionConstant & PATCH_MASK) >>> PATCH_OFFSET;
final String patch = 0 == patchLevel || patchLevel > NUM_LETTERS ? "" : String.valueOf((char) (patchLevel + 'a' - 1));
final int statusCode = (int) (openSSLVersionConstant & STATUS_MASK);
final String status = 0xf == statusCode ? "" : (0 == statusCode ? "-dev" : "-beta" + statusCode);
return String.format("%d.%d.%d%s%s", major, minor, fix, patch, status);
}
|
[
"protected",
"static",
"String",
"getOpenSSLVersion",
"(",
"long",
"openSSLVersionConstant",
")",
"{",
"final",
"long",
"major",
"=",
"openSSLVersionConstant",
">>>",
"MAJOR_OFFSET",
";",
"final",
"long",
"minor",
"=",
"(",
"openSSLVersionConstant",
"&",
"MINOR_MASK",
")",
">>>",
"MINOR_OFFSET",
";",
"final",
"long",
"fix",
"=",
"(",
"openSSLVersionConstant",
"&",
"FIX_MASK",
")",
">>>",
"FIX_OFFSET",
";",
"final",
"long",
"patchLevel",
"=",
"(",
"openSSLVersionConstant",
"&",
"PATCH_MASK",
")",
">>>",
"PATCH_OFFSET",
";",
"final",
"String",
"patch",
"=",
"0",
"==",
"patchLevel",
"||",
"patchLevel",
">",
"NUM_LETTERS",
"?",
"\"\"",
":",
"String",
".",
"valueOf",
"(",
"(",
"char",
")",
"(",
"patchLevel",
"+",
"'",
"'",
"-",
"1",
")",
")",
";",
"final",
"int",
"statusCode",
"=",
"(",
"int",
")",
"(",
"openSSLVersionConstant",
"&",
"STATUS_MASK",
")",
";",
"final",
"String",
"status",
"=",
"0xf",
"==",
"statusCode",
"?",
"\"\"",
":",
"(",
"0",
"==",
"statusCode",
"?",
"\"-dev\"",
":",
"\"-beta\"",
"+",
"statusCode",
")",
";",
"return",
"String",
".",
"format",
"(",
"\"%d.%d.%d%s%s\"",
",",
"major",
",",
"minor",
",",
"fix",
",",
"patch",
",",
"status",
")",
";",
"}"
] |
Returns the open SSL version as a string.
@param openSSLVersionConstant The open SSL version
@return the version of openssl
|
[
"Returns",
"the",
"open",
"SSL",
"version",
"as",
"a",
"string",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/analyzer/OpenSSLAnalyzer.java#L119-L128
|
17,789
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/analyzer/OpenSSLAnalyzer.java
|
OpenSSLAnalyzer.getFileContents
|
private String getFileContents(final File actualFile)
throws AnalysisException {
try {
return FileUtils.readFileToString(actualFile, Charset.defaultCharset()).trim();
} catch (IOException e) {
throw new AnalysisException(
"Problem occurred while reading dependency file.", e);
}
}
|
java
|
private String getFileContents(final File actualFile)
throws AnalysisException {
try {
return FileUtils.readFileToString(actualFile, Charset.defaultCharset()).trim();
} catch (IOException e) {
throw new AnalysisException(
"Problem occurred while reading dependency file.", e);
}
}
|
[
"private",
"String",
"getFileContents",
"(",
"final",
"File",
"actualFile",
")",
"throws",
"AnalysisException",
"{",
"try",
"{",
"return",
"FileUtils",
".",
"readFileToString",
"(",
"actualFile",
",",
"Charset",
".",
"defaultCharset",
"(",
")",
")",
".",
"trim",
"(",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"throw",
"new",
"AnalysisException",
"(",
"\"Problem occurred while reading dependency file.\"",
",",
"e",
")",
";",
"}",
"}"
] |
Retrieves the contents of a given file.
@param actualFile the file to read
@return the contents of the file
@throws AnalysisException thrown if there is an IO Exception
|
[
"Retrieves",
"the",
"contents",
"of",
"a",
"given",
"file",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/analyzer/OpenSSLAnalyzer.java#L231-L239
|
17,790
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/data/nexus/NexusSearch.java
|
NexusSearch.preflightRequest
|
public boolean preflightRequest() {
final HttpURLConnection conn;
try {
final URL url = new URL(rootURL, "status");
final URLConnectionFactory factory = new URLConnectionFactory(settings);
conn = factory.createHttpURLConnection(url, useProxy);
conn.addRequestProperty("Accept", "application/xml");
final String authHeader = buildHttpAuthHeaderValue();
if (!authHeader.isEmpty()) {
conn.addRequestProperty("Authorization", authHeader);
}
conn.connect();
if (conn.getResponseCode() != 200) {
LOGGER.warn("Expected 200 result from Nexus, got {}", conn.getResponseCode());
return false;
}
final DocumentBuilder builder = XmlUtils.buildSecureDocumentBuilder();
final Document doc = builder.parse(conn.getInputStream());
if (!"status".equals(doc.getDocumentElement().getNodeName())) {
LOGGER.warn("Expected root node name of status, got {}", doc.getDocumentElement().getNodeName());
return false;
}
} catch (IOException | ParserConfigurationException | SAXException e) {
return false;
}
return true;
}
|
java
|
public boolean preflightRequest() {
final HttpURLConnection conn;
try {
final URL url = new URL(rootURL, "status");
final URLConnectionFactory factory = new URLConnectionFactory(settings);
conn = factory.createHttpURLConnection(url, useProxy);
conn.addRequestProperty("Accept", "application/xml");
final String authHeader = buildHttpAuthHeaderValue();
if (!authHeader.isEmpty()) {
conn.addRequestProperty("Authorization", authHeader);
}
conn.connect();
if (conn.getResponseCode() != 200) {
LOGGER.warn("Expected 200 result from Nexus, got {}", conn.getResponseCode());
return false;
}
final DocumentBuilder builder = XmlUtils.buildSecureDocumentBuilder();
final Document doc = builder.parse(conn.getInputStream());
if (!"status".equals(doc.getDocumentElement().getNodeName())) {
LOGGER.warn("Expected root node name of status, got {}", doc.getDocumentElement().getNodeName());
return false;
}
} catch (IOException | ParserConfigurationException | SAXException e) {
return false;
}
return true;
}
|
[
"public",
"boolean",
"preflightRequest",
"(",
")",
"{",
"final",
"HttpURLConnection",
"conn",
";",
"try",
"{",
"final",
"URL",
"url",
"=",
"new",
"URL",
"(",
"rootURL",
",",
"\"status\"",
")",
";",
"final",
"URLConnectionFactory",
"factory",
"=",
"new",
"URLConnectionFactory",
"(",
"settings",
")",
";",
"conn",
"=",
"factory",
".",
"createHttpURLConnection",
"(",
"url",
",",
"useProxy",
")",
";",
"conn",
".",
"addRequestProperty",
"(",
"\"Accept\"",
",",
"\"application/xml\"",
")",
";",
"final",
"String",
"authHeader",
"=",
"buildHttpAuthHeaderValue",
"(",
")",
";",
"if",
"(",
"!",
"authHeader",
".",
"isEmpty",
"(",
")",
")",
"{",
"conn",
".",
"addRequestProperty",
"(",
"\"Authorization\"",
",",
"authHeader",
")",
";",
"}",
"conn",
".",
"connect",
"(",
")",
";",
"if",
"(",
"conn",
".",
"getResponseCode",
"(",
")",
"!=",
"200",
")",
"{",
"LOGGER",
".",
"warn",
"(",
"\"Expected 200 result from Nexus, got {}\"",
",",
"conn",
".",
"getResponseCode",
"(",
")",
")",
";",
"return",
"false",
";",
"}",
"final",
"DocumentBuilder",
"builder",
"=",
"XmlUtils",
".",
"buildSecureDocumentBuilder",
"(",
")",
";",
"final",
"Document",
"doc",
"=",
"builder",
".",
"parse",
"(",
"conn",
".",
"getInputStream",
"(",
")",
")",
";",
"if",
"(",
"!",
"\"status\"",
".",
"equals",
"(",
"doc",
".",
"getDocumentElement",
"(",
")",
".",
"getNodeName",
"(",
")",
")",
")",
"{",
"LOGGER",
".",
"warn",
"(",
"\"Expected root node name of status, got {}\"",
",",
"doc",
".",
"getDocumentElement",
"(",
")",
".",
"getNodeName",
"(",
")",
")",
";",
"return",
"false",
";",
"}",
"}",
"catch",
"(",
"IOException",
"|",
"ParserConfigurationException",
"|",
"SAXException",
"e",
")",
"{",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}"
] |
Do a preflight request to see if the repository is actually working.
@return whether the repository is listening and returns the /status URL
correctly
|
[
"Do",
"a",
"preflight",
"request",
"to",
"see",
"if",
"the",
"repository",
"is",
"actually",
"working",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/data/nexus/NexusSearch.java#L177-L204
|
17,791
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/data/nexus/NexusSearch.java
|
NexusSearch.buildHttpAuthHeaderValue
|
private String buildHttpAuthHeaderValue() {
final String user = settings.getString(Settings.KEYS.ANALYZER_NEXUS_USER, "");
final String pass = settings.getString(Settings.KEYS.ANALYZER_NEXUS_PASSWORD, "");
String result = "";
if (user.isEmpty() || pass.isEmpty()) {
LOGGER.debug("Skip authentication as user and/or password for nexus is empty");
} else {
final String auth = user + ':' + pass;
final String base64Auth = Base64.getEncoder().encodeToString(auth.getBytes(StandardCharsets.UTF_8));
result = new StringBuilder("Basic ").append(base64Auth).toString();
}
return result;
}
|
java
|
private String buildHttpAuthHeaderValue() {
final String user = settings.getString(Settings.KEYS.ANALYZER_NEXUS_USER, "");
final String pass = settings.getString(Settings.KEYS.ANALYZER_NEXUS_PASSWORD, "");
String result = "";
if (user.isEmpty() || pass.isEmpty()) {
LOGGER.debug("Skip authentication as user and/or password for nexus is empty");
} else {
final String auth = user + ':' + pass;
final String base64Auth = Base64.getEncoder().encodeToString(auth.getBytes(StandardCharsets.UTF_8));
result = new StringBuilder("Basic ").append(base64Auth).toString();
}
return result;
}
|
[
"private",
"String",
"buildHttpAuthHeaderValue",
"(",
")",
"{",
"final",
"String",
"user",
"=",
"settings",
".",
"getString",
"(",
"Settings",
".",
"KEYS",
".",
"ANALYZER_NEXUS_USER",
",",
"\"\"",
")",
";",
"final",
"String",
"pass",
"=",
"settings",
".",
"getString",
"(",
"Settings",
".",
"KEYS",
".",
"ANALYZER_NEXUS_PASSWORD",
",",
"\"\"",
")",
";",
"String",
"result",
"=",
"\"\"",
";",
"if",
"(",
"user",
".",
"isEmpty",
"(",
")",
"||",
"pass",
".",
"isEmpty",
"(",
")",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"Skip authentication as user and/or password for nexus is empty\"",
")",
";",
"}",
"else",
"{",
"final",
"String",
"auth",
"=",
"user",
"+",
"'",
"'",
"+",
"pass",
";",
"final",
"String",
"base64Auth",
"=",
"Base64",
".",
"getEncoder",
"(",
")",
".",
"encodeToString",
"(",
"auth",
".",
"getBytes",
"(",
"StandardCharsets",
".",
"UTF_8",
")",
")",
";",
"result",
"=",
"new",
"StringBuilder",
"(",
"\"Basic \"",
")",
".",
"append",
"(",
"base64Auth",
")",
".",
"toString",
"(",
")",
";",
"}",
"return",
"result",
";",
"}"
] |
Constructs the base64 encoded basic authentication header value.
@return the base64 encoded basic authentication header value
|
[
"Constructs",
"the",
"base64",
"encoded",
"basic",
"authentication",
"header",
"value",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/data/nexus/NexusSearch.java#L211-L223
|
17,792
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/analyzer/OssIndexAnalyzer.java
|
OssIndexAnalyzer.parsePackageUrl
|
@Nullable
private PackageUrl parsePackageUrl(final String value) {
try {
return PackageUrl.parse(value);
} catch (PackageUrl.InvalidException e) {
log.warn("Invalid Package-URL: {}", value, e);
return null;
}
}
|
java
|
@Nullable
private PackageUrl parsePackageUrl(final String value) {
try {
return PackageUrl.parse(value);
} catch (PackageUrl.InvalidException e) {
log.warn("Invalid Package-URL: {}", value, e);
return null;
}
}
|
[
"@",
"Nullable",
"private",
"PackageUrl",
"parsePackageUrl",
"(",
"final",
"String",
"value",
")",
"{",
"try",
"{",
"return",
"PackageUrl",
".",
"parse",
"(",
"value",
")",
";",
"}",
"catch",
"(",
"PackageUrl",
".",
"InvalidException",
"e",
")",
"{",
"log",
".",
"warn",
"(",
"\"Invalid Package-URL: {}\"",
",",
"value",
",",
"e",
")",
";",
"return",
"null",
";",
"}",
"}"
] |
Helper to complain if unable to parse Package-URL.
|
[
"Helper",
"to",
"complain",
"if",
"unable",
"to",
"parse",
"Package",
"-",
"URL",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/analyzer/OssIndexAnalyzer.java#L138-L146
|
17,793
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/analyzer/OssIndexAnalyzer.java
|
OssIndexAnalyzer.requestReports
|
private Map<PackageUrl, ComponentReport> requestReports(final Dependency[] dependencies) throws Exception {
log.debug("Requesting component-reports for {} dependencies", dependencies.length);
// create requests for each dependency which has a PURL identifier
List<PackageUrl> packages = new ArrayList<>();
for (Dependency dependency : dependencies) {
for (Identifier id : dependency.getSoftwareIdentifiers()) {
if (id instanceof PurlIdentifier) {
PackageUrl purl = parsePackageUrl(id.getValue());
if (purl != null) {
packages.add(purl);
}
}
}
}
// only attempt if we have been able to collect some packages
if (!packages.isEmpty()) {
return client.requestComponentReports(packages);
}
log.warn("Unable to determine Package-URL identifiers for {} dependencies", dependencies.length);
return Collections.emptyMap();
}
|
java
|
private Map<PackageUrl, ComponentReport> requestReports(final Dependency[] dependencies) throws Exception {
log.debug("Requesting component-reports for {} dependencies", dependencies.length);
// create requests for each dependency which has a PURL identifier
List<PackageUrl> packages = new ArrayList<>();
for (Dependency dependency : dependencies) {
for (Identifier id : dependency.getSoftwareIdentifiers()) {
if (id instanceof PurlIdentifier) {
PackageUrl purl = parsePackageUrl(id.getValue());
if (purl != null) {
packages.add(purl);
}
}
}
}
// only attempt if we have been able to collect some packages
if (!packages.isEmpty()) {
return client.requestComponentReports(packages);
}
log.warn("Unable to determine Package-URL identifiers for {} dependencies", dependencies.length);
return Collections.emptyMap();
}
|
[
"private",
"Map",
"<",
"PackageUrl",
",",
"ComponentReport",
">",
"requestReports",
"(",
"final",
"Dependency",
"[",
"]",
"dependencies",
")",
"throws",
"Exception",
"{",
"log",
".",
"debug",
"(",
"\"Requesting component-reports for {} dependencies\"",
",",
"dependencies",
".",
"length",
")",
";",
"// create requests for each dependency which has a PURL identifier",
"List",
"<",
"PackageUrl",
">",
"packages",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"for",
"(",
"Dependency",
"dependency",
":",
"dependencies",
")",
"{",
"for",
"(",
"Identifier",
"id",
":",
"dependency",
".",
"getSoftwareIdentifiers",
"(",
")",
")",
"{",
"if",
"(",
"id",
"instanceof",
"PurlIdentifier",
")",
"{",
"PackageUrl",
"purl",
"=",
"parsePackageUrl",
"(",
"id",
".",
"getValue",
"(",
")",
")",
";",
"if",
"(",
"purl",
"!=",
"null",
")",
"{",
"packages",
".",
"add",
"(",
"purl",
")",
";",
"}",
"}",
"}",
"}",
"// only attempt if we have been able to collect some packages",
"if",
"(",
"!",
"packages",
".",
"isEmpty",
"(",
")",
")",
"{",
"return",
"client",
".",
"requestComponentReports",
"(",
"packages",
")",
";",
"}",
"log",
".",
"warn",
"(",
"\"Unable to determine Package-URL identifiers for {} dependencies\"",
",",
"dependencies",
".",
"length",
")",
";",
"return",
"Collections",
".",
"emptyMap",
"(",
")",
";",
"}"
] |
Batch request component-reports for all dependencies.
|
[
"Batch",
"request",
"component",
"-",
"reports",
"for",
"all",
"dependencies",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/analyzer/OssIndexAnalyzer.java#L151-L174
|
17,794
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/analyzer/OssIndexAnalyzer.java
|
OssIndexAnalyzer.enrich
|
private void enrich(final Dependency dependency) {
log.debug("Enrich dependency: {}", dependency);
for (Identifier id : dependency.getSoftwareIdentifiers()) {
if (id instanceof PurlIdentifier) {
log.debug(" Package: {} -> {}", id, id.getConfidence());
PackageUrl purl = parsePackageUrl(id.getValue());
if (purl != null) {
try {
ComponentReport report = reports.get(purl);
if (report == null) {
throw new IllegalStateException("Missing component-report for: " + purl);
}
// expose the URL to the package details for report generation
id.setUrl(report.getReference().toString());
for (ComponentReportVulnerability vuln : report.getVulnerabilities()) {
Vulnerability v = transform(report, vuln);
Vulnerability existing = dependency.getVulnerabilities().stream().filter(e->e.getName().equals(v.getName())).findFirst().orElse(null);
if (existing!=null) {
//TODO - can we enhance anything other than the references?
existing.getReferences().addAll(v.getReferences());
} else {
dependency.addVulnerability(v);
}
}
} catch (Exception e) {
log.warn("Failed to fetch component-report for: {}", purl, e);
}
}
}
}
}
|
java
|
private void enrich(final Dependency dependency) {
log.debug("Enrich dependency: {}", dependency);
for (Identifier id : dependency.getSoftwareIdentifiers()) {
if (id instanceof PurlIdentifier) {
log.debug(" Package: {} -> {}", id, id.getConfidence());
PackageUrl purl = parsePackageUrl(id.getValue());
if (purl != null) {
try {
ComponentReport report = reports.get(purl);
if (report == null) {
throw new IllegalStateException("Missing component-report for: " + purl);
}
// expose the URL to the package details for report generation
id.setUrl(report.getReference().toString());
for (ComponentReportVulnerability vuln : report.getVulnerabilities()) {
Vulnerability v = transform(report, vuln);
Vulnerability existing = dependency.getVulnerabilities().stream().filter(e->e.getName().equals(v.getName())).findFirst().orElse(null);
if (existing!=null) {
//TODO - can we enhance anything other than the references?
existing.getReferences().addAll(v.getReferences());
} else {
dependency.addVulnerability(v);
}
}
} catch (Exception e) {
log.warn("Failed to fetch component-report for: {}", purl, e);
}
}
}
}
}
|
[
"private",
"void",
"enrich",
"(",
"final",
"Dependency",
"dependency",
")",
"{",
"log",
".",
"debug",
"(",
"\"Enrich dependency: {}\"",
",",
"dependency",
")",
";",
"for",
"(",
"Identifier",
"id",
":",
"dependency",
".",
"getSoftwareIdentifiers",
"(",
")",
")",
"{",
"if",
"(",
"id",
"instanceof",
"PurlIdentifier",
")",
"{",
"log",
".",
"debug",
"(",
"\" Package: {} -> {}\"",
",",
"id",
",",
"id",
".",
"getConfidence",
"(",
")",
")",
";",
"PackageUrl",
"purl",
"=",
"parsePackageUrl",
"(",
"id",
".",
"getValue",
"(",
")",
")",
";",
"if",
"(",
"purl",
"!=",
"null",
")",
"{",
"try",
"{",
"ComponentReport",
"report",
"=",
"reports",
".",
"get",
"(",
"purl",
")",
";",
"if",
"(",
"report",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"Missing component-report for: \"",
"+",
"purl",
")",
";",
"}",
"// expose the URL to the package details for report generation",
"id",
".",
"setUrl",
"(",
"report",
".",
"getReference",
"(",
")",
".",
"toString",
"(",
")",
")",
";",
"for",
"(",
"ComponentReportVulnerability",
"vuln",
":",
"report",
".",
"getVulnerabilities",
"(",
")",
")",
"{",
"Vulnerability",
"v",
"=",
"transform",
"(",
"report",
",",
"vuln",
")",
";",
"Vulnerability",
"existing",
"=",
"dependency",
".",
"getVulnerabilities",
"(",
")",
".",
"stream",
"(",
")",
".",
"filter",
"(",
"e",
"->",
"e",
".",
"getName",
"(",
")",
".",
"equals",
"(",
"v",
".",
"getName",
"(",
")",
")",
")",
".",
"findFirst",
"(",
")",
".",
"orElse",
"(",
"null",
")",
";",
"if",
"(",
"existing",
"!=",
"null",
")",
"{",
"//TODO - can we enhance anything other than the references?",
"existing",
".",
"getReferences",
"(",
")",
".",
"addAll",
"(",
"v",
".",
"getReferences",
"(",
")",
")",
";",
"}",
"else",
"{",
"dependency",
".",
"addVulnerability",
"(",
"v",
")",
";",
"}",
"}",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"log",
".",
"warn",
"(",
"\"Failed to fetch component-report for: {}\"",
",",
"purl",
",",
"e",
")",
";",
"}",
"}",
"}",
"}",
"}"
] |
Attempt to enrich given dependency with vulnerability details from OSS
Index component-report.
|
[
"Attempt",
"to",
"enrich",
"given",
"dependency",
"with",
"vulnerability",
"details",
"from",
"OSS",
"Index",
"component",
"-",
"report",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/analyzer/OssIndexAnalyzer.java#L180-L214
|
17,795
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/dependency/Dependency.java
|
Dependency.calculateChecksums
|
private void calculateChecksums(File file) {
try {
this.md5sum = Checksum.getMD5Checksum(file);
this.sha1sum = Checksum.getSHA1Checksum(file);
this.sha256sum = Checksum.getSHA256Checksum(file);
} catch (NoSuchAlgorithmException | IOException ex) {
LOGGER.debug(String.format("Unable to calculate checksums on %s", file), ex);
}
}
|
java
|
private void calculateChecksums(File file) {
try {
this.md5sum = Checksum.getMD5Checksum(file);
this.sha1sum = Checksum.getSHA1Checksum(file);
this.sha256sum = Checksum.getSHA256Checksum(file);
} catch (NoSuchAlgorithmException | IOException ex) {
LOGGER.debug(String.format("Unable to calculate checksums on %s", file), ex);
}
}
|
[
"private",
"void",
"calculateChecksums",
"(",
"File",
"file",
")",
"{",
"try",
"{",
"this",
".",
"md5sum",
"=",
"Checksum",
".",
"getMD5Checksum",
"(",
"file",
")",
";",
"this",
".",
"sha1sum",
"=",
"Checksum",
".",
"getSHA1Checksum",
"(",
"file",
")",
";",
"this",
".",
"sha256sum",
"=",
"Checksum",
".",
"getSHA256Checksum",
"(",
"file",
")",
";",
"}",
"catch",
"(",
"NoSuchAlgorithmException",
"|",
"IOException",
"ex",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"String",
".",
"format",
"(",
"\"Unable to calculate checksums on %s\"",
",",
"file",
")",
",",
"ex",
")",
";",
"}",
"}"
] |
Calculates the checksums for the given file.
@param file the file used to calculate the checksums
|
[
"Calculates",
"the",
"checksums",
"for",
"the",
"given",
"file",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/dependency/Dependency.java#L210-L218
|
17,796
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/dependency/Dependency.java
|
Dependency.setActualFilePath
|
public void setActualFilePath(String actualFilePath) {
this.actualFilePath = actualFilePath;
this.sha1sum = null;
this.sha256sum = null;
this.md5sum = null;
final File file = getActualFile();
if (file.isFile()) {
calculateChecksums(this.getActualFile());
}
}
|
java
|
public void setActualFilePath(String actualFilePath) {
this.actualFilePath = actualFilePath;
this.sha1sum = null;
this.sha256sum = null;
this.md5sum = null;
final File file = getActualFile();
if (file.isFile()) {
calculateChecksums(this.getActualFile());
}
}
|
[
"public",
"void",
"setActualFilePath",
"(",
"String",
"actualFilePath",
")",
"{",
"this",
".",
"actualFilePath",
"=",
"actualFilePath",
";",
"this",
".",
"sha1sum",
"=",
"null",
";",
"this",
".",
"sha256sum",
"=",
"null",
";",
"this",
".",
"md5sum",
"=",
"null",
";",
"final",
"File",
"file",
"=",
"getActualFile",
"(",
")",
";",
"if",
"(",
"file",
".",
"isFile",
"(",
")",
")",
"{",
"calculateChecksums",
"(",
"this",
".",
"getActualFile",
"(",
")",
")",
";",
"}",
"}"
] |
Sets the actual file path of the dependency on disk.
@param actualFilePath the file path of the dependency
|
[
"Sets",
"the",
"actual",
"file",
"path",
"of",
"the",
"dependency",
"on",
"disk",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/dependency/Dependency.java#L281-L290
|
17,797
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/dependency/Dependency.java
|
Dependency.getDisplayFileName
|
public String getDisplayFileName() {
if (displayName != null) {
return displayName;
}
if (!isVirtual) {
return fileName;
}
if (name == null) {
return fileName;
}
if (version == null) {
return name;
}
return name + ":" + version;
}
|
java
|
public String getDisplayFileName() {
if (displayName != null) {
return displayName;
}
if (!isVirtual) {
return fileName;
}
if (name == null) {
return fileName;
}
if (version == null) {
return name;
}
return name + ":" + version;
}
|
[
"public",
"String",
"getDisplayFileName",
"(",
")",
"{",
"if",
"(",
"displayName",
"!=",
"null",
")",
"{",
"return",
"displayName",
";",
"}",
"if",
"(",
"!",
"isVirtual",
")",
"{",
"return",
"fileName",
";",
"}",
"if",
"(",
"name",
"==",
"null",
")",
"{",
"return",
"fileName",
";",
"}",
"if",
"(",
"version",
"==",
"null",
")",
"{",
"return",
"name",
";",
"}",
"return",
"name",
"+",
"\":\"",
"+",
"version",
";",
"}"
] |
Returns the file name to display in reports; if no display file name has
been set it will default to constructing a name based on the name and
version fields, otherwise it will return the actual file name.
@return the file name to display
|
[
"Returns",
"the",
"file",
"name",
"to",
"display",
"in",
"reports",
";",
"if",
"no",
"display",
"file",
"name",
"has",
"been",
"set",
"it",
"will",
"default",
"to",
"constructing",
"a",
"name",
"based",
"on",
"the",
"name",
"and",
"version",
"fields",
"otherwise",
"it",
"will",
"return",
"the",
"actual",
"file",
"name",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/dependency/Dependency.java#L308-L322
|
17,798
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/dependency/Dependency.java
|
Dependency.addSoftwareIdentifier
|
public synchronized void addSoftwareIdentifier(Identifier identifier) {
//todo the following assertion should be removed after initial testing and implementation
assert !(identifier instanceof CpeIdentifier) : "vulnerability identifier cannot be added to software identifiers";
final Optional<Identifier> found = softwareIdentifiers.stream().filter(id
-> id.getValue().equals(identifier.getValue())).findFirst();
if (found.isPresent()) {
//TODO - should we check for type of identifier? I.e. could we see a Purl and GenericIdentifier with the same value
final Identifier existing = found.get();
if (existing.getConfidence().compareTo(identifier.getConfidence()) < 0) {
existing.setConfidence(identifier.getConfidence());
}
if (existing.getNotes() != null && identifier.getNotes() != null) {
existing.setNotes(existing.getNotes() + " " + identifier.getNotes());
} else if (identifier.getNotes() != null) {
existing.setNotes(identifier.getNotes());
}
if (existing.getUrl() == null && identifier.getUrl() != null) {
existing.setUrl(identifier.getUrl());
}
} else {
this.softwareIdentifiers.add(identifier);
}
}
|
java
|
public synchronized void addSoftwareIdentifier(Identifier identifier) {
//todo the following assertion should be removed after initial testing and implementation
assert !(identifier instanceof CpeIdentifier) : "vulnerability identifier cannot be added to software identifiers";
final Optional<Identifier> found = softwareIdentifiers.stream().filter(id
-> id.getValue().equals(identifier.getValue())).findFirst();
if (found.isPresent()) {
//TODO - should we check for type of identifier? I.e. could we see a Purl and GenericIdentifier with the same value
final Identifier existing = found.get();
if (existing.getConfidence().compareTo(identifier.getConfidence()) < 0) {
existing.setConfidence(identifier.getConfidence());
}
if (existing.getNotes() != null && identifier.getNotes() != null) {
existing.setNotes(existing.getNotes() + " " + identifier.getNotes());
} else if (identifier.getNotes() != null) {
existing.setNotes(identifier.getNotes());
}
if (existing.getUrl() == null && identifier.getUrl() != null) {
existing.setUrl(identifier.getUrl());
}
} else {
this.softwareIdentifiers.add(identifier);
}
}
|
[
"public",
"synchronized",
"void",
"addSoftwareIdentifier",
"(",
"Identifier",
"identifier",
")",
"{",
"//todo the following assertion should be removed after initial testing and implementation",
"assert",
"!",
"(",
"identifier",
"instanceof",
"CpeIdentifier",
")",
":",
"\"vulnerability identifier cannot be added to software identifiers\"",
";",
"final",
"Optional",
"<",
"Identifier",
">",
"found",
"=",
"softwareIdentifiers",
".",
"stream",
"(",
")",
".",
"filter",
"(",
"id",
"->",
"id",
".",
"getValue",
"(",
")",
".",
"equals",
"(",
"identifier",
".",
"getValue",
"(",
")",
")",
")",
".",
"findFirst",
"(",
")",
";",
"if",
"(",
"found",
".",
"isPresent",
"(",
")",
")",
"{",
"//TODO - should we check for type of identifier? I.e. could we see a Purl and GenericIdentifier with the same value",
"final",
"Identifier",
"existing",
"=",
"found",
".",
"get",
"(",
")",
";",
"if",
"(",
"existing",
".",
"getConfidence",
"(",
")",
".",
"compareTo",
"(",
"identifier",
".",
"getConfidence",
"(",
")",
")",
"<",
"0",
")",
"{",
"existing",
".",
"setConfidence",
"(",
"identifier",
".",
"getConfidence",
"(",
")",
")",
";",
"}",
"if",
"(",
"existing",
".",
"getNotes",
"(",
")",
"!=",
"null",
"&&",
"identifier",
".",
"getNotes",
"(",
")",
"!=",
"null",
")",
"{",
"existing",
".",
"setNotes",
"(",
"existing",
".",
"getNotes",
"(",
")",
"+",
"\" \"",
"+",
"identifier",
".",
"getNotes",
"(",
")",
")",
";",
"}",
"else",
"if",
"(",
"identifier",
".",
"getNotes",
"(",
")",
"!=",
"null",
")",
"{",
"existing",
".",
"setNotes",
"(",
"identifier",
".",
"getNotes",
"(",
")",
")",
";",
"}",
"if",
"(",
"existing",
".",
"getUrl",
"(",
")",
"==",
"null",
"&&",
"identifier",
".",
"getUrl",
"(",
")",
"!=",
"null",
")",
"{",
"existing",
".",
"setUrl",
"(",
"identifier",
".",
"getUrl",
"(",
")",
")",
";",
"}",
"}",
"else",
"{",
"this",
".",
"softwareIdentifiers",
".",
"add",
"(",
"identifier",
")",
";",
"}",
"}"
] |
Adds an entry to the list of detected Identifiers for the dependency
file.
@param identifier a reference to the identifier to add
|
[
"Adds",
"an",
"entry",
"to",
"the",
"list",
"of",
"detected",
"Identifiers",
"for",
"the",
"dependency",
"file",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/dependency/Dependency.java#L462-L485
|
17,799
|
jeremylong/DependencyCheck
|
core/src/main/java/org/owasp/dependencycheck/dependency/Dependency.java
|
Dependency.addAsEvidence
|
public void addAsEvidence(String source, MavenArtifact mavenArtifact, Confidence confidence) {
if (mavenArtifact.getGroupId() != null && !mavenArtifact.getGroupId().isEmpty()) {
this.addEvidence(EvidenceType.VENDOR, source, "groupid", mavenArtifact.getGroupId(), confidence);
}
if (mavenArtifact.getArtifactId() != null && !mavenArtifact.getArtifactId().isEmpty()) {
this.addEvidence(EvidenceType.PRODUCT, source, "artifactid", mavenArtifact.getArtifactId(), confidence);
}
if (mavenArtifact.getVersion() != null && !mavenArtifact.getVersion().isEmpty()) {
this.addEvidence(EvidenceType.VERSION, source, "version", mavenArtifact.getVersion(), confidence);
}
boolean found = false;
if (mavenArtifact.getArtifactUrl() != null && !mavenArtifact.getArtifactUrl().isEmpty()) {
synchronized (this) {
for (Identifier i : this.softwareIdentifiers) {
if (i instanceof PurlIdentifier) {
final PurlIdentifier id = (PurlIdentifier) i;
if (mavenArtifact.getArtifactId().equals(id.getName())
&& mavenArtifact.getGroupId().equals(id.getNamespace())) {
found = true;
i.setConfidence(Confidence.HIGHEST);
final String url = "http://search.maven.org/#search|ga|1|1%3A%22" + this.getSha1sum() + "%22";
i.setUrl(url);
//i.setUrl(mavenArtifact.getArtifactUrl());
LOGGER.debug("Already found identifier {}. Confidence set to highest", i.getValue());
break;
}
}
}
}
}
if (!found && mavenArtifact.getGroupId() != null && mavenArtifact.getArtifactId() != null && mavenArtifact.getVersion() != null) {
try {
LOGGER.debug("Adding new maven identifier {}", mavenArtifact);
final PackageURL p = new PackageURL("maven", mavenArtifact.getGroupId(),
mavenArtifact.getArtifactId(), mavenArtifact.getVersion(), null, null);
final PurlIdentifier id = new PurlIdentifier(p, Confidence.HIGHEST);
this.addSoftwareIdentifier(id);
} catch (MalformedPackageURLException ex) {
throw new UnexpectedAnalysisException(ex);
}
}
}
|
java
|
public void addAsEvidence(String source, MavenArtifact mavenArtifact, Confidence confidence) {
if (mavenArtifact.getGroupId() != null && !mavenArtifact.getGroupId().isEmpty()) {
this.addEvidence(EvidenceType.VENDOR, source, "groupid", mavenArtifact.getGroupId(), confidence);
}
if (mavenArtifact.getArtifactId() != null && !mavenArtifact.getArtifactId().isEmpty()) {
this.addEvidence(EvidenceType.PRODUCT, source, "artifactid", mavenArtifact.getArtifactId(), confidence);
}
if (mavenArtifact.getVersion() != null && !mavenArtifact.getVersion().isEmpty()) {
this.addEvidence(EvidenceType.VERSION, source, "version", mavenArtifact.getVersion(), confidence);
}
boolean found = false;
if (mavenArtifact.getArtifactUrl() != null && !mavenArtifact.getArtifactUrl().isEmpty()) {
synchronized (this) {
for (Identifier i : this.softwareIdentifiers) {
if (i instanceof PurlIdentifier) {
final PurlIdentifier id = (PurlIdentifier) i;
if (mavenArtifact.getArtifactId().equals(id.getName())
&& mavenArtifact.getGroupId().equals(id.getNamespace())) {
found = true;
i.setConfidence(Confidence.HIGHEST);
final String url = "http://search.maven.org/#search|ga|1|1%3A%22" + this.getSha1sum() + "%22";
i.setUrl(url);
//i.setUrl(mavenArtifact.getArtifactUrl());
LOGGER.debug("Already found identifier {}. Confidence set to highest", i.getValue());
break;
}
}
}
}
}
if (!found && mavenArtifact.getGroupId() != null && mavenArtifact.getArtifactId() != null && mavenArtifact.getVersion() != null) {
try {
LOGGER.debug("Adding new maven identifier {}", mavenArtifact);
final PackageURL p = new PackageURL("maven", mavenArtifact.getGroupId(),
mavenArtifact.getArtifactId(), mavenArtifact.getVersion(), null, null);
final PurlIdentifier id = new PurlIdentifier(p, Confidence.HIGHEST);
this.addSoftwareIdentifier(id);
} catch (MalformedPackageURLException ex) {
throw new UnexpectedAnalysisException(ex);
}
}
}
|
[
"public",
"void",
"addAsEvidence",
"(",
"String",
"source",
",",
"MavenArtifact",
"mavenArtifact",
",",
"Confidence",
"confidence",
")",
"{",
"if",
"(",
"mavenArtifact",
".",
"getGroupId",
"(",
")",
"!=",
"null",
"&&",
"!",
"mavenArtifact",
".",
"getGroupId",
"(",
")",
".",
"isEmpty",
"(",
")",
")",
"{",
"this",
".",
"addEvidence",
"(",
"EvidenceType",
".",
"VENDOR",
",",
"source",
",",
"\"groupid\"",
",",
"mavenArtifact",
".",
"getGroupId",
"(",
")",
",",
"confidence",
")",
";",
"}",
"if",
"(",
"mavenArtifact",
".",
"getArtifactId",
"(",
")",
"!=",
"null",
"&&",
"!",
"mavenArtifact",
".",
"getArtifactId",
"(",
")",
".",
"isEmpty",
"(",
")",
")",
"{",
"this",
".",
"addEvidence",
"(",
"EvidenceType",
".",
"PRODUCT",
",",
"source",
",",
"\"artifactid\"",
",",
"mavenArtifact",
".",
"getArtifactId",
"(",
")",
",",
"confidence",
")",
";",
"}",
"if",
"(",
"mavenArtifact",
".",
"getVersion",
"(",
")",
"!=",
"null",
"&&",
"!",
"mavenArtifact",
".",
"getVersion",
"(",
")",
".",
"isEmpty",
"(",
")",
")",
"{",
"this",
".",
"addEvidence",
"(",
"EvidenceType",
".",
"VERSION",
",",
"source",
",",
"\"version\"",
",",
"mavenArtifact",
".",
"getVersion",
"(",
")",
",",
"confidence",
")",
";",
"}",
"boolean",
"found",
"=",
"false",
";",
"if",
"(",
"mavenArtifact",
".",
"getArtifactUrl",
"(",
")",
"!=",
"null",
"&&",
"!",
"mavenArtifact",
".",
"getArtifactUrl",
"(",
")",
".",
"isEmpty",
"(",
")",
")",
"{",
"synchronized",
"(",
"this",
")",
"{",
"for",
"(",
"Identifier",
"i",
":",
"this",
".",
"softwareIdentifiers",
")",
"{",
"if",
"(",
"i",
"instanceof",
"PurlIdentifier",
")",
"{",
"final",
"PurlIdentifier",
"id",
"=",
"(",
"PurlIdentifier",
")",
"i",
";",
"if",
"(",
"mavenArtifact",
".",
"getArtifactId",
"(",
")",
".",
"equals",
"(",
"id",
".",
"getName",
"(",
")",
")",
"&&",
"mavenArtifact",
".",
"getGroupId",
"(",
")",
".",
"equals",
"(",
"id",
".",
"getNamespace",
"(",
")",
")",
")",
"{",
"found",
"=",
"true",
";",
"i",
".",
"setConfidence",
"(",
"Confidence",
".",
"HIGHEST",
")",
";",
"final",
"String",
"url",
"=",
"\"http://search.maven.org/#search|ga|1|1%3A%22\"",
"+",
"this",
".",
"getSha1sum",
"(",
")",
"+",
"\"%22\"",
";",
"i",
".",
"setUrl",
"(",
"url",
")",
";",
"//i.setUrl(mavenArtifact.getArtifactUrl());",
"LOGGER",
".",
"debug",
"(",
"\"Already found identifier {}. Confidence set to highest\"",
",",
"i",
".",
"getValue",
"(",
")",
")",
";",
"break",
";",
"}",
"}",
"}",
"}",
"}",
"if",
"(",
"!",
"found",
"&&",
"mavenArtifact",
".",
"getGroupId",
"(",
")",
"!=",
"null",
"&&",
"mavenArtifact",
".",
"getArtifactId",
"(",
")",
"!=",
"null",
"&&",
"mavenArtifact",
".",
"getVersion",
"(",
")",
"!=",
"null",
")",
"{",
"try",
"{",
"LOGGER",
".",
"debug",
"(",
"\"Adding new maven identifier {}\"",
",",
"mavenArtifact",
")",
";",
"final",
"PackageURL",
"p",
"=",
"new",
"PackageURL",
"(",
"\"maven\"",
",",
"mavenArtifact",
".",
"getGroupId",
"(",
")",
",",
"mavenArtifact",
".",
"getArtifactId",
"(",
")",
",",
"mavenArtifact",
".",
"getVersion",
"(",
")",
",",
"null",
",",
"null",
")",
";",
"final",
"PurlIdentifier",
"id",
"=",
"new",
"PurlIdentifier",
"(",
"p",
",",
"Confidence",
".",
"HIGHEST",
")",
";",
"this",
".",
"addSoftwareIdentifier",
"(",
"id",
")",
";",
"}",
"catch",
"(",
"MalformedPackageURLException",
"ex",
")",
"{",
"throw",
"new",
"UnexpectedAnalysisException",
"(",
"ex",
")",
";",
"}",
"}",
"}"
] |
Adds the Maven artifact as evidence.
@param source The source of the evidence
@param mavenArtifact The Maven artifact
@param confidence The confidence level of this evidence
|
[
"Adds",
"the",
"Maven",
"artifact",
"as",
"evidence",
"."
] |
6cc7690ea12e4ca1454210ceaa2e9a5523f0926c
|
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/dependency/Dependency.java#L513-L554
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.