updated to use try with resouces

This commit is contained in:
Jeremy Long
2017-03-12 13:22:27 -04:00
parent 626f6c3de2
commit 7a88981aa4
19 changed files with 111 additions and 479 deletions

View File

@@ -144,9 +144,8 @@ public class Purge extends Task {
*/ */
protected void populateSettings() throws BuildException { protected void populateSettings() throws BuildException {
Settings.initialize(); Settings.initialize();
InputStream taskProperties = null;
try { try (InputStream taskProperties = this.getClass().getClassLoader().getResourceAsStream(PROPERTIES_FILE)) {
taskProperties = this.getClass().getClassLoader().getResourceAsStream(PROPERTIES_FILE);
Settings.mergeProperties(taskProperties); Settings.mergeProperties(taskProperties);
} catch (IOException ex) { } catch (IOException ex) {
final String msg = "Unable to load the dependency-check ant task.properties file."; final String msg = "Unable to load the dependency-check ant task.properties file.";
@@ -154,14 +153,6 @@ public class Purge extends Task {
throw new BuildException(msg, ex); throw new BuildException(msg, ex);
} }
log(msg, ex, Project.MSG_WARN); log(msg, ex, Project.MSG_WARN);
} finally {
if (taskProperties != null) {
try {
taskProperties.close();
} catch (IOException ex) {
log("", ex, Project.MSG_DEBUG);
}
}
} }
if (dataDirectory != null) { if (dataDirectory != null) {
Settings.setString(Settings.KEYS.DATA_DIRECTORY, dataDirectory); Settings.setString(Settings.KEYS.DATA_DIRECTORY, dataDirectory);

View File

@@ -130,10 +130,9 @@ public abstract class AbstractSuppressionAnalyzer extends AbstractAnalyzer {
} }
} else { } else {
file = new File(suppressionFilePath); file = new File(suppressionFilePath);
InputStream suppressionsFromClasspath = null;
if (!file.exists()) { if (!file.exists()) {
try { try (InputStream suppressionsFromClasspath = this.getClass().getClassLoader().getResourceAsStream(suppressionFilePath)) {
suppressionsFromClasspath = this.getClass().getClassLoader().getResourceAsStream(suppressionFilePath);
if (suppressionsFromClasspath != null) { if (suppressionsFromClasspath != null) {
deleteTempFile = true; deleteTempFile = true;
file = FileUtils.getTempFile("suppression", "xml"); file = FileUtils.getTempFile("suppression", "xml");
@@ -143,14 +142,6 @@ public abstract class AbstractSuppressionAnalyzer extends AbstractAnalyzer {
throwSuppressionParseException("Unable to locate suppressions file in classpath", ex); throwSuppressionParseException("Unable to locate suppressions file in classpath", ex);
} }
} }
} finally {
if (suppressionsFromClasspath != null) {
try {
suppressionsFromClasspath.close();
} catch (IOException ex) {
LOGGER.debug("Failed to close stream", ex);
}
}
} }
} }
} }

View File

@@ -535,14 +535,12 @@ public class ArchiveAnalyzer extends AbstractFileTypeAnalyzer {
*/ */
private static void extractAcceptedFile(ArchiveInputStream input, File file) throws AnalysisException { private static void extractAcceptedFile(ArchiveInputStream input, File file) throws AnalysisException {
LOGGER.debug("Extracting '{}'", file.getPath()); LOGGER.debug("Extracting '{}'", file.getPath());
FileOutputStream fos = null; final File parent = file.getParentFile();
try { if (!parent.isDirectory() && !parent.mkdirs()) {
final File parent = file.getParentFile(); final String msg = String.format("Unable to build directory '%s'.", parent.getAbsolutePath());
if (!parent.isDirectory() && !parent.mkdirs()) { throw new AnalysisException(msg);
final String msg = String.format("Unable to build directory '%s'.", parent.getAbsolutePath()); }
throw new AnalysisException(msg); try (FileOutputStream fos = new FileOutputStream(file)) {
}
fos = new FileOutputStream(file);
IOUtils.copy(input, fos); IOUtils.copy(input, fos);
} catch (FileNotFoundException ex) { } catch (FileNotFoundException ex) {
LOGGER.debug("", ex); LOGGER.debug("", ex);
@@ -552,8 +550,6 @@ public class ArchiveAnalyzer extends AbstractFileTypeAnalyzer {
LOGGER.debug("", ex); LOGGER.debug("", ex);
final String msg = String.format("IO Exception while parsing file '%s'.", file.getName()); final String msg = String.format("IO Exception while parsing file '%s'.", file.getName());
throw new AnalysisException(msg, ex); throw new AnalysisException(msg, ex);
} finally {
FileUtils.close(fos);
} }
} }
@@ -567,15 +563,11 @@ public class ArchiveAnalyzer extends AbstractFileTypeAnalyzer {
*/ */
private void decompressFile(CompressorInputStream inputStream, File outputFile) throws ArchiveExtractionException { private void decompressFile(CompressorInputStream inputStream, File outputFile) throws ArchiveExtractionException {
LOGGER.debug("Decompressing '{}'", outputFile.getPath()); LOGGER.debug("Decompressing '{}'", outputFile.getPath());
FileOutputStream out = null; try (FileOutputStream out = new FileOutputStream(outputFile)) {
try {
out = new FileOutputStream(outputFile);
IOUtils.copy(inputStream, out); IOUtils.copy(inputStream, out);
} catch (IOException ex) { } catch (IOException ex) {
LOGGER.debug("", ex); LOGGER.debug("", ex);
throw new ArchiveExtractionException(ex); throw new ArchiveExtractionException(ex);
} finally {
FileUtils.close(out);
} }
} }
@@ -609,7 +601,6 @@ public class ArchiveAnalyzer extends AbstractFileTypeAnalyzer {
} finally { } finally {
ZipFile.closeQuietly(zip); ZipFile.closeQuietly(zip);
} }
return isJar; return isJar;
} }
} }

