Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Java7 updates and cleanup #681

Merged
merged 17 commits into from
Mar 12, 2017
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
updated to use try with resouces
  • Loading branch information
jeremylong committed Mar 12, 2017
commit 7a88981aa4366adb66ecd979dd4832fa03d0af10
Original file line number Diff line number Diff line change
Expand Up @@ -144,24 +144,15 @@ public void execute() throws BuildException {
*/
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.";
if (this.failOnError) {
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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -130,10 +130,9 @@ private void loadSuppressionData() throws SuppressionParseException {
}
} 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");
Expand All @@ -143,14 +142,6 @@ private void loadSuppressionData() throws SuppressionParseException {
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);
}
}
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -535,14 +535,12 @@ private void extractArchive(ArchiveInputStream input, File destination, Engine e
*/
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);
Expand All @@ -552,8 +550,6 @@ private static void extractAcceptedFile(ArchiveInputStream input, File file) thr
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);
}
}

Expand All @@ -567,15 +563,11 @@ private static void extractAcceptedFile(ArchiveInputStream input, File file) thr
*/
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);
}
}

Expand Down Expand Up @@ -609,7 +601,6 @@ private boolean isZipFileActuallyJarFile(Dependency dependency) {
} finally {
ZipFile.closeQuietly(zip);
}

return isJar;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -178,15 +178,15 @@ public void analyzeDependency(Dependency dependency, Engine engine)
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.");
LOGGER.error("----------------------------------------------------");
throw new AnalysisException("Couldn't parse Assembly Analyzer results (GrokAssembly)", saxe);
}
// This shouldn't happen

}

/**
Expand All @@ -198,46 +198,27 @@ public void analyzeDependency(Dependency dependency, Engine engine)
@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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
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;
Expand Down Expand Up @@ -101,9 +102,7 @@ protected void initializeFileTypeAnalyzer() throws InitializationException {
*/
@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();
Expand All @@ -120,18 +119,10 @@ protected void analyzeDependency(Dependency dependency, Engine engine) throws An
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);
}
}
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -322,24 +322,14 @@ private Properties retrievePomProperties(String path, final JarFile jar) {
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);
} catch (UnsupportedEncodingException ex) {
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;
Expand Down Expand Up @@ -377,24 +367,18 @@ private List<String> retrievePomListing(final JarFile jar) throws IOException {
* 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;
}
Expand Down Expand Up @@ -908,9 +892,7 @@ private boolean isImportPackage(String key, String value) {
*/
private List<ClassNameInformation> collectClassNames(Dependency dependency) {
final List<ClassNameInformation> classNames = new ArrayList<>();
JarFile jar = null;
try {
jar = new JarFile(dependency.getActualFilePath());
try (JarFile jar = new JarFile(dependency.getActualFilePath())) {
final Enumeration<JarEntry> entries = jar.entries();
while (entries.hasMoreElements()) {
final JarEntry entry = entries.nextElement();
Expand All @@ -924,14 +906,6 @@ private List<ClassNameInformation> collectClassNames(Dependency dependency) {
} 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;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -121,17 +121,9 @@ protected String getAnalyzerEnabledSettingKey() {
}

@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();
Expand All @@ -151,8 +143,8 @@ protected void analyzeDependency(Dependency dependency, Engine engine)
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);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -132,20 +132,10 @@ public void analyzeDependency(Dependency dependency, Engine engine) throws Analy
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) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -360,20 +360,12 @@ private static InternetHeaders getManifestProperties(File manifest) {
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;
Expand Down
Loading