diff --git a/dependency-check-ant/src/main/java/org/owasp/dependencycheck/taskdefs/Purge.java b/dependency-check-ant/src/main/java/org/owasp/dependencycheck/taskdefs/Purge.java index 2169baaac..52b99d0eb 100644 --- a/dependency-check-ant/src/main/java/org/owasp/dependencycheck/taskdefs/Purge.java +++ b/dependency-check-ant/src/main/java/org/owasp/dependencycheck/taskdefs/Purge.java @@ -144,9 +144,8 @@ public class Purge extends Task { */ protected void populateSettings() throws BuildException { Settings.initialize(); - InputStream taskProperties = null; - try { - taskProperties = this.getClass().getClassLoader().getResourceAsStream(PROPERTIES_FILE); + + try (InputStream taskProperties = this.getClass().getClassLoader().getResourceAsStream(PROPERTIES_FILE)) { Settings.mergeProperties(taskProperties); } catch (IOException ex) { 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); } log(msg, ex, Project.MSG_WARN); - } finally { - if (taskProperties != null) { - try { - taskProperties.close(); - } catch (IOException ex) { - log("", ex, Project.MSG_DEBUG); - } - } } if (dataDirectory != null) { Settings.setString(Settings.KEYS.DATA_DIRECTORY, dataDirectory); diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/AbstractSuppressionAnalyzer.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/AbstractSuppressionAnalyzer.java index 450e8f5ae..b5a74171a 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/AbstractSuppressionAnalyzer.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/AbstractSuppressionAnalyzer.java @@ -130,10 +130,9 @@ public abstract class AbstractSuppressionAnalyzer extends AbstractAnalyzer { } } else { file = new File(suppressionFilePath); - InputStream suppressionsFromClasspath = null; + if (!file.exists()) { - try { - suppressionsFromClasspath = this.getClass().getClassLoader().getResourceAsStream(suppressionFilePath); + try (InputStream suppressionsFromClasspath = this.getClass().getClassLoader().getResourceAsStream(suppressionFilePath)) { if (suppressionsFromClasspath != null) { deleteTempFile = true; file = FileUtils.getTempFile("suppression", "xml"); @@ -143,14 +142,6 @@ public abstract class AbstractSuppressionAnalyzer extends AbstractAnalyzer { 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); - } - } } } } diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/ArchiveAnalyzer.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/ArchiveAnalyzer.java index d964f5cc3..ffd2bc2c2 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/ArchiveAnalyzer.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/ArchiveAnalyzer.java @@ -535,14 +535,12 @@ public class ArchiveAnalyzer extends AbstractFileTypeAnalyzer { */ private static void extractAcceptedFile(ArchiveInputStream input, File file) throws AnalysisException { LOGGER.debug("Extracting '{}'", file.getPath()); - FileOutputStream fos = null; - try { - final File parent = file.getParentFile(); - if (!parent.isDirectory() && !parent.mkdirs()) { - final String msg = String.format("Unable to build directory '%s'.", parent.getAbsolutePath()); - throw new AnalysisException(msg); - } - fos = new FileOutputStream(file); + final File parent = file.getParentFile(); + if (!parent.isDirectory() && !parent.mkdirs()) { + final String msg = String.format("Unable to build directory '%s'.", parent.getAbsolutePath()); + throw new AnalysisException(msg); + } + try (FileOutputStream fos = new FileOutputStream(file)) { IOUtils.copy(input, fos); } catch (FileNotFoundException ex) { LOGGER.debug("", ex); @@ -552,8 +550,6 @@ public class ArchiveAnalyzer extends AbstractFileTypeAnalyzer { LOGGER.debug("", ex); final String msg = String.format("IO Exception while parsing file '%s'.", file.getName()); 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 { LOGGER.debug("Decompressing '{}'", outputFile.getPath()); - FileOutputStream out = null; - try { - out = new FileOutputStream(outputFile); + try (FileOutputStream out = new FileOutputStream(outputFile)) { IOUtils.copy(inputStream, out); } catch (IOException ex) { LOGGER.debug("", ex); throw new ArchiveExtractionException(ex); - } finally { - FileUtils.close(out); } } @@ -609,7 +601,6 @@ public class ArchiveAnalyzer extends AbstractFileTypeAnalyzer { } finally { ZipFile.closeQuietly(zip); } - return isJar; } } diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/AssemblyAnalyzer.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/AssemblyAnalyzer.java index 04149fc40..a0dd8c94e 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/AssemblyAnalyzer.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/AssemblyAnalyzer.java @@ -178,7 +178,7 @@ public class AssemblyAnalyzer extends AbstractFileTypeAnalyzer { throw new AnalysisException("Error initializing the assembly analyzer", pce); } catch (IOException | XPathExpressionException ioe) { throw new AnalysisException(ioe); - }catch (SAXException saxe) { + } catch (SAXException saxe) { LOGGER.error("----------------------------------------------------"); LOGGER.error("Failed to read the Assembly Analyzer results. " + "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); } // This shouldn't happen - + } /** @@ -198,46 +198,27 @@ public class AssemblyAnalyzer extends AbstractFileTypeAnalyzer { @Override public void initializeFileTypeAnalyzer() throws InitializationException { final File tempFile; + final String cfg; try { tempFile = File.createTempFile("GKA", ".exe", Settings.getTempDirectory()); + cfg = tempFile.getPath() + ".config"; } catch (IOException ex) { setEnabled(false); throw new InitializationException("Unable to create temporary file for the assembly analyzer", ex); } - FileOutputStream fos = null; - InputStream is = null; - try { - fos = new FileOutputStream(tempFile); - is = AssemblyAnalyzer.class.getClassLoader().getResourceAsStream("GrokAssembly.exe"); + try (FileOutputStream fos = new FileOutputStream(tempFile); + InputStream is = AssemblyAnalyzer.class.getClassLoader().getResourceAsStream("GrokAssembly.exe"); + FileOutputStream fosCfg = new FileOutputStream(cfg); + InputStream isCfg = AssemblyAnalyzer.class.getClassLoader().getResourceAsStream("GrokAssembly.exe.config")) { IOUtils.copy(is, fos); - grokAssemblyExe = tempFile; LOGGER.debug("Extracted GrokAssembly.exe to {}", grokAssemblyExe.getPath()); - - String cfg = grokAssemblyExe.getPath() + ".config"; - fos = new FileOutputStream(cfg); - is = AssemblyAnalyzer.class.getClassLoader().getResourceAsStream("GrokAssembly.exe.config"); - IOUtils.copy(is, fos); + IOUtils.copy(isCfg, fosCfg); LOGGER.debug("Extracted GrokAssembly.exe.config to {}", cfg); } catch (IOException ioe) { this.setEnabled(false); LOGGER.warn("Could not extract GrokAssembly.exe: {}", ioe.getMessage()); 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. diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/ComposerLockAnalyzer.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/ComposerLockAnalyzer.java index 57c8bf791..d172a2b10 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/ComposerLockAnalyzer.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/ComposerLockAnalyzer.java @@ -34,6 +34,7 @@ import org.slf4j.LoggerFactory; import java.io.FileFilter; import java.io.FileInputStream; import java.io.FileNotFoundException; +import java.io.IOException; import java.nio.charset.Charset; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; @@ -101,9 +102,7 @@ public class ComposerLockAnalyzer extends AbstractFileTypeAnalyzer { */ @Override protected void analyzeDependency(Dependency dependency, Engine engine) throws AnalysisException { - FileInputStream fis = null; - try { - fis = new FileInputStream(dependency.getActualFile()); + try (FileInputStream fis = new FileInputStream(dependency.getActualFile())) { final ComposerLockParser clp = new ComposerLockParser(fis); LOGGER.info("Checking composer.lock file {}", dependency.getActualFilePath()); clp.process(); @@ -120,18 +119,10 @@ public class ComposerLockAnalyzer extends AbstractFileTypeAnalyzer { LOGGER.info("Adding dependency {}", d); engine.getDependencies().add(d); } - } catch (FileNotFoundException fnfe) { + } catch (IOException ex) { LOGGER.warn("Error opening dependency {}", dependency.getActualFilePath()); } catch (ComposerException 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); - } - } } } diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/JarAnalyzer.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/JarAnalyzer.java index 7fc11c2d2..07f063a26 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/JarAnalyzer.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/JarAnalyzer.java @@ -322,9 +322,7 @@ public class JarAnalyzer extends AbstractFileTypeAnalyzer { final String propPath = path.substring(0, path.length() - 7) + "pom.properies"; final ZipEntry propEntry = jar.getEntry(propPath); if (propEntry != null) { - Reader reader = null; - try { - reader = new InputStreamReader(jar.getInputStream(propEntry), "UTF-8"); + try (Reader reader = new InputStreamReader(jar.getInputStream(propEntry), "UTF-8")) { pomProperties = new Properties(); pomProperties.load(reader); LOGGER.debug("Read pom.properties: {}", propPath); @@ -332,14 +330,6 @@ public class JarAnalyzer extends AbstractFileTypeAnalyzer { LOGGER.trace("UTF-8 is not supported", ex); } catch (IOException 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; @@ -377,24 +367,18 @@ public class JarAnalyzer extends AbstractFileTypeAnalyzer { * the file */ private File extractPom(String path, JarFile jar) throws AnalysisException { - InputStream input = null; - FileOutputStream fos = null; final File tmpDir = getNextTempDirectory(); final File file = new File(tmpDir, "pom.xml"); - try { - final ZipEntry entry = jar.getEntry(path); - if (entry == null) { - throw new AnalysisException(String.format("Pom (%s)does not exist in %s", path, jar.getName())); - } - input = jar.getInputStream(entry); - fos = new FileOutputStream(file); + final ZipEntry entry = jar.getEntry(path); + if (entry == null) { + throw new AnalysisException(String.format("Pom (%s) does not exist in %s", path, jar.getName())); + } + try (InputStream input = jar.getInputStream(entry); + FileOutputStream fos = new FileOutputStream(file)) { IOUtils.copy(input, fos); } catch (IOException ex) { LOGGER.warn("An error occurred reading '{}' from '{}'.", path, jar.getName()); LOGGER.error("", ex); - } finally { - FileUtils.close(fos); - FileUtils.close(input); } return file; } @@ -908,9 +892,7 @@ public class JarAnalyzer extends AbstractFileTypeAnalyzer { */ private List collectClassNames(Dependency dependency) { final List classNames = new ArrayList<>(); - JarFile jar = null; - try { - jar = new JarFile(dependency.getActualFilePath()); + try (JarFile jar = new JarFile(dependency.getActualFilePath())) { final Enumeration entries = jar.entries(); while (entries.hasMoreElements()) { final JarEntry entry = entries.nextElement(); @@ -924,14 +906,6 @@ public class JarAnalyzer extends AbstractFileTypeAnalyzer { } catch (IOException ex) { LOGGER.warn("Unable to open jar file '{}'.", dependency.getFileName()); LOGGER.debug("", ex); - } finally { - if (jar != null) { - try { - jar.close(); - } catch (IOException ex) { - LOGGER.trace("", ex); - } - } } return classNames; } diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/NodePackageAnalyzer.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/NodePackageAnalyzer.java index 15f7e6d37..8f9685c41 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/NodePackageAnalyzer.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/NodePackageAnalyzer.java @@ -121,17 +121,9 @@ public class NodePackageAnalyzer extends AbstractFileTypeAnalyzer { } @Override - protected void analyzeDependency(Dependency dependency, Engine engine) - throws AnalysisException { + protected void analyzeDependency(Dependency dependency, Engine engine) throws AnalysisException { final File file = dependency.getActualFile(); - JsonReader jsonReader; - try { - jsonReader = Json.createReader(FileUtils.openInputStream(file)); - } catch (IOException e) { - throw new AnalysisException( - "Problem occurred while reading dependency file.", e); - } - try { + try (JsonReader jsonReader = Json.createReader(FileUtils.openInputStream(file))) { final JsonObject json = jsonReader.readObject(); final EvidenceCollection productEvidence = dependency.getProductEvidence(); 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())); } catch (JsonException e) { LOGGER.warn("Failed to parse package.json file.", e); - } finally { - jsonReader.close(); + } catch (IOException e) { + throw new AnalysisException("Problem occurred while reading dependency file.", e); } } diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/NuspecAnalyzer.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/NuspecAnalyzer.java index 46e74f968..21a523025 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/NuspecAnalyzer.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/NuspecAnalyzer.java @@ -132,20 +132,10 @@ public class NuspecAnalyzer extends AbstractFileTypeAnalyzer { try { final NuspecParser parser = new XPathNuspecParser(); NugetPackage np = null; - FileInputStream fis = null; - try { - fis = new FileInputStream(dependency.getActualFilePath()); + try (FileInputStream fis =new FileInputStream(dependency.getActualFilePath())) { np = parser.parse(fis); } catch (NuspecParseException | FileNotFoundException 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) { diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/PythonDistributionAnalyzer.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/PythonDistributionAnalyzer.java index 23d5c9bc7..8b99153c4 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/PythonDistributionAnalyzer.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/analyzer/PythonDistributionAnalyzer.java @@ -360,20 +360,12 @@ public class PythonDistributionAnalyzer extends AbstractFileTypeAnalyzer { if (null == manifest) { LOGGER.debug("Manifest file not found."); } else { - InputStream in = null; - try { - in = new BufferedInputStream(new FileInputStream(manifest)); + try (InputStream in = new BufferedInputStream(new FileInputStream(manifest))){ result.load(in); } catch (MessagingException | FileNotFoundException e) { LOGGER.warn(e.getMessage(), e); - } finally { - if (in != null) { - try { - in.close(); - } catch (IOException ex) { - LOGGER.debug("failed to close input stream", ex); - } - } + } catch (IOException ex) { + LOGGER.warn(ex.getMessage(), ex); } } return result; diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/cwe/CweDB.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/cwe/CweDB.java index 30c50ab78..38aefd09e 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/cwe/CweDB.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/cwe/CweDB.java @@ -54,12 +54,10 @@ public final class CweDB { * @return a HashMap of CWE data */ private static Map loadData() { - ObjectInputStream oin = null; - try { - final String filePath = "data/cwe.hashmap.serialized"; - final InputStream input = CweDB.class.getClassLoader().getResourceAsStream(filePath); - oin = new ObjectInputStream(input); - @SuppressWarnings("unchecked") + final String filePath = "data/cwe.hashmap.serialized"; + try (InputStream input = CweDB.class.getClassLoader().getResourceAsStream(filePath); + ObjectInputStream oin = new ObjectInputStream(input)) { + final Map ret = (HashMap) oin.readObject(); return ret; } catch (ClassNotFoundException ex) { @@ -68,14 +66,6 @@ public final class CweDB { } catch (IOException ex) { LOGGER.warn("Unable to load CWE data due to an IO Error. This should not be an issue."); LOGGER.debug("", ex); - } finally { - if (oin != null) { - try { - oin.close(); - } catch (IOException ex) { - LOGGER.trace("", ex); - } - } } return null; } diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/update/nvd/DownloadTask.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/update/nvd/DownloadTask.java index 973b6798e..86d1b22a0 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/update/nvd/DownloadTask.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/data/update/nvd/DownloadTask.java @@ -224,33 +224,19 @@ public class DownloadTask implements Callable> { if (file == null || !file.isFile()) { return false; } - InputStream is = null; - try { - is = new FileInputStream(file); - + try (InputStream is = new FileInputStream(file)) { final byte[] buf = new byte[5]; int read; - try { - read = is.read(buf); - } catch (IOException ex) { - return false; - } + read = is.read(buf); return read == 5 && buf[0] == '<' && (buf[1] == '?') && (buf[2] == 'x' || buf[2] == 'X') && (buf[3] == 'm' || buf[3] == 'M') && (buf[4] == 'l' || buf[4] == 'L'); - } catch (FileNotFoundException ex) { + } catch (IOException ex) { + LOGGER.debug("Error checking if file is xml", ex); return false; - } finally { - if (is != null) { - try { - is.close(); - } catch (IOException ex) { - LOGGER.debug("Error closing stream", ex); - } - } } } } diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/reporting/ReportGenerator.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/reporting/ReportGenerator.java index e56f4fc75..a97aef3fa 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/reporting/ReportGenerator.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/reporting/ReportGenerator.java @@ -240,55 +240,39 @@ public class ReportGenerator { InputStream input = null; String templatePath = null; 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 { - reader = new InputStreamReader(input, "UTF-8"); - writer = new OutputStreamWriter(outputStream, "UTF-8"); - if (!velocityEngine.evaluate(context, writer, templatePath, reader)) { - throw new ReportException("Failed to convert the template into html."); + 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); + } + + 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 { - if (writer != null) { + if (input != null) { try { - writer.close(); + input.close(); } catch (IOException ex) { - LOGGER.trace("", 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); + LOGGER.trace("Error closing input", ex); } } } @@ -315,21 +299,10 @@ public class ReportGenerator { throw new ReportException("Unable to create directory '" + outFile.getParentFile().getAbsolutePath() + "'."); } } - - OutputStream outputSteam = null; - try { - outputSteam = new FileOutputStream(outFile); + try (OutputStream outputSteam = new FileOutputStream(outFile)) { generateReport(templateName, outputSteam); - } catch (FileNotFoundException ex) { + } catch (IOException 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); - } - } } } -} \ No newline at end of file +} diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/utils/ExtractionUtil.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/utils/ExtractionUtil.java index 27d96adb0..fe4b07666 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/utils/ExtractionUtil.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/utils/ExtractionUtil.java @@ -85,18 +85,10 @@ public final class ExtractionUtil { 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; - try { + 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()); @@ -107,9 +99,7 @@ public final class ExtractionUtil { } else { final File file = new File(extractTo, entry.getName()); if (engine == null || engine.accept(file)) { - FileOutputStream fos = null; - try { - fos = new FileOutputStream(file); + try (FileOutputStream fos = new FileOutputStream(file)) { IOUtils.copy(zis, fos); } catch (FileNotFoundException ex) { LOGGER.debug("", ex); @@ -119,8 +109,6 @@ public final class ExtractionUtil { LOGGER.debug("", ex); final String msg = String.format("IO Exception while parsing file '%s'.", file.getName()); 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()); LOGGER.debug("", 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 * @throws ExtractionException thrown if the archive is not found */ - public static void extractFilesUsingFilter(File archive, File destination, - FilenameFilter filter) throws ExtractionException { + public static void extractFilesUsingFilter(File archive, File destination, FilenameFilter filter) throws ExtractionException { if (archive == null || destination == null) { return; } - FileInputStream fis = null; - try { - fis = new FileInputStream(archive); + try (FileInputStream fis = new FileInputStream(archive)) { + extractArchive(new ZipArchiveInputStream(new BufferedInputStream( + fis)), destination, filter); } catch (FileNotFoundException ex) { LOGGER.debug("", ex); throw new ExtractionException("Archive file was not found.", ex); - } - try { - extractArchive(new ZipArchiveInputStream(new BufferedInputStream( - fis)), destination, filter); - } catch (ArchiveExtractionException ex) { + } catch (IOException | ArchiveExtractionException ex) { LOGGER.warn("Exception extracting archive '{}'.", archive.getName()); LOGGER.debug("", ex); - } finally { - try { - fis.close(); - } catch (IOException ex) { - LOGGER.debug("", ex); - } + throw new ExtractionException("Unable to extract from archive", ex); } } @@ -219,26 +195,19 @@ public final class ExtractionUtil { FilenameFilter filter, ArchiveEntry entry) throws ExtractionException { final File file = new File(destination, entry.getName()); if (filter.accept(file.getParentFile(), file.getName())) { - LOGGER.debug("Extracting '{}'", - file.getPath()); - FileOutputStream fos = null; - try { - createParentFile(file); - fos = new FileOutputStream(file); + LOGGER.debug("Extracting '{}'", file.getPath()); + createParentFile(file); + + try (FileOutputStream fos = new FileOutputStream(file)) { IOUtils.copy(input, fos); } catch (FileNotFoundException ex) { LOGGER.debug("", ex); - final String msg = String.format("Unable to find file '%s'.", - file.getName()); + final String msg = String.format("Unable to find file '%s'.", file.getName()); throw new ExtractionException(msg, ex); } catch (IOException 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); - } finally { - FileUtils.close(fos); } } } @@ -251,8 +220,7 @@ public final class ExtractionUtil { * @throws ExtractionException thrown if the parent paths could not be * created */ - private static void createParentFile(final File file) - throws ExtractionException { + private static void createParentFile(final File file) throws ExtractionException { final File parent = file.getParentFile(); if (!parent.isDirectory() && !parent.mkdirs()) { final String msg = String.format( @@ -281,34 +249,10 @@ public final class ExtractionUtil { throw new IOException("Unable to rename '" + file.getPath() + "'"); } final File newFile = new File(originalPath); - - final byte[] buffer = new byte[4096]; - - 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); - } + try (GZIPInputStream cin = new GZIPInputStream(new FileInputStream(gzip)); + FileOutputStream out = new FileOutputStream(newFile)) { + IOUtils.copy(cin, out); } 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)) { LOGGER.debug("Failed to delete temporary file when extracting 'gz' {}", gzip.toString()); gzip.deleteOnExit(); diff --git a/dependency-check-core/src/main/java/org/owasp/dependencycheck/xml/pom/PomParser.java b/dependency-check-core/src/main/java/org/owasp/dependencycheck/xml/pom/PomParser.java index 74e15571f..6e605fd6c 100644 --- a/dependency-check-core/src/main/java/org/owasp/dependencycheck/xml/pom/PomParser.java +++ b/dependency-check-core/src/main/java/org/owasp/dependencycheck/xml/pom/PomParser.java @@ -58,21 +58,11 @@ public class PomParser { * @throws PomParseException thrown if the xml file cannot be parsed */ public Model parse(File file) throws PomParseException { - FileInputStream fis = null; - try { - fis = new FileInputStream(file); + try (FileInputStream fis = new FileInputStream(file)) { return parse(fis); } catch (IOException ex) { LOGGER.debug("", ex); throw new PomParseException(ex); - } finally { - if (fis != null) { - try { - fis.close(); - } catch (IOException ex) { - LOGGER.debug("Unable to close stream", ex); - } - } } } diff --git a/dependency-check-maven/src/main/java/org/owasp/dependencycheck/maven/BaseDependencyCheckMojo.java b/dependency-check-maven/src/main/java/org/owasp/dependencycheck/maven/BaseDependencyCheckMojo.java index f7f9ec76f..38c8dd71b 100644 --- a/dependency-check-maven/src/main/java/org/owasp/dependencycheck/maven/BaseDependencyCheckMojo.java +++ b/dependency-check-maven/src/main/java/org/owasp/dependencycheck/maven/BaseDependencyCheckMojo.java @@ -595,28 +595,6 @@ public abstract class BaseDependencyCheckMojo extends AbstractMojo implements Ma 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 * list. @@ -1157,60 +1135,6 @@ public abstract class BaseDependencyCheckMojo extends AbstractMojo implements Ma 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 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); - } - } - } - } - } - } // } diff --git a/dependency-check-maven/src/test/java/org/owasp/dependencycheck/maven/BaseTest.java b/dependency-check-maven/src/test/java/org/owasp/dependencycheck/maven/BaseTest.java index 686e3e6b4..ef23a50ce 100644 --- a/dependency-check-maven/src/test/java/org/owasp/dependencycheck/maven/BaseTest.java +++ b/dependency-check-maven/src/test/java/org/owasp/dependencycheck/maven/BaseTest.java @@ -39,20 +39,9 @@ public class BaseTest { @BeforeClass public static void setUpClass() throws Exception { Settings.initialize(); - InputStream mojoProperties = null; - try { - mojoProperties = BaseTest.class.getClassLoader().getResourceAsStream(BaseTest.PROPERTIES_FILE); + try (InputStream mojoProperties = BaseTest.class.getClassLoader().getResourceAsStream(BaseTest.PROPERTIES_FILE)) { Settings.mergeProperties(mojoProperties); - } finally { - if (mojoProperties != null) { - try { - mojoProperties.close(); - } catch (IOException ex) { - Logger.getLogger(BaseTest.class.getName()).log(Level.SEVERE, null, ex); - } - } } - } @AfterClass diff --git a/dependency-check-utils/src/main/java/org/owasp/dependencycheck/utils/Checksum.java b/dependency-check-utils/src/main/java/org/owasp/dependencycheck/utils/Checksum.java index 71f316b8f..643b83aea 100644 --- a/dependency-check-utils/src/main/java/org/owasp/dependencycheck/utils/Checksum.java +++ b/dependency-check-utils/src/main/java/org/owasp/dependencycheck/utils/Checksum.java @@ -65,11 +65,8 @@ public final class Checksum { */ public static byte[] getChecksum(String algorithm, File file) throws NoSuchAlgorithmException, IOException { final MessageDigest md = MessageDigest.getInstance(algorithm); - FileInputStream fis = null; - FileChannel ch = null; - try { - fis = new FileInputStream(file); - ch = fis.getChannel(); + try (FileInputStream fis = new FileInputStream(file); + FileChannel ch = fis.getChannel()) { final ByteBuffer buf = ByteBuffer.allocateDirect(8192); int b = ch.read(buf); while (b != -1 && b != 0) { @@ -81,21 +78,6 @@ public final class Checksum { b = ch.read(buf); } 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); - } - } } } diff --git a/dependency-check-utils/src/main/java/org/owasp/dependencycheck/utils/Settings.java b/dependency-check-utils/src/main/java/org/owasp/dependencycheck/utils/Settings.java index 84174243d..aac1d40ed 100644 --- a/dependency-check-utils/src/main/java/org/owasp/dependencycheck/utils/Settings.java +++ b/dependency-check-utils/src/main/java/org/owasp/dependencycheck/utils/Settings.java @@ -433,10 +433,8 @@ public final class Settings { * @param propertiesFilePath the path to the base properties file to load */ private Settings(String propertiesFilePath) { - InputStream in = null; props = new Properties(); - try { - in = this.getClass().getClassLoader().getResourceAsStream(propertiesFilePath); + try (InputStream in = this.getClass().getClassLoader().getResourceAsStream(propertiesFilePath)) { props.load(in); } catch (NullPointerException ex) { LOGGER.error("Did not find settings file '{}'.", propertiesFilePath); @@ -444,14 +442,6 @@ public final class Settings { } catch (IOException ex) { LOGGER.error("Unable to load settings from '{}'.", propertiesFilePath); LOGGER.debug("", ex); - } finally { - if (in != null) { - try { - in.close(); - } catch (IOException ex) { - LOGGER.trace("", ex); - } - } } logProperties("Properties loaded", props); } @@ -644,18 +634,8 @@ public final class Settings { * the properties */ public static void mergeProperties(File filePath) throws FileNotFoundException, IOException { - FileInputStream fis = null; - try { - fis = new FileInputStream(filePath); + try (FileInputStream fis = new FileInputStream(filePath)) { 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 */ public static void mergeProperties(String filePath) throws FileNotFoundException, IOException { - FileInputStream fis = null; - try { - fis = new FileInputStream(filePath); + try (FileInputStream fis = new FileInputStream(filePath)) { 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())) { 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())); } } diff --git a/dependency-check-utils/src/test/java/org/owasp/dependencycheck/utils/ExpectedObjectInputStreamTest.java b/dependency-check-utils/src/test/java/org/owasp/dependencycheck/utils/ExpectedObjectInputStreamTest.java index dc991c390..0907da9bb 100644 --- a/dependency-check-utils/src/test/java/org/owasp/dependencycheck/utils/ExpectedObjectInputStreamTest.java +++ b/dependency-check-utils/src/test/java/org/owasp/dependencycheck/utils/ExpectedObjectInputStreamTest.java @@ -39,12 +39,10 @@ public class ExpectedObjectInputStreamTest { */ @Test public void testResolveClass() { - ObjectOutputStream out = null; - try { - List data = new ArrayList<>(); - data.add(new SimplePojo()); - ByteArrayOutputStream mem = new ByteArrayOutputStream(); - out = new ObjectOutputStream(new BufferedOutputStream(mem)); + List data = new ArrayList<>(); + data.add(new SimplePojo()); + try (ByteArrayOutputStream mem = new ByteArrayOutputStream(); + ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(mem))) { out.writeObject(data); out.flush(); byte[] buf = mem.toByteArray(); @@ -54,14 +52,6 @@ public class ExpectedObjectInputStreamTest { instance.readObject(); } catch (IOException | ClassNotFoundException ex) { fail(ex.getMessage()); - } finally { - try { - if (out != null) { - out.close(); - } - } catch (IOException ex) { - ex.printStackTrace(); - } } }