View File

@@ -178,7 +178,7 @@ public class AssemblyAnalyzer extends AbstractFileTypeAnalyzer {
throw new AnalysisException("Error initializing the assembly analyzer", pce); throw new AnalysisException("Error initializing the assembly analyzer", pce);
} catch (IOException | XPathExpressionException ioe) { } catch (IOException | XPathExpressionException ioe) {
throw new AnalysisException(ioe); throw new AnalysisException(ioe);
}catch (SAXException saxe) { } catch (SAXException saxe) {
LOGGER.error("----------------------------------------------------"); LOGGER.error("----------------------------------------------------");
LOGGER.error("Failed to read the Assembly Analyzer results. " LOGGER.error("Failed to read the Assembly Analyzer results. "
+ "On some systems mono-runtime and mono-devel need to be installed."); + "On some systems mono-runtime and mono-devel need to be installed.");
@@ -186,7 +186,7 @@ public class AssemblyAnalyzer extends AbstractFileTypeAnalyzer {
throw new AnalysisException("Couldn't parse Assembly Analyzer results (GrokAssembly)", saxe); throw new AnalysisException("Couldn't parse Assembly Analyzer results (GrokAssembly)", saxe);
} }
// This shouldn't happen // This shouldn't happen
} }
/** /**
@@ -198,46 +198,27 @@ public class AssemblyAnalyzer extends AbstractFileTypeAnalyzer {
@Override @Override
public void initializeFileTypeAnalyzer() throws InitializationException { public void initializeFileTypeAnalyzer() throws InitializationException {
final File tempFile; final File tempFile;
final String cfg;
try { try {
tempFile = File.createTempFile("GKA", ".exe", Settings.getTempDirectory()); tempFile = File.createTempFile("GKA", ".exe", Settings.getTempDirectory());
cfg = tempFile.getPath() + ".config";
} catch (IOException ex) { } catch (IOException ex) {
setEnabled(false); setEnabled(false);
throw new InitializationException("Unable to create temporary file for the assembly analyzer", ex); throw new InitializationException("Unable to create temporary file for the assembly analyzer", ex);
} }
FileOutputStream fos = null; try (FileOutputStream fos = new FileOutputStream(tempFile);
InputStream is = null; InputStream is = AssemblyAnalyzer.class.getClassLoader().getResourceAsStream("GrokAssembly.exe");
try { FileOutputStream fosCfg = new FileOutputStream(cfg);
fos = new FileOutputStream(tempFile); InputStream isCfg = AssemblyAnalyzer.class.getClassLoader().getResourceAsStream("GrokAssembly.exe.config")) {
is = AssemblyAnalyzer.class.getClassLoader().getResourceAsStream("GrokAssembly.exe");
IOUtils.copy(is, fos); IOUtils.copy(is, fos);
grokAssemblyExe = tempFile; grokAssemblyExe = tempFile;
LOGGER.debug("Extracted GrokAssembly.exe to {}", grokAssemblyExe.getPath()); LOGGER.debug("Extracted GrokAssembly.exe to {}", grokAssemblyExe.getPath());
IOUtils.copy(isCfg, fosCfg);
String cfg = grokAssemblyExe.getPath() + ".config";
fos = new FileOutputStream(cfg);
is = AssemblyAnalyzer.class.getClassLoader().getResourceAsStream("GrokAssembly.exe.config");
IOUtils.copy(is, fos);
LOGGER.debug("Extracted GrokAssembly.exe.config to {}", cfg); LOGGER.debug("Extracted GrokAssembly.exe.config to {}", cfg);
} catch (IOException ioe) { } catch (IOException ioe) {
this.setEnabled(false); this.setEnabled(false);
LOGGER.warn("Could not extract GrokAssembly.exe: {}", ioe.getMessage()); LOGGER.warn("Could not extract GrokAssembly.exe: {}", ioe.getMessage());
throw new InitializationException("Could not extract GrokAssembly.exe", ioe); throw new InitializationException("Could not extract GrokAssembly.exe", ioe);
} finally {
if (fos != null) {
try {
fos.close();
} catch (Throwable e) {
LOGGER.debug("Error closing output stream");
}
}
if (is != null) {
try {
is.close();
} catch (Throwable e) {
LOGGER.debug("Error closing input stream");
}
}
} }
// Now, need to see if GrokAssembly actually runs from this location. // Now, need to see if GrokAssembly actually runs from this location.

View File

@@ -34,6 +34,7 @@ import org.slf4j.LoggerFactory;
import java.io.FileFilter; import java.io.FileFilter;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.security.MessageDigest; import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
@@ -101,9 +102,7 @@ public class ComposerLockAnalyzer extends AbstractFileTypeAnalyzer {
*/ */
@Override @Override
protected void analyzeDependency(Dependency dependency, Engine engine) throws AnalysisException { protected void analyzeDependency(Dependency dependency, Engine engine) throws AnalysisException {
FileInputStream fis = null; try (FileInputStream fis = new FileInputStream(dependency.getActualFile())) {
try {
fis = new FileInputStream(dependency.getActualFile());
final ComposerLockParser clp = new ComposerLockParser(fis); final ComposerLockParser clp = new ComposerLockParser(fis);
LOGGER.info("Checking composer.lock file {}", dependency.getActualFilePath()); LOGGER.info("Checking composer.lock file {}", dependency.getActualFilePath());
clp.process(); clp.process();
@@ -120,18 +119,10 @@ public class ComposerLockAnalyzer extends AbstractFileTypeAnalyzer {
LOGGER.info("Adding dependency {}", d); LOGGER.info("Adding dependency {}", d);
engine.getDependencies().add(d); engine.getDependencies().add(d);
} }
} catch (FileNotFoundException fnfe) { } catch (IOException ex) {
LOGGER.warn("Error opening dependency {}", dependency.getActualFilePath()); LOGGER.warn("Error opening dependency {}", dependency.getActualFilePath());
} catch (ComposerException ce) { } catch (ComposerException ce) {
LOGGER.warn("Error parsing composer.json {}", dependency.getActualFilePath(), ce); LOGGER.warn("Error parsing composer.json {}", dependency.getActualFilePath(), ce);
} finally {
if (fis != null) {
try {
fis.close();
} catch (Exception e) {
LOGGER.debug("Unable to close file", e);
}
}
} }
} }

