Merge branch 'warning-fixes-resource-management' of https://github.com/liblit/WALA

This commit is contained in:
Julian Dolby 2017-03-13 10:44:38 -04:00
commit bb0f38338e
42 changed files with 462 additions and 463 deletions

View File

@ -111,9 +111,10 @@ public abstract class JavaSourceAnalysisEngine<I extends InstanceKey> extends Ab
scope = makeSourceAnalysisScope();
if (getExclusionsFile() != null) {
InputStream is = new File(getExclusionsFile()).exists()? new FileInputStream(getExclusionsFile()): FileProvider.class.getClassLoader().getResourceAsStream(getExclusionsFile());
try (final InputStream is = new File(getExclusionsFile()).exists()? new FileInputStream(getExclusionsFile()): FileProvider.class.getClassLoader().getResourceAsStream(getExclusionsFile())) {
scope.setExclusions(new FileOfClasses(is));
}
}
for (Module M : this.systemEntries) {
scope.addToScope(scope.getPrimordialLoader(), M);

View File

@ -251,16 +251,15 @@ public class DomLessSourceExtractor extends JSSourceExtractor {
private void getScriptFromUrl(String urlAsString, ITag scriptTag) throws IOException, MalformedURLException {
URL scriptSrc = new URL(entrypointUrl, urlAsString);
Reader scriptInputStream;
BOMInputStream bs;
try {
BOMInputStream bs = new BOMInputStream(scriptSrc.openConnection().getInputStream(), false,
bs = new BOMInputStream(scriptSrc.openConnection().getInputStream(), false,
ByteOrderMark.UTF_8,
ByteOrderMark.UTF_16LE, ByteOrderMark.UTF_16BE,
ByteOrderMark.UTF_32LE, ByteOrderMark.UTF_32BE);
if (bs.hasBOM()) {
System.err.println("removing BOM " + bs.getBOM());
}
scriptInputStream = new InputStreamReader(bs);
} catch (Exception e) {
//it looks like this happens when we can't resolve the url?
if (DEBUG) {
@ -270,22 +269,17 @@ public class DomLessSourceExtractor extends JSSourceExtractor {
}
return;
}
BufferedReader scriptReader = null;
try {
try (
final Reader scriptInputStream = new InputStreamReader(bs);
final BufferedReader scriptReader = new BufferedReader(scriptInputStream);
) {
String line;
scriptReader = new BufferedReader(scriptInputStream);
StringBuffer x = new StringBuffer();
while ((line = scriptReader.readLine()) != null) {
x.append(line).append("\n");
}
scriptRegion.println(x.toString(), scriptTag.getElementPosition(), scriptSrc, false);
} finally {
if (scriptReader != null) {
scriptReader.close();
}
}
}
@ -329,9 +323,11 @@ public class DomLessSourceExtractor extends JSSourceExtractor {
public Set<MappedSourceModule> extractSources(URL entrypointUrl, IHtmlParser htmlParser, IUrlResolver urlResolver)
throws IOException, Error {
Reader inputStreamReader = WebUtil.getStream(entrypointUrl);
IGeneratorCallback htmlCallback = createHtmlCallback(entrypointUrl, urlResolver);
IGeneratorCallback htmlCallback;
try (Reader inputStreamReader = WebUtil.getStream(entrypointUrl)) {
htmlCallback = createHtmlCallback(entrypointUrl, urlResolver);
htmlParser.parse(entrypointUrl, inputStreamReader, htmlCallback, entrypointUrl.getFile());
}
SourceRegion finalRegion = new SourceRegion();
htmlCallback.writeToFinalRegion(finalRegion);
@ -339,7 +335,10 @@ public class DomLessSourceExtractor extends JSSourceExtractor {
// writing the final region into one SourceFileModule.
File outputFile = createOutputFile(entrypointUrl, DELETE_UPON_EXIT, USE_TEMP_NAME);
tempFile = outputFile;
FileMapping fileMapping = finalRegion.writeToFile(new PrintWriter(new FileWriter(outputFile)));
FileMapping fileMapping;
try (final PrintWriter printer = new PrintWriter(new FileWriter(outputFile))) {
fileMapping = finalRegion.writeToFile(printer);
}
if (fileMapping == null) {
fileMapping = new EmptyFileMapping();
}

View File

@ -74,8 +74,8 @@ public class LoadFileTargetSelector implements MethodTargetSelector {
URL url = new URL(builder.getBaseURL(), str);
if(!loadedFiles.contains(url)) {
// try to open the input stream for the URL. if it fails, we'll get an IOException and fall through to default case
InputStream inputStream = url.openConnection().getInputStream();
inputStream.close();
try (InputStream inputStream = url.openConnection().getInputStream()) {
}
JSCallGraphUtil.loadAdditionalFile(builder.getClassHierarchy() , cl, url);
loadedFiles.add(url);
IClass script = builder.getClassHierarchy().lookupClass(TypeReference.findOrCreate(cl.getReference(), "L" + url.getFile()));

View File

@ -28,17 +28,17 @@ public class CAstPrinter {
}
@Override
public void write(char[] cbuf, int off, int len) throws IOException {
public void write(char[] cbuf, int off, int len) {
sb.append(new String(cbuf, off, len));
}
@Override
public void flush() throws IOException {
public void flush() {
// do nothing
}
@Override
public void close() throws IOException {
public void close() {
// do nothing
}
}
@ -146,15 +146,17 @@ public class CAstPrinter {
public String doPrint(CAstNode top, CAstSourcePositionMap pos) {
final StringBuffer sb = new StringBuffer();
Writer writer = new StringWriter(sb);
try (final StringWriter writer = new StringWriter(sb)) {
printTo(top, pos, writer);
}
return sb.toString();
}
public String doPrint(CAstEntity ce) {
final StringBuffer sb = new StringBuffer();
StringWriter writer = new StringWriter(sb);
try (final StringWriter writer = new StringWriter(sb)) {
printTo(ce, writer);
}
return sb.toString();
}

View File

@ -58,8 +58,10 @@ public class CFGSanitizerTest extends WalaTestCase {
ClassHierarchy cha = ClassHierarchyFactory.make(scope);
ClassLoader cl = CFGSanitizerTest.class.getClassLoader();
InputStream s = cl.getResourceAsStream("natives.xml");
XMLMethodSummaryReader summary = new XMLMethodSummaryReader(s, scope);
XMLMethodSummaryReader summary;
try (final InputStream s = cl.getResourceAsStream("natives.xml")) {
summary = new XMLMethodSummaryReader(s, scope);
}
AnalysisOptions options = new AnalysisOptions(scope, null);
Map<MethodReference, MethodSummary> summaries = summary.getSummaries();
for (MethodReference mr : summaries.keySet()) {

View File

@ -192,9 +192,9 @@ public abstract class DynamicCallGraphTestBase extends WalaTestCase {
}
protected void check(CallGraph staticCG, EdgesTest test, Predicate<MethodReference> filter) throws IOException {
BufferedReader dynamicEdgesFile = new BufferedReader(new InputStreamReader(new GZIPInputStream(new FileInputStream(cgLocation))));
String line;
int lines = 0;
try (final BufferedReader dynamicEdgesFile = new BufferedReader(new InputStreamReader(new GZIPInputStream(new FileInputStream(cgLocation))))) {
String line;
loop: while ((line = dynamicEdgesFile.readLine()) != null) {
lines++;
StringTokenizer edge = new StringTokenizer(line, "\t");
@ -226,8 +226,7 @@ public abstract class DynamicCallGraphTestBase extends WalaTestCase {
}
test.edgesTest(staticCG, caller, callee);
}
dynamicEdgesFile.close();
}
Assert.assertTrue("more than one edge", lines > 0);
}

View File

@ -931,9 +931,10 @@ public class SlicerTest {
public static void dumpSliceToFile(Collection<Statement> slice, String fileName) throws FileNotFoundException {
File f = new File(fileName);
FileOutputStream fo = new FileOutputStream(f);
PrintWriter w = new PrintWriter(fo);
try (final PrintWriter w = new PrintWriter(fo)) {
dumpSlice(slice, w);
}
}
public static CGNode findMainMethod(CallGraph cg) {
Descriptor d = Descriptor.findOrCreateUTF8("([Ljava/lang/String;)V");

View File

@ -67,8 +67,7 @@ public class WalaUtil {
}
System.err.print("dumping ir...");
String irFile = p.getProperty(WalaProperties.OUTPUT_DIR) + File.separatorChar + benchName + "-ir.txt";
try {
PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(irFile)));
try (final PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(irFile)))) {
for (Iterator<? extends CGNode> iter = cg.iterator(); iter.hasNext();) {
CGNode node = iter.next();
IR ir = node.getIR();
@ -79,7 +78,6 @@ public class WalaUtil {
writer.println(ir);
writer.println("");
}
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();

View File

@ -105,7 +105,9 @@ public class SimpleThreadEscapeAnalysis extends AbstractAnalysisEngine {
collectJars(files[i], result);
}
} else if (f.getAbsolutePath().endsWith(".jar")) {
result.add(new JarFile(f, false));
try (final JarFile jar = new JarFile(f, false)) {
result.add(jar);
}
}
}

View File

@ -93,7 +93,10 @@ public class DalvikCallGraphTestBase extends DynamicCallGraphTestBase {
public void dynamicCG(File javaJarPath, String mainClass, String... args) throws FileNotFoundException, IOException, ClassNotFoundException, InvalidClassFileException, FailureException, SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException, InterruptedException {
File F = TemporaryFile.streamToFile(new File("test_jar.jar"), new FileInputStream(javaJarPath));
File F;
try (final FileInputStream in = new FileInputStream(javaJarPath)) {
F = TemporaryFile.streamToFile(new File("test_jar.jar"), in);
}
F.deleteOnExit();
instrument(F.getAbsolutePath());
run(mainClass.substring(1).replace('/', '.'), "LibraryExclusions.txt", args);

View File

@ -73,7 +73,9 @@ public class DexFileModule implements Module {
public static DexFileModule make(File f) throws IllegalArgumentException, IOException {
if (f.getName().endsWith("jar")) {
return new DexFileModule(new JarFile(f));
try (final JarFile jar = new JarFile(f)) {
return new DexFileModule(jar);
}
} else {
return new DexFileModule(f);
}

View File

@ -39,8 +39,9 @@ public class AndroidAnalysisScope {
scope = AnalysisScope.createJavaAnalysisScope();
File exclusionsFile = new File(exclusions);
InputStream fs = exclusionsFile.exists()? new FileInputStream(exclusionsFile): FileProvider.class.getClassLoader().getResourceAsStream(exclusionsFile.getName());
try (final InputStream fs = exclusionsFile.exists()? new FileInputStream(exclusionsFile): FileProvider.class.getClassLoader().getResourceAsStream(exclusionsFile.getName())) {
scope.setExclusions(new FileOfClasses(fs));
}
scope.setLoaderImpl(ClassLoaderReference.Primordial,
"com.ibm.wala.dalvik.classLoader.WDexClassLoaderImpl");
@ -50,7 +51,9 @@ public class AndroidAnalysisScope {
scope.addToScope(ClassLoaderReference.Primordial, DexFileModule.make(new File(al)));
} catch (Exception e) {
e.printStackTrace();
scope.addToScope(ClassLoaderReference.Primordial, new JarFileModule(new JarFile(new File(al))));
try (final JarFile jar = new JarFile(new File(al))) {
scope.addToScope(ClassLoaderReference.Primordial, new JarFileModule(jar));
}
}
}

View File

@ -101,8 +101,8 @@ public class AndroidManifestXMLReader {
if (xmlFile == null) {
throw new IllegalArgumentException("xmlFile may not be null");
}
try {
readXML(new FileInputStream(xmlFile));
try (final FileInputStream in = new FileInputStream(xmlFile)) {
readXML(in);
} catch (Exception e) {
e.printStackTrace();
throw new IllegalStateException("Exception was thrown");

View File

@ -37,6 +37,7 @@
*/
package com.ibm.wala.cast.java.test;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
@ -50,8 +51,14 @@ public class JDTJavaIRTests extends JavaIRTests {
public static final String PROJECT_ZIP = "test_project.zip";
public static final ZippedProjectData PROJECT = new ZippedProjectData(Activator.getDefault(), PROJECT_NAME, PROJECT_ZIP);
public static final ZippedProjectData PROJECT;
static {
try {
PROJECT = new ZippedProjectData(Activator.getDefault(), PROJECT_NAME, PROJECT_ZIP);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private final ZippedProjectData project;
public JDTJavaIRTests() {

View File

@ -10,6 +10,8 @@
*******************************************************************************/
package com.ibm.wala.ide.jsdt.tests;
import java.io.IOException;
import com.ibm.wala.ide.tests.util.EclipseTestUtil.ZippedProjectData;
public class JSProjectScopeTest extends AbstractJSProjectScopeTest {
@ -18,7 +20,14 @@ public class JSProjectScopeTest extends AbstractJSProjectScopeTest {
public static final String PROJECT_ZIP = "test_js_project.zip";
public static final ZippedProjectData PROJECT = new ZippedProjectData(Activator.getDefault(), PROJECT_NAME, PROJECT_ZIP);
public static final ZippedProjectData PROJECT;
static {
try {
PROJECT = new ZippedProjectData(Activator.getDefault(), PROJECT_NAME, PROJECT_ZIP);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public JSProjectScopeTest() {
super(PROJECT);

View File

@ -41,14 +41,14 @@ public class EclipseTestUtil {
public final String projectName;
public final String zipFileName;
public ZippedProjectData(Plugin sourcePlugin, String projectName, String zipFileName) {
public ZippedProjectData(Plugin sourcePlugin, String projectName, String zipFileName) throws IOException {
this.sourcePlugin = sourcePlugin;
this.projectName = projectName;
this.zipFileName = zipFileName;
open();
}
private void open() {
private void open() throws IOException {
importZippedProject(sourcePlugin, projectName, zipFileName, new NullProgressMonitor());
}
@ -57,11 +57,12 @@ public class EclipseTestUtil {
}
}
public static void importZippedProject(Plugin plugin, String projectName, String zipFileName, IProgressMonitor monitor) {
ZipFile zipFile = getZipFile(plugin, zipFileName);
public static void importZippedProject(Plugin plugin, String projectName, String zipFileName, IProgressMonitor monitor) throws IOException {
try (final ZipFile zipFile = getZipFile(plugin, zipFileName)) {
createOpenProject(projectName);
importZipfile(projectName, zipFile, monitor);
}
}
public static void createOpenProject(String projectName) {
IWorkspaceRoot root = getWorkspace();

View File

@ -60,9 +60,10 @@ abstract public class EclipseProjectAnalysisEngine<P, I extends InstanceKey> ext
ePath = createProjectPath(project);
super.scope = ePath.toAnalysisScope(makeAnalysisScope());
if (getExclusionsFile() != null) {
InputStream is = new File(getExclusionsFile()).exists()? new FileInputStream(getExclusionsFile()): FileProvider.class.getClassLoader().getResourceAsStream(getExclusionsFile());
try (final InputStream is = new File(getExclusionsFile()).exists()? new FileInputStream(getExclusionsFile()): FileProvider.class.getClassLoader().getResourceAsStream(getExclusionsFile())) {
scope.setExclusions(new FileOfClasses(is));
}
}
} catch (CoreException e) {
assert false : e.getMessage();
}

View File

@ -75,7 +75,9 @@ public class EclipseFileProvider extends FileProvider {
IPath path = new Path(fileName);
if (workspaceRoot_getFile.invoke(workspaceRoot, path) != null) {
return new JarFileModule(new JarFile(fileName, false));
try (final JarFile jar = new JarFile(fileName, false)) {
return new JarFileModule(jar);
}
}
} catch (Exception e) {
}
@ -105,7 +107,10 @@ public class EclipseFileProvider extends FileProvider {
*/
private JarFileModule getFromPlugin(Plugin p, String fileName) throws IOException {
URL url = getFileURLFromPlugin(p, fileName);
return (url == null) ? null : new JarFileModule(new JarFile(filePathFromURL(url)));
if (url == null) return null;
try (final JarFile jar = new JarFile(filePathFromURL(url))) {
return new JarFileModule(jar);
}
}
/**

View File

@ -256,7 +256,6 @@ public class AndroidAnalysisContext {
throw new IllegalArgumentException("cha cannot be null");
}
InputStream s = null;
try {
Set<TypeReference> summaryClasses = HashSetFactory.make();
Map<MethodReference, MethodSummary> summaries = HashMapFactory.make();
@ -271,9 +270,9 @@ public class AndroidAnalysisContext {
//
// }
s = new FileProvider().getInputStreamFromClassLoader(pathToSpec
try (final InputStream s = new FileProvider().getInputStreamFromClassLoader(pathToSpec
+ File.separator + methodSpec,
AndroidAnalysisContext.class.getClassLoader());
AndroidAnalysisContext.class.getClassLoader())) {
XMLMethodSummaryReader nativeSummaries = loadMethodSummaries(scope,
s);
@ -295,43 +294,26 @@ public class AndroidAnalysisContext {
cha.getLoader(scope.getLoader(Atom
.findOrCreateUnicodeAtom("Synthetic"))));
options.setSelector(cs);
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (null != s) {
try {
s.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private static XMLMethodSummaryReader loadMethodSummaries(
AnalysisScope scope, InputStream xmlIStream)
throws FileNotFoundException {
InputStream s = xmlIStream;
XMLMethodSummaryReader summary = null;
try {
if (null == s) {
s = AndroidAnalysisContext.class.getClassLoader()
try (InputStream s = xmlIStream != null ? xmlIStream :
AndroidAnalysisContext.class.getClassLoader()
.getResourceAsStream(
pathToSpec + File.separator + methodSpec);
}
summary = new XMLMethodSummaryReader(s, scope);
} finally {
try {
if (null != s) {
s.close();
}
pathToSpec + File.separator + methodSpec)) {
return new XMLMethodSummaryReader(s, scope);
} catch (IOException e) {
e.printStackTrace();
}
}
return summary;
return null;
}
/**

View File

@ -150,7 +150,9 @@ public class CGAnalysisContext<E extends ISSABasicBlock> {
SSAPropagationCallGraphBuilder cgb;
if (null != options.getSummariesURI()) {
extraSummaries.add(new FileInputStream(new File(options.getSummariesURI())));
try (final FileInputStream in = new FileInputStream(new File(options.getSummariesURI()))) {
extraSummaries.add(in);
}
}
cgb = AndroidAnalysisContext.makeZeroCFABuilder(analysisOptions, cache, cha, scope,

View File

@ -162,9 +162,9 @@ public class DexDotUtil extends DotUtil {
}
try {
File f = new File(dotfile);
FileWriter fw = new FileWriter(f);
try (final FileWriter fw = new FileWriter(f)) {
fw.write(dotStringBuffer.toString());
fw.close();
}
return f;
} catch (Exception e) {

View File

@ -44,8 +44,7 @@ public class AddBytecodeDebug {
for (int i = 0; i < 1; i++) {
instrumenter = new OfflineInstrumenter(true);
Writer w = new BufferedWriter(new FileWriter("report", false));
try (final Writer w = new BufferedWriter(new FileWriter("report", false))) {
args = instrumenter.parseStandardArgs(args);
instrumenter.setPassUnmodifiedClasses(true);
instrumenter.beginTraversal();
@ -56,6 +55,7 @@ public class AddBytecodeDebug {
instrumenter.close();
}
}
}
private static void doClass(final ClassInstrumenter ci, Writer w) throws Exception {
final String className = ci.getReader().getName();

View File

@ -62,7 +62,7 @@ public class Bench {
public static void main(String[] args) throws Exception {
for (int i = 0; i < 1; i++) {
Writer w = new BufferedWriter(new FileWriter("report", false));
try (final Writer w = new BufferedWriter(new FileWriter("report", false))) {
args = instrumenter.parseStandardArgs(args);
if (args.length > 0) {
@ -80,6 +80,7 @@ public class Bench {
while ((ci = instrumenter.nextClass()) != null) {
doClass(ci, w);
}
}
instrumenter.close();
}
}

View File

@ -43,7 +43,7 @@ public class InterfaceAnalyzer {
public static void main(String[] args) throws Exception {
OfflineInstrumenter instrumenter = new OfflineInstrumenter(true);
Writer w = new BufferedWriter(new OutputStreamWriter(System.out));
try (final Writer w = new BufferedWriter(new OutputStreamWriter(System.out))) {
args = instrumenter.parseStandardArgs(args);
@ -61,7 +61,7 @@ public class InterfaceAnalyzer {
w.write(k + "\t" + t.totalOccurrences + "\t" + t.methodOccurrences + "\t" + t.publicMethodOccurrences + "\t"
+ t.foreignPublicMethodOccurrences + "\n");
}
w.close();
}
}
static int methodUID = 0;

View File

@ -59,7 +59,7 @@ public class Mangler {
for (int i = 0; i < 1; i++) {
instrumenter = new OfflineInstrumenter(true);
Writer w = new BufferedWriter(new FileWriter("report", false));
try (final Writer w = new BufferedWriter(new FileWriter("report", false))) {
args = instrumenter.parseStandardArgs(args);
int seed;
@ -67,7 +67,6 @@ public class Mangler {
seed = Integer.parseInt(args[0]);
} catch (NumberFormatException ex) {
System.err.println("Invalid number: " + args[0]);
w.close();
return;
}
@ -79,6 +78,7 @@ public class Mangler {
while ((ci = instrumenter.nextClass()) != null) {
doClass(ci, w, r);
}
}
instrumenter.close();
}
}

View File

@ -41,7 +41,7 @@ public class Statistics {
for (int i = 0; i < 1; i++) {
instrumenter = new OfflineInstrumenter(true);
Writer w = new BufferedWriter(new FileWriter("report", false));
try (Writer w = new BufferedWriter(new FileWriter("report", false))) {
args = instrumenter.parseStandardArgs(args);
@ -51,7 +51,7 @@ public class Statistics {
doClass(ci, w);
}
instrumenter.close();
w.close();
}
}
}

View File

@ -73,7 +73,7 @@ public class OfflineDynamicCallGraph {
public static void main(String[] args) throws IOException, ClassNotFoundException, InvalidClassFileException, FailureException {
OfflineInstrumenter instrumenter;
ClassInstrumenter ci;
Writer w = new BufferedWriter(new FileWriter("report", false));
try (final Writer w = new BufferedWriter(new FileWriter("report", false))) {
for(int i = 0; i < args.length - 1; i++) {
if ("--runtime".equals(args[i])) {
@ -113,6 +113,7 @@ public class OfflineDynamicCallGraph {
instrumenter.outputModifiedClass(ci, cw);
}
}
}
instrumenter.close();
}

View File

@ -67,8 +67,8 @@ public class Runtime {
};
private Runtime(String fileName, String filterFileName, String policyClassName) {
try {
filter = new FileOfClasses(new FileInputStream(filterFileName));
try (final FileInputStream in = new FileInputStream(filterFileName)) {
filter = new FileOfClasses(in);
} catch (Exception e) {
filter = null;
}

View File

@ -40,9 +40,9 @@ public class CodeScraper implements ClassFileTransformer {
if (className == null || sourceFile == null || !sourceFile.endsWith("java") || true) try {
String log = prefix + File.separator + reader.getName() + ".class";
(new File(log)).getParentFile().mkdirs();
FileOutputStream f = new FileOutputStream(log);
try (final FileOutputStream f = new FileOutputStream(log)) {
f.write(classfileBuffer);
f.close();
}
} catch (IOException e) {
assert false : e;
}

View File

@ -89,9 +89,10 @@ public class AddSerialVersion {
} catch (NoSuchAlgorithmException e) {
throw new Error("SHA algorithm not supported: " + e.getMessage());
}
try (
SinkOutputStream sink = new SinkOutputStream();
DataOutputStream out = new DataOutputStream(new DigestOutputStream(sink, digest));
) {
try {
// step 1
out.writeUTF(r.getName());
@ -174,11 +175,8 @@ public class AddSerialVersion {
}
} catch (IOException e1) {
throw new Error("Unexpected IOException: " + e1.getMessage());
} finally {
try {
out.close();
} catch (IOException e2) {
}
} catch (IOException e2) {
}
byte[] hash = digest.digest();
@ -191,8 +189,8 @@ public class AddSerialVersion {
if (args[i] == null) {
throw new IllegalArgumentException("args[" + i + "] is null");
}
try {
byte[] data = Util.readFully(new FileInputStream(args[i]));
try (final FileInputStream in = new FileInputStream(args[i])) {
byte[] data = Util.readFully(in);
ClassReader r = new ClassReader(data);
System.out.println(Util.makeClass(r.getName()) + ": serialVersionUID = " + computeSerialVersionUID(r));
} catch (FileNotFoundException e) {

View File

@ -57,7 +57,7 @@ public class BatchVerifier {
}
}
PrintWriter w = new PrintWriter(new BufferedWriter(new FileWriter("report", false)));
try (final PrintWriter w = new PrintWriter(new BufferedWriter(new FileWriter("report", false)))) {
oi.beginTraversal();
ClassInstrumenter ci;
@ -70,6 +70,7 @@ public class BatchVerifier {
while ((ci = oi.nextClass()) != null) {
doClass(ci.getReader(), w);
}
}
oi.close();

View File

@ -55,8 +55,7 @@ public class BootstrapDumper {
assert f.exists();
urls[i-1] = f.toURI().toURL();
}
URLClassLoader image = URLClassLoader.newInstance(urls, BootstrapDumper.class.getClassLoader().getParent());
try (final URLClassLoader image = URLClassLoader.newInstance(urls, BootstrapDumper.class.getClassLoader().getParent())) {
System.err.println(image);
ClassInstrumenter ci;
@ -68,6 +67,7 @@ public class BootstrapDumper {
w.flush();
}
}
}
oi.close();
}

View File

@ -38,7 +38,7 @@ public class ClassSearcher {
public static void main(String[] args) throws Exception {
instrumenter = new OfflineInstrumenter(true);
Writer w = new BufferedWriter(new FileWriter("report", true));
try (final Writer w = new BufferedWriter(new FileWriter("report", true))) {
instrumenter.parseStandardArgs(args);
instrumenter.beginTraversal();
@ -47,7 +47,7 @@ public class ClassSearcher {
doClass(ci, w, instrumenter.getLastClassResourceName());
}
instrumenter.close();
w.close();
}
System.out.println("Classes scanned: " + scanned);
}

View File

@ -53,7 +53,7 @@ public class MethodTracer {
for (int i = 0; i < 1; i++) {
instrumenter = new OfflineInstrumenter(true);
Writer w = new BufferedWriter(new FileWriter("report", false));
try (final Writer w = new BufferedWriter(new FileWriter("report", false))) {
instrumenter.parseStandardArgs(args);
instrumenter.setPassUnmodifiedClasses(false);
@ -62,6 +62,7 @@ public class MethodTracer {
while ((ci = instrumenter.nextClass()) != null) {
doClass(ci, w);
}
}
instrumenter.close();
}
}

View File

@ -127,6 +127,7 @@ public abstract class OfflineInstrumenterBase {
}
@Override
@SuppressWarnings("resource")
public InputStream open() throws IOException {
JarFile cachedJar = openCachedJar(file);
return cachedJar.getInputStream(cachedJar.getEntry(name));
@ -150,6 +151,7 @@ public abstract class OfflineInstrumenterBase {
/**
* Get the underlying ZipEntry corresponding to this resource.
*/
@SuppressWarnings("resource")
public ZipEntry getEntry() throws IOException {
JarFile cachedJar = openCachedJar(file);
return cachedJar.getEntry(name);
@ -229,13 +231,13 @@ public abstract class OfflineInstrumenterBase {
* Add a JAR file containing source classes to instrument.
*/
final public void addInputJar(File f) throws IOException {
JarFile jf = new JarFile(f, false);
try (final JarFile jf = new JarFile(f, false)) {
for (Enumeration<JarEntry> e = jf.entries(); e.hasMoreElements();) {
JarEntry entry = e.nextElement();
String name = entry.getName();
inputs.add(new JarInput(f, name));
}
jf.close();
}
}
/**
@ -387,14 +389,11 @@ public abstract class OfflineInstrumenterBase {
if (ignoringInputs.get(inputIndex - 1) || !in.isClass()) {
continue;
}
BufferedInputStream s = new BufferedInputStream(in.open());
try {
try (final BufferedInputStream s = new BufferedInputStream(in.open())) {
Object r = makeClassFromStream(in.getInputName(), s);
String name = getClassName(r);
in.setClassName(name);
return r;
} finally {
s.close();
}
}
}
@ -454,7 +453,9 @@ public abstract class OfflineInstrumenterBase {
throw new IllegalStateException("Output file was not set");
}
outputJar = new JarOutputStream(new FileOutputStream(outputFile));
@SuppressWarnings("resource")
final FileOutputStream out = new FileOutputStream(outputFile);
outputJar = new JarOutputStream(out);
}
}
@ -539,8 +540,7 @@ public abstract class OfflineInstrumenterBase {
if (in instanceof JarInput) {
JarInput jin = (JarInput) in;
ZipEntry entry = jin.getEntry();
InputStream s = jin.open();
try {
try (final InputStream s = jin.open()) {
ZipEntry newEntry = new ZipEntry(entry.getName());
newEntry.setComment(entry.getComment());
newEntry.setExtra(entry.getExtra());
@ -548,8 +548,6 @@ public abstract class OfflineInstrumenterBase {
putNextEntry(newEntry);
copyStream(s, outputJar);
outputJar.closeEntry();
} finally {
s.close();
}
} else {
throw new Error("Unknown non-class input: " + in);
@ -557,8 +555,7 @@ public abstract class OfflineInstrumenterBase {
} else {
String name = in.getClassName();
if (name == null) {
BufferedInputStream s = new BufferedInputStream(in.open(), 65536);
try {
try (final BufferedInputStream s = new BufferedInputStream(in.open(), 65536)) {
Object cl = makeClassFromStream(in.getInputName(), s);
String entryName = toEntryName(getClassName(cl));
if (!entryNames.contains(entryName)) {
@ -568,21 +565,16 @@ public abstract class OfflineInstrumenterBase {
clOut.flush();
outputJar.closeEntry();
}
} finally {
s.close();
}
} else {
String entryName = toEntryName(name);
if (!entryNames.contains(entryName)) {
BufferedInputStream s = new BufferedInputStream(in.open());
try {
try (final BufferedInputStream s = new BufferedInputStream(in.open())) {
putNextEntry(new ZipEntry(entryName));
BufferedOutputStream clOut = new BufferedOutputStream(outputJar);
copyStream(s, clOut);
clOut.flush();
outputJar.closeEntry();
} finally {
s.close();
}
}
}

View File

@ -71,9 +71,9 @@ public class Util {
}
// create a memory buffer to which to dump the trace
ByteArrayOutputStream traceDump = new ByteArrayOutputStream();
PrintWriter w = new PrintWriter(traceDump);
try (final PrintWriter w = new PrintWriter(traceDump)) {
thrown.printStackTrace(w);
w.close();
}
return traceDump.toString();
}

View File

@ -38,7 +38,7 @@ public class FileOfClasses extends SetOfClasses implements Serializable {
if (input == null) {
throw new IllegalArgumentException("null input");
}
BufferedReader is = new BufferedReader(new InputStreamReader(input));
try (final BufferedReader is = new BufferedReader(new InputStreamReader(input))) {
StringBuffer regex = null;
String line;
@ -57,8 +57,7 @@ public class FileOfClasses extends SetOfClasses implements Serializable {
this.regex = regex.toString();
needsCompile = true;
}
is.close();
}
}
private void compile() {

View File

@ -84,27 +84,15 @@ public class FileUtil {
if (destFileName == null) {
throw new IllegalArgumentException("destFileName is null");
}
FileChannel src = null;
FileChannel dest = null;
try {
src = new FileInputStream(srcFileName).getChannel();
dest = new FileOutputStream(destFileName).getChannel();
try (
final FileInputStream srcStream = new FileInputStream(srcFileName);
final FileOutputStream dstStream = new FileOutputStream(destFileName);
final FileChannel src = srcStream.getChannel();
final FileChannel dest = dstStream.getChannel();
) {
long n = src.size();
MappedByteBuffer buf = src.map(FileChannel.MapMode.READ_ONLY, 0, n);
dest.write(buf);
} finally {
if (dest != null) {
try {
dest.close();
} catch (IOException e1) {
}
}
if (src != null) {
try {
src.close();
} catch (IOException e1) {
}
}
}
}
@ -175,7 +163,7 @@ public class FileUtil {
if (s == null) {
throw new IllegalArgumentException("null s");
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
try (final ByteArrayOutputStream out = new ByteArrayOutputStream()) {
byte[] b = new byte[1024];
int n = s.read(b);
while (n != -1) {
@ -183,9 +171,9 @@ public class FileUtil {
n = s.read(b);
}
byte[] bb = out.toByteArray();
out.close();
return bb;
}
}
/**
* write string s into file f
@ -195,9 +183,9 @@ public class FileUtil {
* @throws IOException
*/
public static void writeFile(File f, String content) throws IOException {
final FileWriter fw = new FileWriter(f);
try (final FileWriter fw = new FileWriter(f)) {
fw.append(content);
fw.close();
}
}
public static void recurseFiles(VoidFunction<File> action, final Predicate<File> filter, File top) {

View File

@ -41,7 +41,7 @@ public class TemporaryFile {
}
public static File streamToFile(File F, InputStream... inputs) throws IOException {
FileOutputStream output = new FileOutputStream(F);
try (final FileOutputStream output = new FileOutputStream(F)) {
int read;
byte[] buffer = new byte[ 1024 ];
@ -51,19 +51,18 @@ public class TemporaryFile {
}
input.close();
}
output.close();
}
return F;
}
public static File stringToFile(File F, String... inputs) throws IOException {
FileOutputStream output = new FileOutputStream(F);
try (final FileOutputStream output = new FileOutputStream(F)) {
for(String input : inputs) {
output.write(input.getBytes());
}
}
output.close();
return F;
}
}

View File

@ -49,11 +49,9 @@ public class BasicLauncher extends Launcher {
Thread d1 = isCaptureErr() ? captureStdErr(p) : drainStdErr(p);
Thread d2 = isCaptureOutput() ? captureStdOut(p) : drainStdOut(p);
if (getInput() != null) {
final BufferedOutputStream input = new BufferedOutputStream(p.getOutputStream());
try {
try (final BufferedOutputStream input = new BufferedOutputStream(p.getOutputStream())) {
input.write(getInput(), 0, getInput().length);
input.flush();
input.close();
} catch (IOException e) {
e.printStackTrace();
throw new IOException("error priming stdin", e);

View File

@ -83,7 +83,9 @@ public class StringTable extends Table<String> implements Cloneable {
if (f == null) {
throw new IllegalArgumentException("null f");
}
return readFromStream(new FileInputStream(f), comment);
try (final FileInputStream in = new FileInputStream(f)) {
return readFromStream(in, comment);
}
}
/**

View File

@ -168,9 +168,9 @@ public class DotUtil {
}
try {
File f = new File(dotfile);
FileWriter fw = new FileWriter(f);
try (FileWriter fw = new FileWriter(f)) {
fw.write(dotStringBuffer.toString());
fw.close();
}
return f;
} catch (Exception e) {