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. */
File createJar(File jar, String... entries) throws IOException {
OutputStream out = new FileOutputStream(jar);
try {
JarOutputStream jos = new JarOutputStream(out);
try (JarOutputStream jos = new JarOutputStream(new FileOutputStream(jar))) {
for (String e: entries) {
jos.putNextEntry(new JarEntry(getPathForZipEntry(e)));
jos.write(getBodyForEntry(e).getBytes());
}
jos.close();
} finally {
out.close();
}
return jar;
}

View File

@ -91,10 +91,9 @@ public class T6400872 {
mainAttrs.put(Attributes.Name.MANIFEST_VERSION, "1.0");
mainAttrs.put(Attributes.Name.CLASS_PATH, join(classPath, " "));
}
OutputStream out = new BufferedOutputStream(new FileOutputStream(jar));
JarOutputStream j = new JarOutputStream(out, m);
add(j, base, files);
j.close();
try (JarOutputStream j = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(jar)), m)) {
add(j, base, files);
}
}
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 {
byte[] buf = new byte[(int) f.length()];
BufferedInputStream in = new BufferedInputStream(new FileInputStream(f));
int offset = 0;
while (offset < buf.length) {
int n = in.read(buf, offset, buf.length - offset);
if (n < 0)
throw new EOFException();
offset += n;
try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(f))) {
int offset = 0;
while (offset < buf.length) {
int n = in.read(buf, offset, buf.length - offset);
if (n < 0)
throw new EOFException();
offset += n;
}
return buf;
}
return buf;
}
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;
static void createClassFile() throws IOException {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(TEST_JAVA);
PrintStream ps = new PrintStream(fos);
try (PrintStream ps = new PrintStream(new FileOutputStream(TEST_JAVA))) {
ps.println("public class " + TEST_FILE_NAME + " {}");
} finally {
fos.close();
}
String cmds[] = {TEST_JAVA};
com.sun.tools.javac.Main.compile(cmds);
@ -85,43 +80,23 @@ public class T6567415 {
File tfile = new File(f.getAbsolutePath() + ".tmp");
f.renameTo(tfile);
RandomAccessFile raf = null;
FileChannel wfc = null;
FileInputStream fis = null;
FileChannel rfc = null;
try {
raf = new RandomAccessFile(f, "rw");
wfc = raf.getChannel();
fis = new FileInputStream(tfile);
rfc = fis.getChannel();
try (
FileChannel wfc = new RandomAccessFile(f, "rw").getChannel();
FileChannel rfc = new FileInputStream(tfile).getChannel()) {
ByteBuffer bb = MappedByteBuffer.allocate(BAD_FILE_LENGTH);
rfc.read(bb);
bb.rewind();
wfc.write(bb);
wfc.truncate(BAD_FILE_LENGTH);
} finally {
wfc.close();
raf.close();
rfc.close();
fis.close();
}
System.out.println("file length = " + f.length());
}
static void createJavaFile() throws IOException {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(TEST2_JAVA);
PrintStream ps = new PrintStream(fos);
try (PrintStream ps = new PrintStream(new FileOutputStream(TEST2_JAVA))) {
ps.println("public class " + TEST2_FILE_NAME +
" {" + TEST_FILE_NAME + " b = new " +
TEST_FILE_NAME + " ();}");
} finally {
fos.close();
}
}

View File

@ -42,6 +42,7 @@ import combo.ComboInstance;
import combo.ComboParameter;
import combo.ComboTask;
import combo.ComboTestHelper;
import java.io.InputStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Iterator;
@ -110,7 +111,10 @@ public class ConditionalExpressionResolvePending extends ComboInstance<Condition
if (filesIt.hasNext()) {
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() {
protected Class<?> findClass(String name) throws ClassNotFoundException {
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.
*/
void scan(JavaFileObject fo) throws IOException {
InputStream in = fo.openInputStream();
try {
try (InputStream in = fo.openInputStream()) {
ClassFile cf = ClassFile.read(in);
for (ConstantPool.CPInfo cpinfo: cf.constant_pool.entries()) {
if (cpinfo.getTag() == ConstantPool.CONSTANT_Methodref) {
@ -119,8 +118,6 @@ public class NoStringToLower {
}
}
} 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.CLASS_PATH, join(classPath, " "));
}
OutputStream out = new BufferedOutputStream(new FileOutputStream(jar));
JarOutputStream j = new JarOutputStream(out, m);
add(j, base, files);
j.close();
try (JarOutputStream j = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(jar)), m)) {
add(j, base, files);
}
}
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 {
byte[] buf = new byte[(int) f.length()];
BufferedInputStream in = new BufferedInputStream(new FileInputStream(f));
int offset = 0;
while (offset < buf.length) {
int n = in.read(buf, offset, buf.length - offset);
if (n < 0)
throw new EOFException();
offset += n;
try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(f))) {
int offset = 0;
while (offset < buf.length) {
int n = in.read(buf, offset, buf.length - offset);
if (n < 0)
throw new EOFException();
offset += n;
}
return buf;
}
return buf;
}
static <T> Iterable<T> iterable(T single) {

View File

@ -63,9 +63,9 @@ public class TestCompileJARInClassPath {
}
void writeFile(String f, String contents) throws IOException {
PrintStream s = new PrintStream(new FileOutputStream(f));
s.println(contents);
s.close();
try (PrintStream s = new PrintStream(new FileOutputStream(f))) {
s.println(contents);
}
}
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("elts: " + elts);
for (TypeElement te: ElementFilter.typesIn(elts)) {
try {
Writer out = filer.createSourceFile(te.getSimpleName() + "Wrapper").openWriter();
try (Writer out = filer.createSourceFile(te.getSimpleName() + "Wrapper").openWriter()) {
out.write("class " + te.getSimpleName() + "Wrapper { }");
out.close();
} catch (IOException ex) {
ex.printStackTrace();
}

View File

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

View File

@ -32,6 +32,7 @@
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
@ -178,7 +179,11 @@ public class DetectMutableStaticFields {
int index = className.lastIndexOf('.');
String pckName = index == -1 ? "" : className.substring(0, index);
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 f = new File(classFileName);
FileOutputStream output = new FileOutputStream(f);
output.write(hexToByte(hexString));
output.close();
try (FileOutputStream output = new FileOutputStream(f)) {
output.write(hexToByte(hexString));
}
return f;
}

View File

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

View File

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

View File

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

View File

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

View File

@ -23,6 +23,7 @@
import com.sun.tools.classfile.*;
import java.io.InputStream;
import java.nio.file.Paths;
import java.util.HashSet;
import java.util.List;
@ -66,7 +67,10 @@ public class LineNumberTestBase extends TestBase {
writeToFileIfEnabled(Paths.get(testCase.getName() + ".java"), testCase.src);
Set<Integer> coveredLines = new HashSet<>();
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) {
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.SourceFile_attribute;
import java.io.InputStream;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
@ -84,7 +85,11 @@ public class SourceFileTestBase extends TestBase {
Map<String, ? extends JavaFileObject> classes = compile(sourceCode).getClasses();
String fileName = ToolBox.getJavaFileNameFromSource(sourceCode);
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 {
byte[] bytes = new byte[(int) f.length()];
DataInputStream in = new DataInputStream(new FileInputStream(f));
try {
try (DataInputStream in = new DataInputStream(new FileInputStream(f))) {
in.readFully(bytes);
} finally {
in.close();
}
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.
*/
void scan(JavaFileObject fo, Set<String> results) throws IOException {
InputStream in = fo.openInputStream();
try {
try (InputStream in = fo.openInputStream()) {
ClassFile cf = ClassFile.read(in);
for (ConstantPool.CPInfo cpinfo: cf.constant_pool.entries()) {
if (cpinfo.getTag() == ConstantPool.CONSTANT_Utf8) {
@ -500,8 +499,6 @@ public class CheckResourceKeys {
}
}
} catch (ConstantPoolException ignore) {
} finally {
in.close();
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -66,18 +66,13 @@ public class Utils {
}
public static void createJavaFile(File outFile, File superClass) throws IOException {
PrintStream ps = null;
String srcStr = "public class " + getSimpleName(outFile) + " ";
if (superClass != null) {
srcStr = srcStr.concat("extends " + getSimpleName(superClass) + " ");
}
srcStr = srcStr.concat("{}");
try {
FileOutputStream fos = new FileOutputStream(outFile);
ps = new PrintStream(fos);
try (PrintStream ps = new PrintStream(new FileOutputStream(outFile))) {
ps.println(srcStr);
} finally {
close(ps);
}
}
@ -116,22 +111,12 @@ public class Utils {
}
public static void cat(File output, File... files) throws IOException {
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
FileOutputStream fos = null;
try {
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);
try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(output))) {
for (File file : files) {
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))) {
copyStream(bis, bos);
}
}
} 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.util.Context;
import com.sun.tools.javac.util.JCDiagnostic;
import java.io.InputStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
@ -135,7 +136,10 @@ public class DeduplicationTest {
// lambdas.
Set<String> bootstrapMethodNames = new TreeSet<>();
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")) {
continue;
}

View File

@ -75,24 +75,18 @@ class DirectedClassLoader extends ClassLoader {
}
private Class<?> defineFrom(String name, File file) {
FileInputStream fis = null;
try {
try {
fis = new FileInputStream(file);
byte[] bytes = new byte[fis.available()];
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();
try (FileInputStream fis = new FileInputStream(file)) {
byte[] bytes = new byte[fis.available()];
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);
} catch (IOException e) {}
return null;
}

View File

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

View File

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

View File

@ -39,6 +39,7 @@
*/
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
@ -404,7 +405,9 @@ public class PreviewErrors extends ComboInstance<PreviewErrors> {
if (testClass == null) {
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) {
throw new IllegalStateException(ex);
}

View File

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

View File

@ -53,11 +53,11 @@ public class T6413690 extends JavacTestingAbstractProcessor {
Set<? extends Element> supers = roundEnvironment.getElementsAnnotatedWith(testMe);
try {
for (Element sup : supers) {
Writer sub = filer.createSourceFile(sup.getSimpleName() + "_GENERATED").openWriter();
sub.write(String.format("class %s_GENERATED extends %s {}",
sup.getSimpleName(),
((TypeElement)sup).getQualifiedName()));
sub.close();
try (Writer sub = filer.createSourceFile(sup.getSimpleName() + "_GENERATED").openWriter()) {
sub.write(String.format("class %s_GENERATED extends %s {}",
sup.getSimpleName(),
((TypeElement)sup).getQualifiedName()));
}
}
} catch (IOException 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");
byte[] bytes = new byte[(int) pkgInfo.length()];
DataInputStream in = null;
try {
in = new DataInputStream(new FileInputStream(pkgInfo));
try (DataInputStream in = new DataInputStream(new FileInputStream(pkgInfo))) {
in.readFully(bytes);
} catch (IOException 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 {
if (kind.equals("java"))
out = filer.createSourceFile("foo.package-info").openOutputStream();
else
out = filer.createClassFile("foo.package-info").openOutputStream();
try (OutputStream out = kind.equals("java") ?
filer.createSourceFile("foo.package-info").openOutputStream() :
filer.createClassFile("foo.package-info").openOutputStream()) {
out.write(bytes, 0, bytes.length);
} catch (IOException 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()) {
System.out.println("Writing out source files.");
try {
PrintWriter pw = new PrintWriter(filer.createSourceFile("foo.WrittenAfterProcessing").openWriter());
try {
try (PrintWriter pw = new PrintWriter(filer.createSourceFile("foo.WrittenAfterProcessing").openWriter())) {
pw.println("package foo;");
pw.println("public class WrittenAfterProcessing {");
pw.println(" public WrittenAfterProcessing() {super();}");
pw.println("}");
} finally {
pw.close();
}
pw = new PrintWriter(filer.createSourceFile("foo.package-info").openWriter());
try {
try (PrintWriter pw = new PrintWriter(filer.createSourceFile("foo.package-info").openWriter())) {
pw.println("@Deprecated");
pw.println("package foo;");
} finally {
pw.close();
}
} catch(IOException io) {
throw new RuntimeException(io);

View File

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

View File

@ -406,40 +406,20 @@ public class T6920317 {
/** Read a file. */
byte[] read(File file) {
byte[] bytes = new byte[(int) file.length()];
DataInputStream in = null;
try {
in = new DataInputStream(new FileInputStream(file));
try (DataInputStream in = new DataInputStream(new FileInputStream(file))) {
in.readFully(bytes);
} catch (IOException e) {
error("Error reading file: " + e);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
error("Error closing file: " + e);
}
}
}
return bytes;
}
/** Write a file. */
void write(JavaFileObject file, byte[] bytes) {
OutputStream out = null;
try {
out = file.openOutputStream();
try (OutputStream out = file.openOutputStream()) {
out.write(bytes, 0, bytes.length);
} catch (IOException 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) {
try {
JavaFileObject fo = filer.createSourceFile(name);
Writer out = fo.openWriter();
try {
try (Writer out = fo.openWriter()) {
out.write("class " + name + " {\n"
+ (warn ? " void m() throws Exception { try (AutoCloseable ac = null) { } }" : "")
+ (error ? " ERROR\n" : "")
+ "}\n");
} finally {
out.close();
}
} catch (IOException e) {
throw new Error(e);

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -45,9 +45,9 @@ public class ValidateJarWithSealedAndRecord {
}
void writeFile(String f, String contents) throws IOException {
PrintStream s = new PrintStream(new FileOutputStream(f));
s.println(contents);
s.close();
try (PrintStream s = new PrintStream(new FileOutputStream(f))) {
s.println(contents);
}
}
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.ComboTask;
import combo.ComboTestHelper;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.nio.file.Path;
import java.nio.file.Paths;
@ -111,7 +112,10 @@ public class SwitchExpressionNoValue extends ComboInstance<SwitchExpressionNoVal
if (filesIt.hasNext()) {
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() {
protected Class<?> findClass(String name) throws ClassNotFoundException {
if ("Test".equals(name)) {

View File

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