View File

@@ -322,9 +322,7 @@ public class JarAnalyzer extends AbstractFileTypeAnalyzer {
final String propPath = path.substring(0, path.length() - 7) + "pom.properies"; final String propPath = path.substring(0, path.length() - 7) + "pom.properies";
final ZipEntry propEntry = jar.getEntry(propPath); final ZipEntry propEntry = jar.getEntry(propPath);
if (propEntry != null) { if (propEntry != null) {
Reader reader = null; try (Reader reader = new InputStreamReader(jar.getInputStream(propEntry), "UTF-8")) {
try {
reader = new InputStreamReader(jar.getInputStream(propEntry), "UTF-8");
pomProperties = new Properties(); pomProperties = new Properties();
pomProperties.load(reader); pomProperties.load(reader);
LOGGER.debug("Read pom.properties: {}", propPath); LOGGER.debug("Read pom.properties: {}", propPath);
@@ -332,14 +330,6 @@ public class JarAnalyzer extends AbstractFileTypeAnalyzer {
LOGGER.trace("UTF-8 is not supported", ex); LOGGER.trace("UTF-8 is not supported", ex);
} catch (IOException ex) { } catch (IOException ex) {
LOGGER.trace("Unable to read the POM properties", ex); LOGGER.trace("Unable to read the POM properties", ex);
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException ex) {
LOGGER.trace("close error", ex);
}
}
} }
} }
return pomProperties; return pomProperties;
@@ -377,24 +367,18 @@ public class JarAnalyzer extends AbstractFileTypeAnalyzer {
* the file * the file
*/ */
private File extractPom(String path, JarFile jar) throws AnalysisException { private File extractPom(String path, JarFile jar) throws AnalysisException {
InputStream input = null;
FileOutputStream fos = null;
final File tmpDir = getNextTempDirectory(); final File tmpDir = getNextTempDirectory();
final File file = new File(tmpDir, "pom.xml"); final File file = new File(tmpDir, "pom.xml");
try { final ZipEntry entry = jar.getEntry(path);
final ZipEntry entry = jar.getEntry(path); if (entry == null) {
if (entry == null) { throw new AnalysisException(String.format("Pom (%s) does not exist in %s", path, jar.getName()));
throw new AnalysisException(String.format("Pom (%s)does not exist in %s", path, jar.getName())); }
} try (InputStream input = jar.getInputStream(entry);
input = jar.getInputStream(entry); FileOutputStream fos = new FileOutputStream(file)) {
fos = new FileOutputStream(file);
IOUtils.copy(input, fos); IOUtils.copy(input, fos);
} catch (IOException ex) { } catch (IOException ex) {
LOGGER.warn("An error occurred reading '{}' from '{}'.", path, jar.getName()); LOGGER.warn("An error occurred reading '{}' from '{}'.", path, jar.getName());
LOGGER.error("", ex); LOGGER.error("", ex);
} finally {
FileUtils.close(fos);
FileUtils.close(input);
} }
return file; return file;
} }
@@ -908,9 +892,7 @@ public class JarAnalyzer extends AbstractFileTypeAnalyzer {
*/ */
private List<ClassNameInformation> collectClassNames(Dependency dependency) { private List<ClassNameInformation> collectClassNames(Dependency dependency) {
final List<ClassNameInformation> classNames = new ArrayList<>(); final List<ClassNameInformation> classNames = new ArrayList<>();
JarFile jar = null; try (JarFile jar = new JarFile(dependency.getActualFilePath())) {
try {
jar = new JarFile(dependency.getActualFilePath());
final Enumeration<JarEntry> entries = jar.entries(); final Enumeration<JarEntry> entries = jar.entries();
while (entries.hasMoreElements()) { while (entries.hasMoreElements()) {
final JarEntry entry = entries.nextElement(); final JarEntry entry = entries.nextElement();
@@ -924,14 +906,6 @@ public class JarAnalyzer extends AbstractFileTypeAnalyzer {
} catch (IOException ex) { } catch (IOException ex) {
LOGGER.warn("Unable to open jar file '{}'.", dependency.getFileName()); LOGGER.warn("Unable to open jar file '{}'.", dependency.getFileName());
LOGGER.debug("", ex); LOGGER.debug("", ex);
} finally {
if (jar != null) {
try {
jar.close();
} catch (IOException ex) {
LOGGER.trace("", ex);
}
}
} }
return classNames; return classNames;
} }

View File

@@ -121,17 +121,9 @@ public class NodePackageAnalyzer extends AbstractFileTypeAnalyzer {
} }
@Override @Override
protected void analyzeDependency(Dependency dependency, Engine engine) protected void analyzeDependency(Dependency dependency, Engine engine) throws AnalysisException {
throws AnalysisException {
final File file = dependency.getActualFile(); final File file = dependency.getActualFile();
JsonReader jsonReader; try (JsonReader jsonReader = Json.createReader(FileUtils.openInputStream(file))) {
try {
jsonReader = Json.createReader(FileUtils.openInputStream(file));
} catch (IOException e) {
throw new AnalysisException(
"Problem occurred while reading dependency file.", e);
}
try {
final JsonObject json = jsonReader.readObject(); final JsonObject json = jsonReader.readObject();
final EvidenceCollection productEvidence = dependency.getProductEvidence(); final EvidenceCollection productEvidence = dependency.getProductEvidence();
final EvidenceCollection vendorEvidence = dependency.getVendorEvidence(); final EvidenceCollection vendorEvidence = dependency.getVendorEvidence();
@@ -151,8 +143,8 @@ public class NodePackageAnalyzer extends AbstractFileTypeAnalyzer {
dependency.setDisplayFileName(String.format("%s/%s", file.getParentFile().getName(), file.getName())); dependency.setDisplayFileName(String.format("%s/%s", file.getParentFile().getName(), file.getName()));
} catch (JsonException e) { } catch (JsonException e) {
LOGGER.warn("Failed to parse package.json file.", e); LOGGER.warn("Failed to parse package.json file.", e);
} finally { } catch (IOException e) {
jsonReader.close(); throw new AnalysisException("Problem occurred while reading dependency file.", e);
} }
} }

View File

@@ -132,20 +132,10 @@ public class NuspecAnalyzer extends AbstractFileTypeAnalyzer {
try { try {
final NuspecParser parser = new XPathNuspecParser(); final NuspecParser parser = new XPathNuspecParser();
NugetPackage np = null; NugetPackage np = null;
FileInputStream fis = null; try (FileInputStream fis =new FileInputStream(dependency.getActualFilePath())) {
try {
fis = new FileInputStream(dependency.getActualFilePath());
np = parser.parse(fis); np = parser.parse(fis);
} catch (NuspecParseException | FileNotFoundException ex) { } catch (NuspecParseException | FileNotFoundException ex) {
throw new AnalysisException(ex); throw new AnalysisException(ex);
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
LOGGER.debug("Error closing input stream");
}
}
} }
if (np.getOwners() != null) { if (np.getOwners() != null) {

View File

@@ -360,20 +360,12 @@ public class PythonDistributionAnalyzer extends AbstractFileTypeAnalyzer {
if (null == manifest) { if (null == manifest) {
LOGGER.debug("Manifest file not found."); LOGGER.debug("Manifest file not found.");
} else { } else {
InputStream in = null; try (InputStream in = new BufferedInputStream(new FileInputStream(manifest))){
try {
in = new BufferedInputStream(new FileInputStream(manifest));
result.load(in); result.load(in);
} catch (MessagingException | FileNotFoundException e) { } catch (MessagingException | FileNotFoundException e) {
LOGGER.warn(e.getMessage(), e); LOGGER.warn(e.getMessage(), e);
} finally { } catch (IOException ex) {
if (in != null) { LOGGER.warn(ex.getMessage(), ex);
try {
in.close();
} catch (IOException ex) {
LOGGER.debug("failed to close input stream", ex);
}
}
} }
} }
return result; return result;

View File

@@ -54,12 +54,10 @@ public final class CweDB {
* @return a HashMap of CWE data * @return a HashMap of CWE data
*/ */
private static Map<String, String> loadData() { private static Map<String, String> loadData() {
ObjectInputStream oin = null; final String filePath = "data/cwe.hashmap.serialized";
try { try (InputStream input = CweDB.class.getClassLoader().getResourceAsStream(filePath);
final String filePath = "data/cwe.hashmap.serialized"; ObjectInputStream oin = new ObjectInputStream(input)) {
final InputStream input = CweDB.class.getClassLoader().getResourceAsStream(filePath);
oin = new ObjectInputStream(input);
@SuppressWarnings("unchecked")
final Map<String, String> ret = (HashMap<String, String>) oin.readObject(); final Map<String, String> ret = (HashMap<String, String>) oin.readObject();
return ret; return ret;
} catch (ClassNotFoundException ex) { } catch (ClassNotFoundException ex) {
@@ -68,14 +66,6 @@ public final class CweDB {
} catch (IOException ex) { } catch (IOException ex) {
LOGGER.warn("Unable to load CWE data due to an IO Error. This should not be an issue."); LOGGER.warn("Unable to load CWE data due to an IO Error. This should not be an issue.");
LOGGER.debug("", ex); LOGGER.debug("", ex);
} finally {
if (oin != null) {
try {
oin.close();
} catch (IOException ex) {
LOGGER.trace("", ex);
}
}
} }
return null; return null;
} }

View File

@@ -224,33 +224,19 @@ public class DownloadTask implements Callable<Future<ProcessTask>> {
if (file == null || !file.isFile()) { if (file == null || !file.isFile()) {
return false; return false;
} }
InputStream is = null; try (InputStream is = new FileInputStream(file)) {
try {
is = new FileInputStream(file);
final byte[] buf = new byte[5]; final byte[] buf = new byte[5];
int read; int read;
try { read = is.read(buf);
read = is.read(buf);
} catch (IOException ex) {
return false;
}
return read == 5 return read == 5
&& buf[0] == '<' && buf[0] == '<'
&& (buf[1] == '?') && (buf[1] == '?')
&& (buf[2] == 'x' || buf[2] == 'X') && (buf[2] == 'x' || buf[2] == 'X')
&& (buf[3] == 'm' || buf[3] == 'M') && (buf[3] == 'm' || buf[3] == 'M')
&& (buf[4] == 'l' || buf[4] == 'L'); && (buf[4] == 'l' || buf[4] == 'L');
} catch (FileNotFoundException ex) { } catch (IOException ex) {
LOGGER.debug("Error checking if file is xml", ex);
return false; return false;
} finally {
if (is != null) {
try {
is.close();
} catch (IOException ex) {
LOGGER.debug("Error closing stream", ex);
}
}
} }
} }
} }

View File

@@ -240,55 +240,39 @@ public class ReportGenerator {
InputStream input = null; InputStream input = null;
String templatePath = null; String templatePath = null;
final File f = new File(templateName); final File f = new File(templateName);
if (f.exists() && f.isFile()) {
try {
templatePath = templateName;
input = new FileInputStream(f);
} catch (FileNotFoundException ex) {
throw new ReportException("Unable to locate template file: " + templateName, ex);
}
} else {
templatePath = "templates/" + templateName + ".vsl";
input = this.getClass().getClassLoader().getResourceAsStream(templatePath);
}
if (input == null) {
throw new ReportException("Template file doesn't exist: " + templatePath);
}
InputStreamReader reader = null;
OutputStreamWriter writer = null;
try { try {
reader = new InputStreamReader(input, "UTF-8"); if (f.exists() && f.isFile()) {
writer = new OutputStreamWriter(outputStream, "UTF-8"); try {
if (!velocityEngine.evaluate(context, writer, templatePath, reader)) { templatePath = templateName;
throw new ReportException("Failed to convert the template into html."); input = new FileInputStream(f);
} catch (FileNotFoundException ex) {
throw new ReportException("Unable to locate template file: " + templateName, ex);
}
} else {
templatePath = "templates/" + templateName + ".vsl";
input = this.getClass().getClassLoader().getResourceAsStream(templatePath);
}
if (input == null) {
throw new ReportException("Template file doesn't exist: " + templatePath);
}
try (InputStreamReader reader = new InputStreamReader(input, "UTF-8");
OutputStreamWriter writer = new OutputStreamWriter(outputStream, "UTF-8")) {
if (!velocityEngine.evaluate(context, writer, templatePath, reader)) {
throw new ReportException("Failed to convert the template into html.");
}
writer.flush();
} catch (UnsupportedEncodingException ex) {
throw new ReportException("Unable to generate the report using UTF-8", ex);
} catch (IOException ex) {
throw new ReportException("Unable to write the report", ex);
} }
writer.flush();
} catch (UnsupportedEncodingException ex) {
throw new ReportException("Unable to generate the report using UTF-8", ex);
} catch (IOException ex) {
throw new ReportException("Unable to write the report", ex);
} finally { } finally {
if (writer != null) { if (input != null) {
try { try {
writer.close(); input.close();
} catch (IOException ex) { } catch (IOException ex) {
LOGGER.trace("", ex); LOGGER.trace("Error closing input", ex);
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException ex) {
LOGGER.trace("", ex);
}
}
if (reader != null) {
try {
reader.close();
} catch (IOException ex) {
LOGGER.trace("", ex);
} }
} }
} }
@@ -315,21 +299,10 @@ public class ReportGenerator {
throw new ReportException("Unable to create directory '" + outFile.getParentFile().getAbsolutePath() + "'."); throw new ReportException("Unable to create directory '" + outFile.getParentFile().getAbsolutePath() + "'.");
} }
} }
try (OutputStream outputSteam = new FileOutputStream(outFile)) {
OutputStream outputSteam = null;
try {
outputSteam = new FileOutputStream(outFile);
generateReport(templateName, outputSteam); generateReport(templateName, outputSteam);
} catch (FileNotFoundException ex) { } catch (IOException ex) {
throw new ReportException("Unable to write to file: " + outFile, ex); throw new ReportException("Unable to write to file: " + outFile, ex);
} finally {
if (outputSteam != null) {
try {
outputSteam.close();
} catch (IOException ex) {
LOGGER.trace("ignore", ex);
}
}
} }
} }
} }

View File

@@ -85,18 +85,10 @@ public final class ExtractionUtil {
return; return;
} }
FileInputStream fis = null;
ZipInputStream zis = null;
try {
fis = new FileInputStream(archive);
} catch (FileNotFoundException ex) {
LOGGER.debug("", ex);
throw new ExtractionException("Archive file was not found.", ex);
}
zis = new ZipInputStream(new BufferedInputStream(fis));
ZipEntry entry; ZipEntry entry;
try { try (FileInputStream fis = new FileInputStream(archive);
BufferedInputStream bis = new BufferedInputStream(fis);
ZipInputStream zis = new ZipInputStream(bis)) {
while ((entry = zis.getNextEntry()) != null) { while ((entry = zis.getNextEntry()) != null) {
if (entry.isDirectory()) { if (entry.isDirectory()) {
final File d = new File(extractTo, entry.getName()); final File d = new File(extractTo, entry.getName());
@@ -107,9 +99,7 @@ public final class ExtractionUtil {
} else { } else {
final File file = new File(extractTo, entry.getName()); final File file = new File(extractTo, entry.getName());
if (engine == null || engine.accept(file)) { if (engine == null || engine.accept(file)) {
FileOutputStream fos = null; try (FileOutputStream fos = new FileOutputStream(file)) {
try {
fos = new FileOutputStream(file);
IOUtils.copy(zis, fos); IOUtils.copy(zis, fos);
} catch (FileNotFoundException ex) { } catch (FileNotFoundException ex) {
LOGGER.debug("", ex); LOGGER.debug("", ex);
@@ -119,8 +109,6 @@ public final class ExtractionUtil {
LOGGER.debug("", ex); LOGGER.debug("", ex);
final String msg = String.format("IO Exception while parsing file '%s'.", file.getName()); final String msg = String.format("IO Exception while parsing file '%s'.", file.getName());
throw new ExtractionException(msg, ex); throw new ExtractionException(msg, ex);
} finally {
FileUtils.close(fos);
} }
} }
} }
@@ -129,8 +117,6 @@ public final class ExtractionUtil {
final String msg = String.format("Exception reading archive '%s'.", archive.getName()); final String msg = String.format("Exception reading archive '%s'.", archive.getName());
LOGGER.debug("", ex); LOGGER.debug("", ex);
throw new ExtractionException(msg, ex); throw new ExtractionException(msg, ex);
} finally {
FileUtils.close(zis);
} }
} }
@@ -142,31 +128,21 @@ public final class ExtractionUtil {
* @param filter determines which files get extracted * @param filter determines which files get extracted
* @throws ExtractionException thrown if the archive is not found * @throws ExtractionException thrown if the archive is not found
*/ */
public static void extractFilesUsingFilter(File archive, File destination, public static void extractFilesUsingFilter(File archive, File destination, FilenameFilter filter) throws ExtractionException {
FilenameFilter filter) throws ExtractionException {
if (archive == null || destination == null) { if (archive == null || destination == null) {
return; return;
} }
FileInputStream fis = null; try (FileInputStream fis = new FileInputStream(archive)) {
try { extractArchive(new ZipArchiveInputStream(new BufferedInputStream(
fis = new FileInputStream(archive); fis)), destination, filter);
} catch (FileNotFoundException ex) { } catch (FileNotFoundException ex) {
LOGGER.debug("", ex); LOGGER.debug("", ex);
throw new ExtractionException("Archive file was not found.", ex); throw new ExtractionException("Archive file was not found.", ex);
} } catch (IOException | ArchiveExtractionException ex) {
try {
extractArchive(new ZipArchiveInputStream(new BufferedInputStream(
fis)), destination, filter);
} catch (ArchiveExtractionException ex) {
LOGGER.warn("Exception extracting archive '{}'.", archive.getName()); LOGGER.warn("Exception extracting archive '{}'.", archive.getName());
LOGGER.debug("", ex); LOGGER.debug("", ex);
} finally { throw new ExtractionException("Unable to extract from archive", ex);
try {
fis.close();
} catch (IOException ex) {
LOGGER.debug("", ex);
}
} }
} }
@@ -219,26 +195,19 @@ public final class ExtractionUtil {
FilenameFilter filter, ArchiveEntry entry) throws ExtractionException { FilenameFilter filter, ArchiveEntry entry) throws ExtractionException {
final File file = new File(destination, entry.getName()); final File file = new File(destination, entry.getName());
if (filter.accept(file.getParentFile(), file.getName())) { if (filter.accept(file.getParentFile(), file.getName())) {
LOGGER.debug("Extracting '{}'", LOGGER.debug("Extracting '{}'", file.getPath());
file.getPath()); createParentFile(file);
FileOutputStream fos = null;
try { try (FileOutputStream fos = new FileOutputStream(file)) {
createParentFile(file);
fos = new FileOutputStream(file);
IOUtils.copy(input, fos); IOUtils.copy(input, fos);
} catch (FileNotFoundException ex) { } catch (FileNotFoundException ex) {
LOGGER.debug("", ex); LOGGER.debug("", ex);
final String msg = String.format("Unable to find file '%s'.", final String msg = String.format("Unable to find file '%s'.", file.getName());
file.getName());
throw new ExtractionException(msg, ex); throw new ExtractionException(msg, ex);
} catch (IOException ex) { } catch (IOException ex) {
LOGGER.debug("", ex); LOGGER.debug("", ex);
final String msg = String final String msg = String.format("IO Exception while parsing file '%s'.", file.getName());
.format("IO Exception while parsing file '%s'.",
file.getName());
throw new ExtractionException(msg, ex); throw new ExtractionException(msg, ex);
} finally {
FileUtils.close(fos);
} }
} }
} }
@@ -251,8 +220,7 @@ public final class ExtractionUtil {
* @throws ExtractionException thrown if the parent paths could not be * @throws ExtractionException thrown if the parent paths could not be
* created * created
*/ */
private static void createParentFile(final File file) private static void createParentFile(final File file) throws ExtractionException {
throws ExtractionException {
final File parent = file.getParentFile(); final File parent = file.getParentFile();
if (!parent.isDirectory() && !parent.mkdirs()) { if (!parent.isDirectory() && !parent.mkdirs()) {
final String msg = String.format( final String msg = String.format(
@@ -281,34 +249,10 @@ public final class ExtractionUtil {
throw new IOException("Unable to rename '" + file.getPath() + "'"); throw new IOException("Unable to rename '" + file.getPath() + "'");
} }
final File newFile = new File(originalPath); final File newFile = new File(originalPath);
try (GZIPInputStream cin = new GZIPInputStream(new FileInputStream(gzip));
final byte[] buffer = new byte[4096]; FileOutputStream out = new FileOutputStream(newFile)) {
IOUtils.copy(cin, out);
GZIPInputStream cin = null;
FileOutputStream out = null;
try {
cin = new GZIPInputStream(new FileInputStream(gzip));
out = new FileOutputStream(newFile);
int len;
while ((len = cin.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
} finally { } finally {
if (cin != null) {
try {
cin.close();
} catch (IOException ex) {
LOGGER.trace("ignore", ex);
}
}
if (out != null) {
try {
out.close();
} catch (IOException ex) {
LOGGER.trace("ignore", ex);
}
}
if (gzip.isFile() && !org.apache.commons.io.FileUtils.deleteQuietly(gzip)) { if (gzip.isFile() && !org.apache.commons.io.FileUtils.deleteQuietly(gzip)) {
LOGGER.debug("Failed to delete temporary file when extracting 'gz' {}", gzip.toString()); LOGGER.debug("Failed to delete temporary file when extracting 'gz' {}", gzip.toString());
gzip.deleteOnExit(); gzip.deleteOnExit();

View File

@@ -58,21 +58,11 @@ public class PomParser {
* @throws PomParseException thrown if the xml file cannot be parsed * @throws PomParseException thrown if the xml file cannot be parsed
*/ */
public Model parse(File file) throws PomParseException { public Model parse(File file) throws PomParseException {
FileInputStream fis = null; try (FileInputStream fis = new FileInputStream(file)) {
try {
fis = new FileInputStream(file);
return parse(fis); return parse(fis);
} catch (IOException ex) { } catch (IOException ex) {
LOGGER.debug("", ex); LOGGER.debug("", ex);
throw new PomParseException(ex); throw new PomParseException(ex);
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException ex) {
LOGGER.debug("Unable to close stream", ex);
}
}
} }
} }

View File

@@ -595,28 +595,6 @@ public abstract class BaseDependencyCheckMojo extends AbstractMojo implements Ma
return target; 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)
*/
protected File getDataFile(MavenProject current) {
if (getLog().isDebugEnabled()) {
getLog().debug(String.format("Getting data file for %s using key '%s'", current.getName(), getDataFileContextKey()));
}
final Object obj = current.getContextValue(getDataFileContextKey());
if (obj != null) {
if (obj instanceof String) {
return new File((String) obj);
}
} else if (getLog().isDebugEnabled()) {
getLog().debug("Context value not found");
}
return null;
}
/** /**
* Scans the project's artifacts and adds them to the engine's dependency * Scans the project's artifacts and adds them to the engine's dependency
* list. * list.
@@ -1157,60 +1135,6 @@ public abstract class BaseDependencyCheckMojo extends AbstractMojo implements Ma
return "dependency-output-dir-" + dataFileName; return "dependency-output-dir-" + dataFileName;
} }
/**
* Writes the scan data to disk. This is used to serialize the scan data
* between the "check" and "aggregate" phase.
*
* @param mp the Maven project for which the data file was created
* @param writeTo the directory to write the data file
* @param dependencies the list of dependencies to serialize
*/
protected void writeDataFile(MavenProject mp, File writeTo, List<Dependency> dependencies) {
File file;
//check to see if this was already written out
if (mp.getContextValue(this.getDataFileContextKey()) == null) {
if (writeTo == null) {
file = new File(mp.getBuild().getDirectory());
file = new File(file, dataFileName);
} else {
file = new File(writeTo, dataFileName);
}
final File parent = file.getParentFile();
if (!parent.isDirectory() && !parent.mkdirs()) {
getLog().error(String.format("Directory '%s' does not exist and cannot be created; unable to write data file.",
parent.getAbsolutePath()));
}
ObjectOutputStream out = null;
try {
if (dependencies != null) {
out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(file)));
out.writeObject(dependencies);
}
if (getLog().isDebugEnabled()) {
getLog().debug(String.format("Serialized data file written to '%s' for %s, referenced by key %s",
file.getAbsolutePath(), mp.getName(), this.getDataFileContextKey()));
}
mp.setContextValue(this.getDataFileContextKey(), file.getAbsolutePath());
} catch (IOException ex) {
getLog().warn("Unable to create data file used for report aggregation; "
+ "if report aggregation is being used the results may be incomplete.");
if (getLog().isDebugEnabled()) {
getLog().debug(ex.getMessage(), ex);
}
} finally {
if (out != null) {
try {
out.close();
} catch (IOException ex) {
if (getLog().isDebugEnabled()) {
getLog().debug("ignore", ex);
}
}
}
}
}
}
//</editor-fold> //</editor-fold>
} }

View File

@@ -39,20 +39,9 @@ public class BaseTest {
@BeforeClass @BeforeClass
public static void setUpClass() throws Exception { public static void setUpClass() throws Exception {
Settings.initialize(); Settings.initialize();
InputStream mojoProperties = null; try (InputStream mojoProperties = BaseTest.class.getClassLoader().getResourceAsStream(BaseTest.PROPERTIES_FILE)) {
try {
mojoProperties = BaseTest.class.getClassLoader().getResourceAsStream(BaseTest.PROPERTIES_FILE);
Settings.mergeProperties(mojoProperties); Settings.mergeProperties(mojoProperties);
} finally {
if (mojoProperties != null) {
try {
mojoProperties.close();
} catch (IOException ex) {
Logger.getLogger(BaseTest.class.getName()).log(Level.SEVERE, null, ex);
}
}
} }
} }
@AfterClass @AfterClass

View File

@@ -65,11 +65,8 @@ public final class Checksum {
*/ */
public static byte[] getChecksum(String algorithm, File file) throws NoSuchAlgorithmException, IOException { public static byte[] getChecksum(String algorithm, File file) throws NoSuchAlgorithmException, IOException {
final MessageDigest md = MessageDigest.getInstance(algorithm); final MessageDigest md = MessageDigest.getInstance(algorithm);
FileInputStream fis = null; try (FileInputStream fis = new FileInputStream(file);
FileChannel ch = null; FileChannel ch = fis.getChannel()) {
try {
fis = new FileInputStream(file);
ch = fis.getChannel();
final ByteBuffer buf = ByteBuffer.allocateDirect(8192); final ByteBuffer buf = ByteBuffer.allocateDirect(8192);
int b = ch.read(buf); int b = ch.read(buf);
while (b != -1 && b != 0) { while (b != -1 && b != 0) {
@@ -81,21 +78,6 @@ public final class Checksum {
b = ch.read(buf); b = ch.read(buf);
} }
return md.digest(); return md.digest();
} finally {
if (ch != null) {
try {
ch.close();
} catch (IOException ex) {
LOGGER.trace("Error closing channel '{}'.", file.getName(), ex);
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException ex) {
LOGGER.trace("Error closing file '{}'.", file.getName(), ex);
}
}
} }
} }

View File

@@ -433,10 +433,8 @@ public final class Settings {
* @param propertiesFilePath the path to the base properties file to load * @param propertiesFilePath the path to the base properties file to load
*/ */
private Settings(String propertiesFilePath) { private Settings(String propertiesFilePath) {
InputStream in = null;
props = new Properties(); props = new Properties();
try { try (InputStream in = this.getClass().getClassLoader().getResourceAsStream(propertiesFilePath)) {
in = this.getClass().getClassLoader().getResourceAsStream(propertiesFilePath);
props.load(in); props.load(in);
} catch (NullPointerException ex) { } catch (NullPointerException ex) {
LOGGER.error("Did not find settings file '{}'.", propertiesFilePath); LOGGER.error("Did not find settings file '{}'.", propertiesFilePath);
@@ -444,14 +442,6 @@ public final class Settings {
} catch (IOException ex) { } catch (IOException ex) {
LOGGER.error("Unable to load settings from '{}'.", propertiesFilePath); LOGGER.error("Unable to load settings from '{}'.", propertiesFilePath);
LOGGER.debug("", ex); LOGGER.debug("", ex);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException ex) {
LOGGER.trace("", ex);
}
}
} }
logProperties("Properties loaded", props); logProperties("Properties loaded", props);
} }
@@ -644,18 +634,8 @@ public final class Settings {
* the properties * the properties
*/ */
public static void mergeProperties(File filePath) throws FileNotFoundException, IOException { public static void mergeProperties(File filePath) throws FileNotFoundException, IOException {
FileInputStream fis = null; try (FileInputStream fis = new FileInputStream(filePath)) {
try {
fis = new FileInputStream(filePath);
mergeProperties(fis); mergeProperties(fis);
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException ex) {
LOGGER.trace("close error", ex);
}
}
} }
} }
@@ -672,18 +652,8 @@ public final class Settings {
* the properties * the properties
*/ */
public static void mergeProperties(String filePath) throws FileNotFoundException, IOException { public static void mergeProperties(String filePath) throws FileNotFoundException, IOException {
FileInputStream fis = null; try (FileInputStream fis = new FileInputStream(filePath)) {
try {
fis = new FileInputStream(filePath);
mergeProperties(fis); mergeProperties(fis);
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException ex) {
LOGGER.trace("close error", ex);
}
}
} }
} }
@@ -977,6 +947,7 @@ public final class Settings {
if (path != null && (path.exists() || path.mkdirs())) { if (path != null && (path.exists() || path.mkdirs())) {
return path; return path;
} }
throw new IOException(String.format("Unable to create the data directory '%s'", path.getAbsolutePath())); throw new IOException(String.format("Unable to create the data directory '%s'",
(path == null) ? "unknown" : path.getAbsolutePath()));
} }
} }

View File

@@ -39,12 +39,10 @@ public class ExpectedObjectInputStreamTest {
*/ */
@Test @Test
public void testResolveClass() { public void testResolveClass() {
ObjectOutputStream out = null; List<SimplePojo> data = new ArrayList<>();
try { data.add(new SimplePojo());
List<SimplePojo> data = new ArrayList<>(); try (ByteArrayOutputStream mem = new ByteArrayOutputStream();
data.add(new SimplePojo()); ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(mem))) {
ByteArrayOutputStream mem = new ByteArrayOutputStream();
out = new ObjectOutputStream(new BufferedOutputStream(mem));
out.writeObject(data); out.writeObject(data);
out.flush(); out.flush();
byte[] buf = mem.toByteArray(); byte[] buf = mem.toByteArray();
@@ -54,14 +52,6 @@ public class ExpectedObjectInputStreamTest {
instance.readObject(); instance.readObject();
} catch (IOException | ClassNotFoundException ex) { } catch (IOException | ClassNotFoundException ex) {
fail(ex.getMessage()); fail(ex.getMessage());
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
} }
} }