8302685: Some javac unit tests aren't reliably closing open files

Reviewed-by: darcy, vromero
This commit is contained in:
Archie L. Cobbs 2023-02-27 16:21:57 +00:00 committed by Vicente Romero
parent f5a12768fb
commit 55e6bb6b85
58 changed files with 240 additions and 391 deletions

View file

@ -131,16 +131,11 @@ public class T4241573 {
/** Create a jar file containing one or more entries. */ /** Create a jar file containing one or more entries. */
File createJar(File jar, String... entries) throws IOException { File createJar(File jar, String... entries) throws IOException {
OutputStream out = new FileOutputStream(jar); try (JarOutputStream jos = new JarOutputStream(new FileOutputStream(jar))) {
try {
JarOutputStream jos = new JarOutputStream(out);
for (String e: entries) { for (String e: entries) {
jos.putNextEntry(new JarEntry(getPathForZipEntry(e))); jos.putNextEntry(new JarEntry(getPathForZipEntry(e)));
jos.write(getBodyForEntry(e).getBytes()); jos.write(getBodyForEntry(e).getBytes());
} }
jos.close();
} finally {
out.close();
} }
return jar; return jar;
} }

View file

@ -91,10 +91,9 @@ public class T6400872 {
mainAttrs.put(Attributes.Name.MANIFEST_VERSION, "1.0"); mainAttrs.put(Attributes.Name.MANIFEST_VERSION, "1.0");
mainAttrs.put(Attributes.Name.CLASS_PATH, join(classPath, " ")); mainAttrs.put(Attributes.Name.CLASS_PATH, join(classPath, " "));
} }
OutputStream out = new BufferedOutputStream(new FileOutputStream(jar)); try (JarOutputStream j = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(jar)), m)) {
JarOutputStream j = new JarOutputStream(out, m); add(j, base, files);
add(j, base, files); }
j.close();
} }
static void add(JarOutputStream j, File base, File... files) throws IOException { static void add(JarOutputStream j, File base, File... files) throws IOException {
@ -124,15 +123,16 @@ public class T6400872 {
static byte[] read(File f) throws IOException { static byte[] read(File f) throws IOException {
byte[] buf = new byte[(int) f.length()]; byte[] buf = new byte[(int) f.length()];
BufferedInputStream in = new BufferedInputStream(new FileInputStream(f)); try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(f))) {
int offset = 0; int offset = 0;
while (offset < buf.length) { while (offset < buf.length) {
int n = in.read(buf, offset, buf.length - offset); int n = in.read(buf, offset, buf.length - offset);
if (n < 0) if (n < 0)
throw new EOFException(); throw new EOFException();
offset += n; offset += n;
}
return buf;
} }
return buf;
} }
static <T> Iterable<T> iterable(T single) { static <T> Iterable<T> iterable(T single) {

View file

@ -64,13 +64,8 @@ public class T6567415 {
com.sun.tools.javac.jvm.ClassReader.INITIAL_BUFFER_SIZE; com.sun.tools.javac.jvm.ClassReader.INITIAL_BUFFER_SIZE;
static void createClassFile() throws IOException { static void createClassFile() throws IOException {
FileOutputStream fos = null; try (PrintStream ps = new PrintStream(new FileOutputStream(TEST_JAVA))) {
try {
fos = new FileOutputStream(TEST_JAVA);
PrintStream ps = new PrintStream(fos);
ps.println("public class " + TEST_FILE_NAME + " {}"); ps.println("public class " + TEST_FILE_NAME + " {}");
} finally {
fos.close();
} }
String cmds[] = {TEST_JAVA}; String cmds[] = {TEST_JAVA};
com.sun.tools.javac.Main.compile(cmds); com.sun.tools.javac.Main.compile(cmds);
@ -85,43 +80,23 @@ public class T6567415 {
File tfile = new File(f.getAbsolutePath() + ".tmp"); File tfile = new File(f.getAbsolutePath() + ".tmp");
f.renameTo(tfile); f.renameTo(tfile);
RandomAccessFile raf = null; try (
FileChannel wfc = null; FileChannel wfc = new RandomAccessFile(f, "rw").getChannel();
FileChannel rfc = new FileInputStream(tfile).getChannel()) {
FileInputStream fis = null;
FileChannel rfc = null;
try {
raf = new RandomAccessFile(f, "rw");
wfc = raf.getChannel();
fis = new FileInputStream(tfile);
rfc = fis.getChannel();
ByteBuffer bb = MappedByteBuffer.allocate(BAD_FILE_LENGTH); ByteBuffer bb = MappedByteBuffer.allocate(BAD_FILE_LENGTH);
rfc.read(bb); rfc.read(bb);
bb.rewind(); bb.rewind();
wfc.write(bb); wfc.write(bb);
wfc.truncate(BAD_FILE_LENGTH); wfc.truncate(BAD_FILE_LENGTH);
} finally {
wfc.close();
raf.close();
rfc.close();
fis.close();
} }
System.out.println("file length = " + f.length()); System.out.println("file length = " + f.length());
} }
static void createJavaFile() throws IOException { static void createJavaFile() throws IOException {
FileOutputStream fos = null; try (PrintStream ps = new PrintStream(new FileOutputStream(TEST2_JAVA))) {
try {
fos = new FileOutputStream(TEST2_JAVA);
PrintStream ps = new PrintStream(fos);
ps.println("public class " + TEST2_FILE_NAME + ps.println("public class " + TEST2_FILE_NAME +
" {" + TEST_FILE_NAME + " b = new " + " {" + TEST_FILE_NAME + " b = new " +
TEST_FILE_NAME + " ();}"); TEST_FILE_NAME + " ();}");
} finally {
fos.close();
} }
} }

View file

@ -42,6 +42,7 @@ import combo.ComboInstance;
import combo.ComboParameter; import combo.ComboParameter;
import combo.ComboTask; import combo.ComboTask;
import combo.ComboTestHelper; import combo.ComboTestHelper;
import java.io.InputStream;
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.Paths; import java.nio.file.Paths;
import java.util.Iterator; import java.util.Iterator;
@ -110,7 +111,10 @@ public class ConditionalExpressionResolvePending extends ComboInstance<Condition
if (filesIt.hasNext()) { if (filesIt.hasNext()) {
throw new IllegalStateException("More than one classfile returned!"); throw new IllegalStateException("More than one classfile returned!");
} }
byte[] data = file.openInputStream().readAllBytes(); byte[] data;
try (InputStream input = file.openInputStream()) {
data = input.readAllBytes();
}
ClassLoader inMemoryLoader = new ClassLoader() { ClassLoader inMemoryLoader = new ClassLoader() {
protected Class<?> findClass(String name) throws ClassNotFoundException { protected Class<?> findClass(String name) throws ClassNotFoundException {
if ("Test".equals(name)) { if ("Test".equals(name)) {

View file

@ -102,8 +102,7 @@ public class NoStringToLower {
* Verify there are no references to String.toLowerCase() in a class file. * Verify there are no references to String.toLowerCase() in a class file.
*/ */
void scan(JavaFileObject fo) throws IOException { void scan(JavaFileObject fo) throws IOException {
InputStream in = fo.openInputStream(); try (InputStream in = fo.openInputStream()) {
try {
ClassFile cf = ClassFile.read(in); ClassFile cf = ClassFile.read(in);
for (ConstantPool.CPInfo cpinfo: cf.constant_pool.entries()) { for (ConstantPool.CPInfo cpinfo: cf.constant_pool.entries()) {
if (cpinfo.getTag() == ConstantPool.CONSTANT_Methodref) { if (cpinfo.getTag() == ConstantPool.CONSTANT_Methodref) {
@ -119,8 +118,6 @@ public class NoStringToLower {
} }
} }
} catch (ConstantPoolException ignore) { } catch (ConstantPoolException ignore) {
} finally {
in.close();
} }
} }

View file

@ -106,10 +106,9 @@ public class JarFromManifestFailure {
mainAttrs.put(Attributes.Name.MANIFEST_VERSION, "1.0"); mainAttrs.put(Attributes.Name.MANIFEST_VERSION, "1.0");
mainAttrs.put(Attributes.Name.CLASS_PATH, join(classPath, " ")); mainAttrs.put(Attributes.Name.CLASS_PATH, join(classPath, " "));
} }
OutputStream out = new BufferedOutputStream(new FileOutputStream(jar)); try (JarOutputStream j = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(jar)), m)) {
JarOutputStream j = new JarOutputStream(out, m); add(j, base, files);
add(j, base, files); }
j.close();
} }
static void add(JarOutputStream j, File base, File... files) throws IOException { static void add(JarOutputStream j, File base, File... files) throws IOException {
@ -144,15 +143,16 @@ public class JarFromManifestFailure {
static byte[] read(File f) throws IOException { static byte[] read(File f) throws IOException {
byte[] buf = new byte[(int) f.length()]; byte[] buf = new byte[(int) f.length()];
BufferedInputStream in = new BufferedInputStream(new FileInputStream(f)); try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(f))) {
int offset = 0; int offset = 0;
while (offset < buf.length) { while (offset < buf.length) {
int n = in.read(buf, offset, buf.length - offset); int n = in.read(buf, offset, buf.length - offset);
if (n < 0) if (n < 0)
throw new EOFException(); throw new EOFException();
offset += n; offset += n;
}
return buf;
} }
return buf;
} }
static <T> Iterable<T> iterable(T single) { static <T> Iterable<T> iterable(T single) {

View file

@ -63,9 +63,9 @@ public class TestCompileJARInClassPath {
} }
void writeFile(String f, String contents) throws IOException { void writeFile(String f, String contents) throws IOException {
PrintStream s = new PrintStream(new FileOutputStream(f)); try (PrintStream s = new PrintStream(new FileOutputStream(f))) {
s.println(contents); s.println(contents);
s.close(); }
} }
void rm(String filename) throws Exception { void rm(String filename) throws Exception {

View file

@ -84,10 +84,8 @@ public class T6403466 extends AbstractProcessor {
System.err.println("anno: " + anno); System.err.println("anno: " + anno);
System.err.println("elts: " + elts); System.err.println("elts: " + elts);
for (TypeElement te: ElementFilter.typesIn(elts)) { for (TypeElement te: ElementFilter.typesIn(elts)) {
try { try (Writer out = filer.createSourceFile(te.getSimpleName() + "Wrapper").openWriter()) {
Writer out = filer.createSourceFile(te.getSimpleName() + "Wrapper").openWriter();
out.write("class " + te.getSimpleName() + "Wrapper { }"); out.write("class " + te.getSimpleName() + "Wrapper { }");
out.close();
} catch (IOException ex) { } catch (IOException ex) {
ex.printStackTrace(); ex.printStackTrace();
} }

View file

@ -78,13 +78,8 @@ public class T7159016 {
return false; return false;
} }
messager.printNote("writing Generated.java"); messager.printNote("writing Generated.java");
try { try (Writer w = processingEnv.getFiler().createSourceFile("p.Generated").openWriter()) {
Writer w = processingEnv.getFiler().createSourceFile("p.Generated").openWriter(); w.write("package p; public class Generated { public static void m() { } }");
try {
w.write("package p; public class Generated { public static void m() { } }");
} finally {
w.close();
}
} catch (IOException x) { } catch (IOException x) {
messager.printError(x.toString()); messager.printError(x.toString());
} }

View file

@ -32,6 +32,7 @@
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream;
import java.net.URI; import java.net.URI;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.util.ArrayList; import java.util.ArrayList;
@ -178,7 +179,11 @@ public class DetectMutableStaticFields {
int index = className.lastIndexOf('.'); int index = className.lastIndexOf('.');
String pckName = index == -1 ? "" : className.substring(0, index); String pckName = index == -1 ? "" : className.substring(0, index);
if (shouldAnalyzePackage(pckName)) { if (shouldAnalyzePackage(pckName)) {
analyzeClassFile(ClassFile.read(file.openInputStream())); ClassFile classFile;
try (InputStream input = file.openInputStream()) {
classFile = ClassFile.read(input);
}
analyzeClassFile(classFile);
} }
} }
} }

View file

@ -83,9 +83,9 @@ public class T8071847 {
File writeHexFile(String classFileName, String hexString) throws IOException { File writeHexFile(String classFileName, String hexString) throws IOException {
File f = new File(classFileName); File f = new File(classFileName);
FileOutputStream output = new FileOutputStream(f); try (FileOutputStream output = new FileOutputStream(f)) {
output.write(hexToByte(hexString)); output.write(hexToByte(hexString));
output.close(); }
return f; return f;
} }

View file

@ -60,15 +60,17 @@ public class T8152616 {
JavacTool javac = JavacTool.create(); JavacTool javac = JavacTool.create();
StandardJavaFileManager jfm = javac.getStandardFileManager(null,null,null); StandardJavaFileManager jfm = javac.getStandardFileManager(null,null,null);
File file = File.createTempFile("test", ".java"); File file = File.createTempFile("test", ".java");
OutputStream outputStream = new FileOutputStream(file); try (OutputStream outputStream = new FileOutputStream(file)) {
outputStream.write("enum Foo {AA(10), BB, CC { void m() {} }; void m() {};}".getBytes()); outputStream.write("enum Foo {AA(10), BB, CC { void m() {} }; void m() {};}".getBytes());
}
JavacTask task = javac.getTask(null, jfm, null, null, null, JavacTask task = javac.getTask(null, jfm, null, null, null,
jfm.getJavaFileObjects(file.getAbsolutePath())); jfm.getJavaFileObjects(file.getAbsolutePath()));
Iterable<? extends CompilationUnitTree> trees = task.parse(); Iterable<? extends CompilationUnitTree> trees = task.parse();
CompilationUnitTree thisTree = trees.iterator().next(); CompilationUnitTree thisTree = trees.iterator().next();
file.delete(); file.delete();
outputStream = new FileOutputStream(file); try (OutputStream outputStream = new FileOutputStream(file)) {
outputStream.write((obj.PrettyPrint((JCTree)thisTree)).getBytes()); outputStream.write((obj.PrettyPrint((JCTree)thisTree)).getBytes());
}
task = javac.getTask(null, jfm, null, null, null, task = javac.getTask(null, jfm, null, null, null,
jfm.getJavaFileObjects(file.getAbsolutePath())); jfm.getJavaFileObjects(file.getAbsolutePath()));
if(task.parse().toString().contains("ERROR")){ if(task.parse().toString().contains("ERROR")){

View file

@ -58,14 +58,9 @@ public class T6483788 {
File createJar() throws IOException { File createJar() throws IOException {
byte[] dummy_data = new byte[10]; byte[] dummy_data = new byte[10];
File f = new File("a b.jar"); File f = new File("a b.jar");
OutputStream out = new FileOutputStream(f); try (JarOutputStream jar = new JarOutputStream(new FileOutputStream(f))) {
try {
JarOutputStream jar = new JarOutputStream(out);
jar.putNextEntry(new ZipEntry("dummy.class")); jar.putNextEntry(new ZipEntry("dummy.class"));
jar.write(dummy_data); jar.write(dummy_data);
jar.close();
} finally {
out.close();
} }
return f; return f;
} }

View file

@ -114,8 +114,14 @@ public class T6877206 {
} }
try { try {
byte[] uriData = read(urlconn.getInputStream()); byte[] uriData;
byte[] foData = read(fo.openInputStream()); byte[] foData;
try (InputStream input = urlconn.getInputStream()) {
uriData = read(input);
}
try (InputStream input = fo.openInputStream()) {
foData = read(input);
}
if (!Arrays.equals(uriData, foData)) { if (!Arrays.equals(uriData, foData)) {
if (uriData.length != foData.length) if (uriData.length != foData.length)
throw new Exception("data size differs: uri data " throw new Exception("data size differs: uri data "
@ -174,16 +180,11 @@ public class T6877206 {
File createJar(String name, String... entries) throws IOException { File createJar(String name, String... entries) throws IOException {
File jar = new File(name); File jar = new File(name);
OutputStream out = new FileOutputStream(jar); try (JarOutputStream jos = new JarOutputStream(new FileOutputStream(jar))) {
try {
JarOutputStream jos = new JarOutputStream(out);
for (String e: entries) { for (String e: entries) {
jos.putNextEntry(new ZipEntry(e)); jos.putNextEntry(new ZipEntry(e));
jos.write(e.getBytes()); jos.write(e.getBytes());
} }
jos.close();
} finally {
out.close();
} }
return jar; return jar;
} }

View file

@ -36,6 +36,7 @@
import javax.tools.*; import javax.tools.*;
import java.io.File; import java.io.File;
import java.io.Reader;
import java.util.Collections; import java.util.Collections;
public class Test extends ToolTester { public class Test extends ToolTester {
@ -45,10 +46,10 @@ public class Test extends ToolTester {
class DiagnosticTester implements DiagnosticListener<JavaFileObject> { class DiagnosticTester implements DiagnosticListener<JavaFileObject> {
public void report(Diagnostic<? extends JavaFileObject> diagnostic) { public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
if (diagnostic.getKind() == Diagnostic.Kind.NOTE) { if (diagnostic.getKind() == Diagnostic.Kind.NOTE) {
try { // 6427274: FileObject.openReader throws exception
// 6427274: FileObject.openReader throws exception // 6347778: getSource() returns null for notes
// 6347778: getSource() returns null for notes try (Reader reader = diagnostic.getSource().openReader(true)) {
diagnostic.getSource().openReader(true).getClass(); reader.getClass();
} catch (Exception ex) { } catch (Exception ex) {
throw new AssertionError(ex); throw new AssertionError(ex);
} }
@ -66,9 +67,11 @@ public class Test extends ToolTester {
if (!success) if (!success)
throw new AssertionError("Did not see a NOTE"); throw new AssertionError("Did not see a NOTE");
// 6427274: openReader throws exception // 6427274: openReader throws exception
fm.getFileForInput(StandardLocation.PLATFORM_CLASS_PATH, try (Reader reader = fm.getFileForInput(StandardLocation.PLATFORM_CLASS_PATH,
"java.lang", "java.lang",
"Object.class").openReader(true).getClass(); "Object.class").openReader(true)) {
reader.getClass();
}
DiagnosticCollector<JavaFileObject> diags = new DiagnosticCollector<JavaFileObject>(); DiagnosticCollector<JavaFileObject> diags = new DiagnosticCollector<JavaFileObject>();
task = tool.getTask(null, fm, diags, Collections.singleton("-Xlint:all"), task = tool.getTask(null, fm, diags, Collections.singleton("-Xlint:all"),
null, compilationUnits); null, compilationUnits);

View file

@ -23,6 +23,7 @@
import com.sun.tools.classfile.*; import com.sun.tools.classfile.*;
import java.io.InputStream;
import java.nio.file.Paths; import java.nio.file.Paths;
import java.util.HashSet; import java.util.HashSet;
import java.util.List; import java.util.List;
@ -66,7 +67,10 @@ public class LineNumberTestBase extends TestBase {
writeToFileIfEnabled(Paths.get(testCase.getName() + ".java"), testCase.src); writeToFileIfEnabled(Paths.get(testCase.getName() + ".java"), testCase.src);
Set<Integer> coveredLines = new HashSet<>(); Set<Integer> coveredLines = new HashSet<>();
for (JavaFileObject file : compile(testCase.extraCompilerOptions, testCase.src).getClasses().values()) { for (JavaFileObject file : compile(testCase.extraCompilerOptions, testCase.src).getClasses().values()) {
ClassFile classFile = ClassFile.read(file.openInputStream()); ClassFile classFile;
try (InputStream input = file.openInputStream()) {
classFile = ClassFile.read(input);
}
for (Method m : classFile.methods) { for (Method m : classFile.methods) {
Code_attribute code_attribute = (Code_attribute) m.attributes.get(Code); Code_attribute code_attribute = (Code_attribute) m.attributes.get(Code);

View file

@ -25,6 +25,7 @@ import com.sun.tools.classfile.Attribute;
import com.sun.tools.classfile.ClassFile; import com.sun.tools.classfile.ClassFile;
import com.sun.tools.classfile.SourceFile_attribute; import com.sun.tools.classfile.SourceFile_attribute;
import java.io.InputStream;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -84,7 +85,11 @@ public class SourceFileTestBase extends TestBase {
Map<String, ? extends JavaFileObject> classes = compile(sourceCode).getClasses(); Map<String, ? extends JavaFileObject> classes = compile(sourceCode).getClasses();
String fileName = ToolBox.getJavaFileNameFromSource(sourceCode); String fileName = ToolBox.getJavaFileNameFromSource(sourceCode);
for (String className : classesToTest) { for (String className : classesToTest) {
assertAttributePresent(ClassFile.read(classes.get(className).openInputStream()), fileName); ClassFile classFile;
try (InputStream input = classes.get(className).openInputStream()) {
classFile = ClassFile.read(input);
}
assertAttributePresent(classFile, fileName);
} }
} }

View file

@ -199,11 +199,8 @@ public class CheckExamples {
*/ */
String read(File f) throws IOException { String read(File f) throws IOException {
byte[] bytes = new byte[(int) f.length()]; byte[] bytes = new byte[(int) f.length()];
DataInputStream in = new DataInputStream(new FileInputStream(f)); try (DataInputStream in = new DataInputStream(new FileInputStream(f))) {
try {
in.readFully(bytes); in.readFully(bytes);
} finally {
in.close();
} }
return new String(bytes); return new String(bytes);
} }

View file

@ -489,8 +489,7 @@ public class CheckResourceKeys {
* Only strings that look like they might be a resource key are returned. * Only strings that look like they might be a resource key are returned.
*/ */
void scan(JavaFileObject fo, Set<String> results) throws IOException { void scan(JavaFileObject fo, Set<String> results) throws IOException {
InputStream in = fo.openInputStream(); try (InputStream in = fo.openInputStream()) {
try {
ClassFile cf = ClassFile.read(in); ClassFile cf = ClassFile.read(in);
for (ConstantPool.CPInfo cpinfo: cf.constant_pool.entries()) { for (ConstantPool.CPInfo cpinfo: cf.constant_pool.entries()) {
if (cpinfo.getTag() == ConstantPool.CONSTANT_Utf8) { if (cpinfo.getTag() == ConstantPool.CONSTANT_Utf8) {
@ -500,8 +499,6 @@ public class CheckResourceKeys {
} }
} }
} catch (ConstantPoolException ignore) { } catch (ConstantPoolException ignore) {
} finally {
in.close();
} }
} }

View file

@ -429,11 +429,8 @@ class Example implements Comparable<Example> {
*/ */
private String read(File f) throws IOException { private String read(File f) throws IOException {
byte[] bytes = new byte[(int) f.length()]; byte[] bytes = new byte[(int) f.length()];
DataInputStream in = new DataInputStream(new FileInputStream(f)); try (DataInputStream in = new DataInputStream(new FileInputStream(f))) {
try {
in.readFully(bytes); in.readFully(bytes);
} finally {
in.close();
} }
return new String(bytes); return new String(bytes);
} }

View file

@ -380,11 +380,8 @@ public class MessageInfo {
*/ */
String read(File f) throws IOException { String read(File f) throws IOException {
byte[] bytes = new byte[(int) f.length()]; byte[] bytes = new byte[(int) f.length()];
DataInputStream in = new DataInputStream(new FileInputStream(f)); try (DataInputStream in = new DataInputStream(new FileInputStream(f))) {
try {
in.readFully(bytes); in.readFully(bytes);
} finally {
in.close();
} }
return new String(bytes); return new String(bytes);
} }

View file

@ -261,11 +261,8 @@ public class RunExamples {
protected String read(File f) throws IOException { protected String read(File f) throws IOException {
byte[] bytes = new byte[(int) f.length()]; byte[] bytes = new byte[(int) f.length()];
DataInputStream in = new DataInputStream(new FileInputStream(f)); try (DataInputStream in = new DataInputStream(new FileInputStream(f))) {
try {
in.readFully(bytes); in.readFully(bytes);
} finally {
in.close();
} }
return new String(bytes); return new String(bytes);
} }

View file

@ -36,9 +36,9 @@ public class AnnoProc extends AbstractProcessor {
Messager messager = processingEnv.getMessager(); Messager messager = processingEnv.getMessager();
try { try {
JavaFileObject fo = filer.createSourceFile("Gen"); JavaFileObject fo = filer.createSourceFile("Gen");
Writer out = fo.openWriter(); try (Writer out = fo.openWriter()) {
out.write("class Gen { }"); out.write("class Gen { }");
out.close(); }
} catch (IOException e) { } catch (IOException e) {
messager.printError(e.toString()); messager.printError(e.toString());
} }

View file

@ -37,9 +37,9 @@ public class AnnoProc extends AbstractProcessor {
try { try {
FileObject fo1 = filer.createResource( FileObject fo1 = filer.createResource(
StandardLocation.CLASS_OUTPUT, "", "HelloWorld.txt"); StandardLocation.CLASS_OUTPUT, "", "HelloWorld.txt");
Writer out = fo1.openWriter(); try (Writer out = fo1.openWriter()) {
out.write("Hello World!"); out.write("Hello World!");
out.close(); }
FileObject fo2 = filer.createResource( FileObject fo2 = filer.createResource(
StandardLocation.CLASS_OUTPUT, "", "HelloWorld.txt"); StandardLocation.CLASS_OUTPUT, "", "HelloWorld.txt");
} catch (IOException e) { } catch (IOException e) {

View file

@ -37,9 +37,9 @@ public class AnnoProc extends AbstractProcessor {
try { try {
FileObject fo1 = filer.createResource( FileObject fo1 = filer.createResource(
StandardLocation.CLASS_OUTPUT, "p+q", "Hello-World.txt"); StandardLocation.CLASS_OUTPUT, "p+q", "Hello-World.txt");
Writer out = fo1.openWriter(); try (Writer out = fo1.openWriter()) {
out.write("Hello World!"); out.write("Hello World!");
out.close(); }
} catch (IOException e) { } catch (IOException e) {
messager.printError(e.toString()); messager.printError(e.toString());
} }

View file

@ -37,9 +37,9 @@ public class AnnoProc extends AbstractProcessor {
Messager messager = processingEnv.getMessager(); Messager messager = processingEnv.getMessager();
try { try {
JavaFileObject fo = filer.createSourceFile("Gen"); JavaFileObject fo = filer.createSourceFile("Gen");
Writer out = fo.openWriter(); try (Writer out = fo.openWriter()) {
out.write("class Gen { }"); out.write("class Gen { }");
out.close(); }
} catch (IOException e) { } catch (IOException e) {
messager.printError(e.toString()); messager.printError(e.toString());
} }

View file

@ -36,9 +36,9 @@ public class AnnoProc extends AbstractProcessor {
Messager messager = processingEnv.getMessager(); Messager messager = processingEnv.getMessager();
try { try {
JavaFileObject fo = filer.createSourceFile("Gen"); JavaFileObject fo = filer.createSourceFile("Gen");
Writer out = fo.openWriter(); try (Writer out = fo.openWriter()) {
out.write("class Gen { }"); out.write("class Gen { }");
out.close(); }
} catch (IOException e) { } catch (IOException e) {
messager.printError(e.toString()); messager.printError(e.toString());
} }

View file

@ -36,9 +36,9 @@ public class AnnoProc extends AbstractProcessor {
Messager messager = processingEnv.getMessager(); Messager messager = processingEnv.getMessager();
try { try {
JavaFileObject fo = filer.createSourceFile("Gen"); JavaFileObject fo = filer.createSourceFile("Gen");
Writer out = fo.openWriter(); try (Writer out = fo.openWriter()) {
out.write("class Gen { }"); out.write("class Gen { }");
out.close(); }
} catch (IOException e) { } catch (IOException e) {
messager.printError(e.toString()); messager.printError(e.toString());
} }

View file

@ -203,7 +203,7 @@ public class DocCommentTreeApiTester {
t.getElements().getPackageOf(klass).getQualifiedName().toString(), t.getElements().getPackageOf(klass).getQualifiedName().toString(),
fileName + ".out"); fileName + ".out");
String expected = getExpected(htmlFo.openReader(true)); String expected = getExpectedAndClose(htmlFo.openReader(true));
astcheck(fileName, expected, found); astcheck(fileName, expected, found);
} }
} }
@ -239,7 +239,7 @@ public class DocCommentTreeApiTester {
throw new Exception("invalid input: " + jfo); throw new Exception("invalid input: " + jfo);
break; break;
default: default:
expected = getExpected(jfo.openReader(true)); expected = getExpectedAndClose(jfo.openReader(true));
} }
} }
@ -297,7 +297,7 @@ public class DocCommentTreeApiTester {
String found = sw.toString(); String found = sw.toString();
Iterable<? extends JavaFileObject> oos = fm.getJavaFileObjectsFromFiles(otherFiles); Iterable<? extends JavaFileObject> oos = fm.getJavaFileObjectsFromFiles(otherFiles);
JavaFileObject otherFo = oos.iterator().next(); JavaFileObject otherFo = oos.iterator().next();
String expected = getExpected(otherFo.openReader(true)); String expected = getExpectedAndClose(otherFo.openReader(true));
astcheck(pkgFileName, expected, found); astcheck(pkgFileName, expected, found);
} }
@ -323,13 +323,14 @@ public class DocCommentTreeApiTester {
} }
} }
String getExpected(Reader inrdr) throws IOException { String getExpectedAndClose(Reader inrdr) throws IOException {
BufferedReader rdr = new BufferedReader(inrdr);
List<String> lines = new ArrayList<>(); List<String> lines = new ArrayList<>();
String line = rdr.readLine(); try (BufferedReader rdr = new BufferedReader(inrdr)) {
while (line != null) { String line = rdr.readLine();
lines.add(line); while (line != null) {
line = rdr.readLine(); lines.add(line);
line = rdr.readLine();
}
} }
return getExpected(lines); return getExpected(lines);
} }

View file

@ -118,10 +118,8 @@ public class T7068437 {
messager.printError("expected file but file not found"); messager.printError("expected file but file not found");
} }
try { try (Writer w = filer.createSourceFile("p.C").openWriter()) {
Writer w = filer.createSourceFile("p.C").openWriter();
w.write("/* hello! */ package p; class C {}"); w.write("/* hello! */ package p; class C {}");
w.close();
messager.printNote("wrote new content"); messager.printNote("wrote new content");
} catch (IOException x) { } catch (IOException x) {
messager.printError("while writing: " + x); messager.printError("while writing: " + x);

View file

@ -151,11 +151,9 @@ public class T7068451 {
messager.printError("while reading: " + x); messager.printError("while reading: " + x);
} }
try { String body = "package p; public class C { public static void " + m + "() {} }";
String body = "package p; public class C { public static void " + m + "() {} }"; try (Writer w = filer.createSourceFile("p.C").openWriter()) {
Writer w = filer.createSourceFile("p.C").openWriter();
w.write(body); w.write(body);
w.close();
messager.printNote("C.java: wrote new content: " + body); messager.printNote("C.java: wrote new content: " + body);
} catch (IOException x) { } catch (IOException x) {
messager.printError("while writing: " + x); messager.printError("while writing: " + x);

View file

@ -79,19 +79,12 @@ public class T6836682 {
static long computeCRC(File inFile) throws IOException { static long computeCRC(File inFile) throws IOException {
byte[] buffer = new byte[8192]; byte[] buffer = new byte[8192];
CRC32 crc = new CRC32(); CRC32 crc = new CRC32();
FileInputStream fis = null; try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(inFile))) {
BufferedInputStream bis = null;
try {
fis = new FileInputStream(inFile);
bis = new BufferedInputStream(fis);
int n = bis.read(buffer); int n = bis.read(buffer);
while (n > 0) { while (n > 0) {
crc.update(buffer, 0, n); crc.update(buffer, 0, n);
n = bis.read(buffer); n = bis.read(buffer);
} }
} finally {
Utils.close(bis);
Utils.close(fis);
} }
return crc.getValue(); return crc.getValue();
} }
@ -109,14 +102,11 @@ public class T6836682 {
long minlength) throws IOException { long minlength) throws IOException {
Utils.createClassFile(javaFile, null, true); Utils.createClassFile(javaFile, null, true);
File classFile = new File(Utils.getClassFileName(javaFile)); File classFile = new File(Utils.getClassFileName(javaFile));
ZipOutputStream zos = null; try (
BufferedOutputStream bos = null; ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(jarFile));
FileInputStream fis = null; BufferedOutputStream bos = new BufferedOutputStream(zos)) {
try {
zos = new ZipOutputStream(new FileOutputStream(jarFile));
zos.setLevel(ZipOutputStream.STORED); zos.setLevel(ZipOutputStream.STORED);
zos.setMethod(0); zos.setMethod(0);
bos = new BufferedOutputStream(zos);
ZipEntry ze = new ZipEntry("large.data"); ZipEntry ze = new ZipEntry("large.data");
ze.setCompressedSize(getCount(minlength) * BUFFER_LEN); ze.setCompressedSize(getCount(minlength) * BUFFER_LEN);
@ -132,14 +122,11 @@ public class T6836682 {
ze.setCrc(computeCRC(classFile)); ze.setCrc(computeCRC(classFile));
ze.setMethod(ZipEntry.STORED); ze.setMethod(ZipEntry.STORED);
zos.putNextEntry(ze); zos.putNextEntry(ze);
fis = new FileInputStream(classFile); try (FileInputStream fis = new FileInputStream(classFile)) {
Utils.copyStream(fis, bos); Utils.copyStream(fis, bos);
}
bos.flush(); bos.flush();
zos.closeEntry(); zos.closeEntry();
} finally {
Utils.close(bos);
Utils.close(zos);
Utils.close(fis);
} }
// deleted to prevent accidental linkage // deleted to prevent accidental linkage
new File(Utils.getClassFileName(javaFile)).delete(); new File(Utils.getClassFileName(javaFile)).delete();
@ -148,12 +135,9 @@ public class T6836682 {
static void createLargeJar(File jarFile, File javaFile) throws IOException { static void createLargeJar(File jarFile, File javaFile) throws IOException {
File classFile = new File(Utils.getClassFileName(javaFile)); File classFile = new File(Utils.getClassFileName(javaFile));
Utils.createClassFile(javaFile, null, true); Utils.createClassFile(javaFile, null, true);
ZipOutputStream zos = null;
FileInputStream fis = null;
final int MAX = Short.MAX_VALUE * 2 + 10; final int MAX = Short.MAX_VALUE * 2 + 10;
ZipEntry ze = null; ZipEntry ze = null;
try { try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(jarFile))) {
zos = new ZipOutputStream(new FileOutputStream(jarFile));
zos.setLevel(ZipOutputStream.STORED); zos.setLevel(ZipOutputStream.STORED);
zos.setMethod(ZipOutputStream.STORED); zos.setMethod(ZipOutputStream.STORED);
for (int i = 0; i < MAX ; i++) { for (int i = 0; i < MAX ; i++) {
@ -170,14 +154,13 @@ public class T6836682 {
ze.setSize(classFile.length()); ze.setSize(classFile.length());
ze.setCrc(computeCRC(classFile)); ze.setCrc(computeCRC(classFile));
zos.putNextEntry(ze); zos.putNextEntry(ze);
fis = new FileInputStream(classFile); try (FileInputStream fis = new FileInputStream(classFile)) {
Utils.copyStream(fis, zos); Utils.copyStream(fis, zos);
}
} finally { } finally {
Utils.close(zos); // deleted to prevent accidental linkage
Utils.close(fis); new File(Utils.getClassFileName(javaFile)).delete();
// deleted to prevent accidental linkage }
new File(Utils.getClassFileName(javaFile)).delete();
}
} }
// a jar with entries exceeding 64k + a class file for the existential test // a jar with entries exceeding 64k + a class file for the existential test

View file

@ -66,18 +66,13 @@ public class Utils {
} }
public static void createJavaFile(File outFile, File superClass) throws IOException { public static void createJavaFile(File outFile, File superClass) throws IOException {
PrintStream ps = null;
String srcStr = "public class " + getSimpleName(outFile) + " "; String srcStr = "public class " + getSimpleName(outFile) + " ";
if (superClass != null) { if (superClass != null) {
srcStr = srcStr.concat("extends " + getSimpleName(superClass) + " "); srcStr = srcStr.concat("extends " + getSimpleName(superClass) + " ");
} }
srcStr = srcStr.concat("{}"); srcStr = srcStr.concat("{}");
try { try (PrintStream ps = new PrintStream(new FileOutputStream(outFile))) {
FileOutputStream fos = new FileOutputStream(outFile);
ps = new PrintStream(fos);
ps.println(srcStr); ps.println(srcStr);
} finally {
close(ps);
} }
} }
@ -116,22 +111,12 @@ public class Utils {
} }
public static void cat(File output, File... files) throws IOException { public static void cat(File output, File... files) throws IOException {
BufferedInputStream bis = null; try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(output))) {
BufferedOutputStream bos = null; for (File file : files) {
FileOutputStream fos = null; try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))) {
try { copyStream(bis, bos);
fos = new FileOutputStream(output); }
bos = new BufferedOutputStream(fos);
for (File x : files) {
FileInputStream fis = new FileInputStream(x);
bis = new BufferedInputStream(fis);
copyStream(bis, bos);
Utils.close(bis);
} }
} finally {
Utils.close(bis);
Utils.close(bos);
Utils.close(fos);
} }
} }
} }

View file

@ -62,6 +62,7 @@ import com.sun.tools.javac.tree.JCTree.Tag;
import com.sun.tools.javac.tree.TreeScanner; import com.sun.tools.javac.tree.TreeScanner;
import com.sun.tools.javac.util.Context; import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.JCDiagnostic; import com.sun.tools.javac.util.JCDiagnostic;
import java.io.InputStream;
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.Paths; import java.nio.file.Paths;
import java.util.ArrayList; import java.util.ArrayList;
@ -135,7 +136,10 @@ public class DeduplicationTest {
// lambdas. // lambdas.
Set<String> bootstrapMethodNames = new TreeSet<>(); Set<String> bootstrapMethodNames = new TreeSet<>();
for (JavaFileObject output : generated) { for (JavaFileObject output : generated) {
ClassFile cf = ClassFile.read(output.openInputStream()); ClassFile cf;
try (InputStream input = output.openInputStream()) {
cf = ClassFile.read(input);
}
if (cf.getName().equals("com/sun/tools/javac/comp/Deduplication$R")) { if (cf.getName().equals("com/sun/tools/javac/comp/Deduplication$R")) {
continue; continue;
} }

View file

@ -75,24 +75,18 @@ class DirectedClassLoader extends ClassLoader {
} }
private Class<?> defineFrom(String name, File file) { private Class<?> defineFrom(String name, File file) {
FileInputStream fis = null; try (FileInputStream fis = new FileInputStream(file)) {
try { byte[] bytes = new byte[fis.available()];
try { int read = fis.read(bytes);
fis = new FileInputStream(file); if (read != bytes.length) {
byte[] bytes = new byte[fis.available()]; return null;
int read = fis.read(bytes);
if (read != bytes.length) {
return null;
}
if (preprocessors != null) {
for (ClassFilePreprocessor cfp : preprocessors) {
bytes = cfp.preprocess(name, bytes);
}
}
return defineClass(name, bytes, 0, bytes.length);
} finally {
fis.close();
} }
if (preprocessors != null) {
for (ClassFilePreprocessor cfp : preprocessors) {
bytes = cfp.preprocess(name, bytes);
}
}
return defineClass(name, bytes, 0, bytes.length);
} catch (IOException e) {} } catch (IOException e) {}
return null; return null;
} }

View file

@ -94,11 +94,8 @@ public class T7022337 extends JavacTestingAbstractProcessor {
void generate(String name) { void generate(String name) {
try { try {
JavaFileObject fo = filer.createSourceFile(name); JavaFileObject fo = filer.createSourceFile(name);
Writer out = fo.openWriter(); try (Writer out = fo.openWriter()) {
try {
out.write("class " + name + " { }"); out.write("class " + name + " { }");
} finally {
out.close();
} }
} catch (IOException e) { } catch (IOException e) {
throw new Error(e); throw new Error(e);

View file

@ -90,12 +90,9 @@ public class ExtraSemiTest {
String readFile(File f) throws IOException { String readFile(File f) throws IOException {
int len = (int) f.length(); int len = (int) f.length();
byte[] data = new byte[len]; byte[] data = new byte[len];
DataInputStream in = new DataInputStream(new FileInputStream(f)); try (DataInputStream in = new DataInputStream(new FileInputStream(f))) {
try {
in.readFully(data); in.readFully(data);
return new String(data); return new String(data);
} finally {
in.close();
} }
} }
} }

View file

@ -39,6 +39,7 @@
*/ */
import java.io.IOException; import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.Paths; import java.nio.file.Paths;
@ -404,7 +405,9 @@ public class PreviewErrors extends ComboInstance<PreviewErrors> {
if (testClass == null) { if (testClass == null) {
throw new IllegalStateException("Cannot find Test.class"); throw new IllegalStateException("Cannot find Test.class");
} }
cf = ClassFile.read(testClass.openInputStream()); try (InputStream input = testClass.openInputStream()) {
cf = ClassFile.read(input);
}
} catch (IOException | ConstantPoolException ex) { } catch (IOException | ConstantPoolException ex) {
throw new IllegalStateException(ex); throw new IllegalStateException(ex);
} }

View file

@ -46,8 +46,7 @@ public class HelloWorldAP extends AbstractProcessor {
boolean ret = true; boolean ret = true;
if(!renv.processingOver() && !DONE) { if(!renv.processingOver() && !DONE) {
msgr.printNote("running process to create HelloWorld."); msgr.printNote("running process to create HelloWorld.");
try { try (Writer pw = filer.createSourceFile("HelloWorld").openWriter()) {
Writer pw = filer.createSourceFile("HelloWorld").openWriter();
pw.write("public class HelloWorld {\n"); pw.write("public class HelloWorld {\n");
pw.write(" public static void main (String argv[]) {\n"); pw.write(" public static void main (String argv[]) {\n");
pw.write(" System.out.println(\"Hello apt world.\");\n"); pw.write(" System.out.println(\"Hello apt world.\");\n");
@ -56,13 +55,11 @@ public class HelloWorldAP extends AbstractProcessor {
pw.flush(); pw.flush();
pw.close(); pw.close();
OutputStream os = filer.createClassFile("HelloWorldAP").openOutputStream();
// the easiest way to create a class file is to copy another one // the easiest way to create a class file is to copy another one
InputStream is = getClass().getResourceAsStream("HelloWorldAP.class"); try (OutputStream os = filer.createClassFile("HelloWorldAP").openOutputStream();
copy(is, os); InputStream is = getClass().getResourceAsStream("HelloWorldAP.class")) {
is.close(); copy(is, os);
os.flush(); }
os.close();
DONE=true; DONE=true;
} }
catch (IOException ioe) { catch (IOException ioe) {

View file

@ -53,11 +53,11 @@ public class T6413690 extends JavacTestingAbstractProcessor {
Set<? extends Element> supers = roundEnvironment.getElementsAnnotatedWith(testMe); Set<? extends Element> supers = roundEnvironment.getElementsAnnotatedWith(testMe);
try { try {
for (Element sup : supers) { for (Element sup : supers) {
Writer sub = filer.createSourceFile(sup.getSimpleName() + "_GENERATED").openWriter(); try (Writer sub = filer.createSourceFile(sup.getSimpleName() + "_GENERATED").openWriter()) {
sub.write(String.format("class %s_GENERATED extends %s {}", sub.write(String.format("class %s_GENERATED extends %s {}",
sup.getSimpleName(), sup.getSimpleName(),
((TypeElement)sup).getQualifiedName())); ((TypeElement)sup).getQualifiedName()));
sub.close(); }
} }
} catch (IOException ex) { } catch (IOException ex) {
throw new RuntimeException(ex); throw new RuntimeException(ex);

View file

@ -78,39 +78,18 @@ public class ClassProcessor extends JavacTestingAbstractProcessor {
pkgInfo = new File(System.getProperty("test.classes"), "foo/package-info.class"); pkgInfo = new File(System.getProperty("test.classes"), "foo/package-info.class");
byte[] bytes = new byte[(int) pkgInfo.length()]; byte[] bytes = new byte[(int) pkgInfo.length()];
DataInputStream in = null; try (DataInputStream in = new DataInputStream(new FileInputStream(pkgInfo))) {
try {
in = new DataInputStream(new FileInputStream(pkgInfo));
in.readFully(bytes); in.readFully(bytes);
} catch (IOException ioe) { } catch (IOException ioe) {
error("Couldn't read package info file: " + ioe); error("Couldn't read package info file: " + ioe);
} finally {
if(in != null) {
try {
in.close();
} catch (IOException e) {
error("InputStream closing failed: " + e);
}
}
} }
OutputStream out = null; try (OutputStream out = kind.equals("java") ?
try { filer.createSourceFile("foo.package-info").openOutputStream() :
if (kind.equals("java")) filer.createClassFile("foo.package-info").openOutputStream()) {
out = filer.createSourceFile("foo.package-info").openOutputStream();
else
out = filer.createClassFile("foo.package-info").openOutputStream();
out.write(bytes, 0, bytes.length); out.write(bytes, 0, bytes.length);
} catch (IOException ioe) { } catch (IOException ioe) {
error("Couldn't create package info file: " + ioe); error("Couldn't create package info file: " + ioe);
} finally {
if(out != null) {
try {
out.close();
} catch (IOException e) {
error("OutputStream closing failed: " + e);
}
}
} }
} }

View file

@ -55,22 +55,16 @@ public class T6634138 extends JavacTestingAbstractProcessor {
if (roundEnvironment.processingOver()) { if (roundEnvironment.processingOver()) {
System.out.println("Writing out source files."); System.out.println("Writing out source files.");
try { try {
PrintWriter pw = new PrintWriter(filer.createSourceFile("foo.WrittenAfterProcessing").openWriter()); try (PrintWriter pw = new PrintWriter(filer.createSourceFile("foo.WrittenAfterProcessing").openWriter())) {
try {
pw.println("package foo;"); pw.println("package foo;");
pw.println("public class WrittenAfterProcessing {"); pw.println("public class WrittenAfterProcessing {");
pw.println(" public WrittenAfterProcessing() {super();}"); pw.println(" public WrittenAfterProcessing() {super();}");
pw.println("}"); pw.println("}");
} finally {
pw.close();
} }
pw = new PrintWriter(filer.createSourceFile("foo.package-info").openWriter()); try (PrintWriter pw = new PrintWriter(filer.createSourceFile("foo.package-info").openWriter())) {
try {
pw.println("@Deprecated"); pw.println("@Deprecated");
pw.println("package foo;"); pw.println("package foo;");
} finally {
pw.close();
} }
} catch(IOException io) { } catch(IOException io) {
throw new RuntimeException(io); throw new RuntimeException(io);

View file

@ -84,10 +84,8 @@ public class T6439826 extends AbstractProcessor {
private void writeBadFile() { private void writeBadFile() {
Filer filer = processingEnv.getFiler(); Filer filer = processingEnv.getFiler();
Messager messager = processingEnv.getMessager(); Messager messager = processingEnv.getMessager();
try { try (Writer out = filer.createSourceFile("Foo").openWriter()) {
Writer out = filer.createSourceFile("Foo").openWriter();
out.write("class Foo #"); // write a file that generates a scanner error out.write("class Foo #"); // write a file that generates a scanner error
out.close();
} catch (IOException e) { } catch (IOException e) {
messager.printError(e.toString()); messager.printError(e.toString());
} }

View file

@ -406,40 +406,20 @@ public class T6920317 {
/** Read a file. */ /** Read a file. */
byte[] read(File file) { byte[] read(File file) {
byte[] bytes = new byte[(int) file.length()]; byte[] bytes = new byte[(int) file.length()];
DataInputStream in = null; try (DataInputStream in = new DataInputStream(new FileInputStream(file))) {
try {
in = new DataInputStream(new FileInputStream(file));
in.readFully(bytes); in.readFully(bytes);
} catch (IOException e) { } catch (IOException e) {
error("Error reading file: " + e); error("Error reading file: " + e);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
error("Error closing file: " + e);
}
}
} }
return bytes; return bytes;
} }
/** Write a file. */ /** Write a file. */
void write(JavaFileObject file, byte[] bytes) { void write(JavaFileObject file, byte[] bytes) {
OutputStream out = null; try (OutputStream out = file.openOutputStream()) {
try {
out = file.openOutputStream();
out.write(bytes, 0, bytes.length); out.write(bytes, 0, bytes.length);
} catch (IOException e) { } catch (IOException e) {
error("Error writing file: " + e); error("Error writing file: " + e);
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
error("Error closing file: " + e);
}
}
} }
} }

View file

@ -322,14 +322,11 @@ public class TestWarnErrorCount extends JavacTestingAbstractProcessor {
void generate(String name, boolean error, boolean warn) { void generate(String name, boolean error, boolean warn) {
try { try {
JavaFileObject fo = filer.createSourceFile(name); JavaFileObject fo = filer.createSourceFile(name);
Writer out = fo.openWriter(); try (Writer out = fo.openWriter()) {
try {
out.write("class " + name + " {\n" out.write("class " + name + " {\n"
+ (warn ? " void m() throws Exception { try (AutoCloseable ac = null) { } }" : "") + (warn ? " void m() throws Exception { try (AutoCloseable ac = null) { } }" : "")
+ (error ? " ERROR\n" : "") + (error ? " ERROR\n" : "")
+ "}\n"); + "}\n");
} finally {
out.close();
} }
} catch (IOException e) { } catch (IOException e) {
throw new Error(e); throw new Error(e);

View file

@ -232,9 +232,9 @@ public class TestSuppression {
private void writeSource(String name, String text) { private void writeSource(String name, String text) {
try { try {
JavaFileObject fo = f.createSourceFile(name); JavaFileObject fo = f.createSourceFile(name);
Writer out = fo.openWriter(); try (Writer out = fo.openWriter()) {
out.write(text); out.write(text);
out.close(); }
} catch (IOException e) { } catch (IOException e) {
m.printError(e.toString()); m.printError(e.toString());
} }

View file

@ -65,10 +65,10 @@ public class TestGetResource extends JavacTestingAbstractProcessor {
String phase = options.get("phase"); String phase = options.get("phase");
if (phase.equals("write")) { if (phase.equals("write")) {
PrintWriter pw = try (PrintWriter pw =
new PrintWriter(filer.createResource(CLASS_OUTPUT, PKG, RESOURCE_NAME).openWriter()); new PrintWriter(filer.createResource(CLASS_OUTPUT, PKG, RESOURCE_NAME).openWriter())) {
pw.print(CONTENTS); pw.print(CONTENTS);
pw.close(); }
} else if (phase.equals("read")) { } else if (phase.equals("read")) {
String contents = filer.getResource(CLASS_OUTPUT, String contents = filer.getResource(CLASS_OUTPUT,
PKG, PKG,

View file

@ -46,9 +46,9 @@ public class TestLastRound extends JavacTestingAbstractProcessor {
if (roundEnv.processingOver()) { if (roundEnv.processingOver()) {
try { try {
JavaFileObject fo = filer.createSourceFile("LastRound.java"); JavaFileObject fo = filer.createSourceFile("LastRound.java");
Writer out = fo.openWriter(); try (Writer out = fo.openWriter()) {
out.write("class LastRound { }"); out.write("class LastRound { }");
out.close(); }
} catch (IOException e) { } catch (IOException e) {
} }
} }

View file

@ -61,8 +61,7 @@ public class Generator extends JavacTestingAbstractProcessor {
void createFile(TypeElement e) { void createFile(TypeElement e) {
try { try {
JavaFileObject fo = filer.createSourceFile(e.getSimpleName()); JavaFileObject fo = filer.createSourceFile(e.getSimpleName());
Writer out = fo.openWriter(); try (Writer out = fo.openWriter()) {
try {
switch (e.getKind()) { switch (e.getKind()) {
case CLASS: case CLASS:
out.write("import java.util.*;\n"); out.write("import java.util.*;\n");
@ -83,8 +82,6 @@ public class Generator extends JavacTestingAbstractProcessor {
out.write("}\n"); out.write("}\n");
break; break;
} }
} finally {
out.close();
} }
} catch (IOException ex) { } catch (IOException ex) {
messager.printError("problem writing file: " + ex); messager.printError("problem writing file: " + ex);

View file

@ -76,11 +76,9 @@ public class TestNames extends JavacTestingAbstractProcessor {
failed = true; failed = true;
try { // Force another round with a new context
// Force another round with a new context try (PrintWriter pw = new PrintWriter(filer.createSourceFile("Foo").openWriter())) {
PrintWriter pw = new PrintWriter(filer.createSourceFile("Foo").openWriter());
pw.println("public class Foo {}"); pw.println("public class Foo {}");
pw.close();
} catch (IOException ioe) { } catch (IOException ioe) {
throw new RuntimeException(); throw new RuntimeException();
} }

View file

@ -65,39 +65,34 @@ public class TestGetConstantExpression extends JavacTestingAbstractProcessor {
// Generate source code with various constant values and // Generate source code with various constant values and
// make sure it compiles. // make sure it compiles.
try { try (PrintWriter pw = new PrintWriter(filer.createSourceFile("ConstantTest").openWriter())) {
PrintWriter pw = new PrintWriter(filer.createSourceFile("ConstantTest").openWriter()); Boolean[] booleans = {true, false};
try { Byte[] bytes = {Byte.MIN_VALUE, -1, 0, 1, Byte.MAX_VALUE};
Boolean[] booleans = {true, false}; Short[] shorts = {Short.MIN_VALUE, -1, 0, 1, Short.MAX_VALUE};
Byte[] bytes = {Byte.MIN_VALUE, -1, 0, 1, Byte.MAX_VALUE}; Integer[] ints = {Integer.MIN_VALUE, -1, 0, 1, Integer.MAX_VALUE};
Short[] shorts = {Short.MIN_VALUE, -1, 0, 1, Short.MAX_VALUE}; Long[] longs = {Long.MIN_VALUE, -1L, 0L,1L, Long.MAX_VALUE};
Integer[] ints = {Integer.MIN_VALUE, -1, 0, 1, Integer.MAX_VALUE}; Character[] chars = {Character.MIN_VALUE, ' ', '\t', 'a', 'b', 'c', '~', Character.MAX_VALUE};
Long[] longs = {Long.MIN_VALUE, -1L, 0L,1L, Long.MAX_VALUE}; Float[] floats = {Float.NaN, Float.NEGATIVE_INFINITY, -1.0f, -0.0f, 0.0f, 1.0f, Float.POSITIVE_INFINITY};
Character[] chars = {Character.MIN_VALUE, ' ', '\t', 'a', 'b', 'c', '~', Character.MAX_VALUE}; Double[] doubles = {Double.NaN, Double.NEGATIVE_INFINITY, -1.0, -0.0, 0.0, 1.0, Double.POSITIVE_INFINITY};
Float[] floats = {Float.NaN, Float.NEGATIVE_INFINITY, -1.0f, -0.0f, 0.0f, 1.0f, Float.POSITIVE_INFINITY};
Double[] doubles = {Double.NaN, Double.NEGATIVE_INFINITY, -1.0, -0.0, 0.0, 1.0, Double.POSITIVE_INFINITY};
pw.println("class ConstantTest {"); pw.println("class ConstantTest {");
pw.println(String.format(" private static boolean[] booleans = {%s};", pw.println(String.format(" private static boolean[] booleans = {%s};",
printConstants(booleans))); printConstants(booleans)));
pw.println(String.format(" private static byte[] bytes = {%s};", pw.println(String.format(" private static byte[] bytes = {%s};",
printConstants(bytes))); printConstants(bytes)));
pw.println(String.format(" private static short[] shorts = {%s};", pw.println(String.format(" private static short[] shorts = {%s};",
printConstants(shorts))); printConstants(shorts)));
pw.println(String.format(" private static int[] ints = {%s};", pw.println(String.format(" private static int[] ints = {%s};",
printConstants(ints))); printConstants(ints)));
pw.println(String.format(" private static long[] longs = {%s};", pw.println(String.format(" private static long[] longs = {%s};",
printConstants(longs))); printConstants(longs)));
pw.println(String.format(" private static char[] chars = {%s};", pw.println(String.format(" private static char[] chars = {%s};",
printConstants(chars))); printConstants(chars)));
pw.println(String.format(" private static float[] floats = {%s};", pw.println(String.format(" private static float[] floats = {%s};",
printConstants(floats))); printConstants(floats)));
pw.println(String.format(" private static double[] doubles = {%s};", pw.println(String.format(" private static double[] doubles = {%s};",
printConstants(doubles))); printConstants(doubles)));
pw.println("}"); pw.println("}");
} finally {
pw.close();
}
} catch(IOException io) { } catch(IOException io) {
throw new RuntimeException(io); throw new RuntimeException(io);
} }

View file

@ -189,11 +189,8 @@ public class TestDocComments extends JavacTestingAbstractProcessor {
try { try {
JavaFileObject fo = filer.createSourceFile(curr); JavaFileObject fo = filer.createSourceFile(curr);
Writer out = fo.openWriter(); try (Writer out = fo.openWriter()) {
try {
out.write(text.toString()); out.write(text.toString());
} finally {
out.close();
} }
} catch (IOException e) { } catch (IOException e) {
throw new Error(e); throw new Error(e);

View file

@ -57,15 +57,8 @@ public class Test extends JavacTestingAbstractProcessor {
void generateSource(String name) { void generateSource(String name) {
String text = "class " + name + " { }\n"; String text = "class " + name + " { }\n";
try (Writer out = filer.createSourceFile(name).openWriter()) {
// avoid try-with-resources so test can be run on older builds out.write(text);
try {
Writer out = filer.createSourceFile(name).openWriter();
try {
out.write(text);
} finally {
out.close();
}
} catch (IOException e) { } catch (IOException e) {
throw new Error(e); throw new Error(e);
} }

View file

@ -91,7 +91,6 @@ public class BaseClassesNotReRead extends AbstractProcessor {
Filer filer = processingEnv.getFiler(); Filer filer = processingEnv.getFiler();
try (Writer out = filer.createSourceFile(name).openWriter()) { try (Writer out = filer.createSourceFile(name).openWriter()) {
out.write(code); out.write(code);
out.close();
} catch (IOException e) { } catch (IOException e) {
processingEnv.getMessager().printError(e.toString()); processingEnv.getMessager().printError(e.toString());
} }

View file

@ -47,9 +47,9 @@ public class WErrorGen extends JavacTestingAbstractProcessor {
if (++round == 1) { if (++round == 1) {
try { try {
JavaFileObject fo = filer.createSourceFile("Gen"); JavaFileObject fo = filer.createSourceFile("Gen");
Writer out = fo.openWriter(); try (Writer out = fo.openWriter()) {
out.write("import java.util.*; class Gen { List l; }"); out.write("import java.util.*; class Gen { List l; }");
out.close(); }
} catch (IOException e) { } catch (IOException e) {
} }
} }

View file

@ -45,9 +45,9 @@ public class ValidateJarWithSealedAndRecord {
} }
void writeFile(String f, String contents) throws IOException { void writeFile(String f, String contents) throws IOException {
PrintStream s = new PrintStream(new FileOutputStream(f)); try (PrintStream s = new PrintStream(new FileOutputStream(f))) {
s.println(contents); s.println(contents);
s.close(); }
} }
private static final ToolProvider JAR_TOOL = ToolProvider.findFirst("jar").orElseThrow(() -> new RuntimeException("jar tool not found")); private static final ToolProvider JAR_TOOL = ToolProvider.findFirst("jar").orElseThrow(() -> new RuntimeException("jar tool not found"));

View file

@ -42,6 +42,7 @@ import combo.ComboInstance;
import combo.ComboParameter; import combo.ComboParameter;
import combo.ComboTask; import combo.ComboTask;
import combo.ComboTestHelper; import combo.ComboTestHelper;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.Paths; import java.nio.file.Paths;
@ -111,7 +112,10 @@ public class SwitchExpressionNoValue extends ComboInstance<SwitchExpressionNoVal
if (filesIt.hasNext()) { if (filesIt.hasNext()) {
throw new IllegalStateException("More than one classfile returned!"); throw new IllegalStateException("More than one classfile returned!");
} }
byte[] data = file.openInputStream().readAllBytes(); byte[] data;
try (InputStream input = file.openInputStream()) {
data = input.readAllBytes();
}
ClassLoader inMemoryLoader = new ClassLoader() { ClassLoader inMemoryLoader = new ClassLoader() {
protected Class<?> findClass(String name) throws ClassNotFoundException { protected Class<?> findClass(String name) throws ClassNotFoundException {
if ("Test".equals(name)) { if ("Test".equals(name)) {

View file

@ -120,11 +120,8 @@ public class TreePosRoundsTest extends AbstractProcessor {
try { try {
JavaFileObject fo = filer.createSourceFile(name); JavaFileObject fo = filer.createSourceFile(name);
Writer out = fo.openWriter(); try (Writer out = fo.openWriter()) {
try {
out.write(text.toString()); out.write(text.toString());
} finally {
out.close();
} }
} catch (IOException e) { } catch (IOException e) {
throw new Error(e); throw new Error(e);