undefect. CWE-407 — 63 sites patched across 27 ecosystems

Authors: russell@unturf.com · brackishbert@gmail.com · foxhop.net · TimeHexOn.com

Patches, unit tests, benchmarks, whitepaper, and outreach briefs.
Public domain — no copyright claimed. Use freely.
This commit is contained in:
russell@unturf.com 2026-03-26 17:11:57 -04:00
commit 0a580b313d
70422 changed files with 17213626 additions and 0 deletions

View file

@ -0,0 +1,209 @@
/*
* Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 8002157
* @author sogoel
* @summary Basic Syntax test for repeating annotations on all elements
* @modules jdk.compiler
* @build Helper
* @compile BasicSyntaxCombo.java
* @run main BasicSyntaxCombo
*/
import java.util.Arrays;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaFileObject;
import javax.tools.Diagnostic;
/*
* Generate test src for element kinds with repeating annotations.
* The test uses Helper.java to get the template to create test src and
* compile the test src.
* The test passes if valid test src compile as expected and
* and invalid test src fail as expected.
*/
public class BasicSyntaxCombo extends Helper{
static int errors = 0;
static boolean exitMode = false;
static String TESTPKG = "testpkg";
static String srcContent = "";
static String pkgInfoContent = "";
static {
// If EXIT_ON_FAIL is set, the combo test will exit at the first error
String exitOnFail = System.getenv("EXIT_ON_FAIL");
if (exitOnFail == null || exitOnFail == "" ) {
exitMode = false;
}
else {
if (exitOnFail.equalsIgnoreCase("YES") ||
exitOnFail.equalsIgnoreCase("Y") ||
exitOnFail.equalsIgnoreCase("TRUE") ||
exitOnFail.equalsIgnoreCase("T")) {
exitMode = true;
}
}
}
enum TestElem {
ANNOTATION_TYPE(true),
PACKAGE(true),
CONSTRUCTOR(true),
FIELD(true),
LOCAL_VARIABLE(true),
METHOD(true),
TYPE(true),
PARAMETER(true),
INNER_CLASS(true),
STATIC_INI(false),
INSTANCE_INI(false);
TestElem(boolean compile) {
this.compile = compile;
}
boolean compile;
boolean shouldCompile() {
return compile;
}
}
public static void main(String[] args) throws Exception {
new BasicSyntaxCombo().runTest();
}
public void runTest() throws Exception {
boolean result = false;
Iterable<? extends JavaFileObject> files = null;
int testCtr = 0;
for (TestElem type : TestElem.values()) {
testCtr++;
String className = "BasicCombo_"+type;
files = getFileList(className, type);
boolean shouldCompile = type.shouldCompile();
result = getCompileResult(className, shouldCompile,files);
if (shouldCompile && !result) {
error(className + " did not compile as expected", srcContent);
if(!pkgInfoContent.isEmpty()) {
System.out.println("package-info.java contents: " + pkgInfoContent);
}
}
if (!shouldCompile && !result) {
error(className + " compiled unexpectedly", srcContent);
if(!pkgInfoContent.isEmpty()) {
System.out.println("package-info.java contents: " + pkgInfoContent);
}
}
}
System.out.println("Total number of tests run: " + testCtr);
System.out.println("Total number of errors: " + errors);
if (errors > 0)
throw new Exception(errors + " errors found");
}
private boolean getCompileResult(String className, boolean shouldCompile,
Iterable<? extends JavaFileObject> files) throws Exception {
DiagnosticCollector<JavaFileObject> diagnostics =
new DiagnosticCollector<JavaFileObject>();
boolean ok = Helper.compileCode(diagnostics,files);
if (!shouldCompile && !ok) {
checkErrorKeys(className, diagnostics);
}
return (shouldCompile == ok);
}
private void checkErrorKeys (
String className, DiagnosticCollector<JavaFileObject> diagnostics) throws Exception {
String expectedErrKey = "compiler.err.illegal.start.of.type";
for (Diagnostic<?> d : diagnostics.getDiagnostics()) {
if ((d.getKind() == Diagnostic.Kind.ERROR) &&
d.getCode().contains(expectedErrKey)) {
break; // Found the expected error
} else {
error("Incorrect error key, expected = "
+ expectedErrKey + ", Actual = " + d.getCode()
+ " for className = " + className, srcContent);
}
}
}
private Iterable<? extends JavaFileObject> getFileList(String className,
TestElem type ) {
String template = Helper.template;
String replaceStr = "/*"+type+"*/";
StringBuilder annoData = new StringBuilder();
annoData.append(Helper.ContentVars.IMPORTCONTAINERSTMTS.getVal())
.append(Helper.ContentVars.CONTAINER.getVal())
.append(Helper.ContentVars.REPEATABLE.getVal())
.append(Helper.ContentVars.BASE.getVal());
JavaFileObject pkgInfoFile = null;
if (type.equals("PACKAGE")) {
srcContent = template.replace(replaceStr, "package testpkg;")
.replace("#ClassName", className);
String pkgInfoName = TESTPKG+"."+"package-info";
pkgInfoContent = Helper.ContentVars.REPEATABLEANNO.getVal()
+ "package " + TESTPKG + ";"
+ annoData;
pkgInfoFile = getFile(pkgInfoName, pkgInfoContent);
} else {
template = template.replace(replaceStr, Helper.ContentVars.REPEATABLEANNO.getVal())
.replace("#ClassName", className);
srcContent = annoData + template;
}
JavaFileObject srcFile = getFile(className, srcContent);
Iterable<? extends JavaFileObject> files = null;
if (pkgInfoFile != null) {
files = Arrays.asList(pkgInfoFile,srcFile);
}
else {
files = Arrays.asList(srcFile);
}
return files;
}
private void error(String msg, String... contents) throws Exception {
System.out.println("error: " + msg);
errors++;
if (contents.length == 1) {
System.out.println("Contents = " + contents[0]);
}
// Test exits as soon as it gets a failure
if (exitMode) throw new Exception();
}
}

View file

@ -0,0 +1,153 @@
/*
* Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 8002157
* @author sogoel
* @summary Combo test to check for usage of Deprecated
* @modules jdk.compiler
* @build Helper
* @compile DeprecatedAnnoCombo.java
* @run main DeprecatedAnnoCombo
*/
import java.util.List;
import javax.tools.Diagnostic;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaFileObject;
/*
* Generate test src for use of @Deprecated on base anno
* or container anno or on both. In all cases, test src should compile and a
* warning should be generated. Repeating annotations used only on class for
* these generated test src.
*/
public class DeprecatedAnnoCombo extends Helper {
static int errors = 0;
enum TestCases {
DeprecatedonBoth,
DeprecatedonContainer,
DeprecatedonBase;
}
public static void main(String[] args) throws Exception {
new DeprecatedAnnoCombo().runTest();
}
public void runTest() throws Exception {
boolean ok = false;
int testCtr = 0;
for (TestCases clName : TestCases.values()) {
testCtr++;
// Create test source content
String contents = getContent(clName.toString());
// Compile the generated source file
DiagnosticCollector<JavaFileObject> diagnostics =
new DiagnosticCollector<JavaFileObject>();
ok = compileCode(clName.toString(), contents, diagnostics);
String errorKey1 = "compiler.note.deprecated.filename";
String errorKey2 = "compiler.note.deprecated.recompile";
List<Diagnostic<? extends JavaFileObject>> diags = diagnostics.getDiagnostics();
//Check for deprecated warnings
if (ok) {
if (diags.size() == 0) {
error("Did not get any warnings for @Deprecated usage");
} else {
for (Diagnostic<?> d : diags) {
if (d.getKind() == Diagnostic.Kind.NOTE) {
if (d.getCode().contains(errorKey1)
|| d.getCode().contains(errorKey2)) {
System.out.println("TestCase =" + clName + " passed as expected");
} else {
error("TestCase =" + clName + " did not give correct warnings" +
"Expected warning keys: " +
"errorKey1 = " + errorKey1 +
"errorKey2 = " + errorKey2 +
"actualErrorKey = " + d.getCode(), contents);
}
} else {
error("Diagnostic Kind is incorrect, expected = " +
Diagnostic.Kind.NOTE + "actual = " + d.getKind(), contents);
}
}
}
} else {
error("TestCase =" + clName + " did not compile as expected", contents);
}
}
System.out.println("Total number of tests run: " + testCtr);
System.out.println("Total number of errors: " + errors);
if (errors > 0)
throw new Exception(errors + " errors found");
}
private String getContent(String className) {
StringBuilder annoData = new StringBuilder();
switch(className) {
case "DeprecatedonBoth":
annoData.append(Helper.ContentVars.DEPRECATED.getVal())
.append(Helper.ContentVars.CONTAINER.getVal())
.append(Helper.ContentVars.DEPRECATED.getVal())
.append(Helper.ContentVars.REPEATABLE.getVal())
.append(Helper.ContentVars.BASE.getVal());
break;
case "DeprecatedonBase":
annoData.append(Helper.ContentVars.CONTAINER.getVal())
.append(Helper.ContentVars.DEPRECATED.getVal())
.append(Helper.ContentVars.REPEATABLE.getVal())
.append(Helper.ContentVars.BASE.getVal());
break;
case "DeprecatedonContainer":
annoData.append(Helper.ContentVars.DEPRECATED.getVal())
.append(Helper.ContentVars.CONTAINER.getVal())
.append(Helper.ContentVars.REPEATABLE.getVal())
.append(Helper.ContentVars.BASE.getVal());
break;
}
String contents = Helper.ContentVars.IMPORTCONTAINERSTMTS.getVal()
+ Helper.ContentVars.IMPORTDEPRECATED.getVal()
+ annoData
+ Helper.ContentVars.REPEATABLEANNO.getVal()
+ "\nclass "+ className + "{}";
return contents;
}
private void error(String msg, String... contents) {
System.out.println("error: " + msg);
errors++;
if (contents.length == 1) {
System.out.println("Contents = " + contents[0]);
}
}
}

View file

@ -0,0 +1,126 @@
/*
* Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 8002157
* @author sogoel
* @summary Positive combo test for use of Documented on baseAnno/containerAnno
* @modules jdk.compiler
* @build Helper
* @compile DocumentedAnnoCombo.java
* @run main DocumentedAnnoCombo
*/
import javax.tools.DiagnosticCollector;
import javax.tools.JavaFileObject;
/*
* Generate valid test src for the use of @Documented on container anno
* or on both base anno and container anno. Both test src should compile.
* Repeating annotations used only on class for these generated test src.
*/
public class DocumentedAnnoCombo extends Helper {
static int errors = 0;
enum TestCases {
DocumentedonBothAnno(true),
DocumentedonContainer(true);
TestCases(boolean compile) {
this.compile = compile;
}
boolean compile;
boolean shouldCompile() {
return compile;
}
}
public static void main(String[] args) throws Exception {
new DocumentedAnnoCombo().runTest();
}
public void runTest() throws Exception {
boolean ok = false;
int testCtr = 0;
// Create test source content
for (TestCases className : TestCases.values()) {
testCtr++;
String contents = getContent(className.toString());
// Compile the generated source file
DiagnosticCollector<JavaFileObject> diagnostics =
new DiagnosticCollector<JavaFileObject>();
ok = compileCode(className.toString(), contents, diagnostics);
if (!ok) {
error("Class="+ className +" did not compile as expected", contents);
} else {
System.out.println("Test passed for className: " + className);
}
}
System.out.println("Total number of tests run: " + testCtr);
System.out.println("Total number of errors: " + errors);
if (errors > 0)
throw new Exception(errors + " errors found");
}
private String getContent(String className) {
StringBuilder annoData = new StringBuilder();
switch(className) {
case "DocumentedonBothAnno":
annoData.append(Helper.ContentVars.DOCUMENTED.getVal())
.append(Helper.ContentVars.CONTAINER.getVal())
.append(Helper.ContentVars.DOCUMENTED.getVal())
.append(Helper.ContentVars.REPEATABLE.getVal())
.append(Helper.ContentVars.BASE.getVal());
break;
case "DocumentedonContainer":
annoData.append(Helper.ContentVars.DOCUMENTED.getVal())
.append(Helper.ContentVars.CONTAINER.getVal())
.append(Helper.ContentVars.REPEATABLE.getVal())
.append(Helper.ContentVars.BASE.getVal());
break;
}
String contents = Helper.ContentVars.IMPORTCONTAINERSTMTS.getVal()
+ Helper.ContentVars.IMPORTDOCUMENTED.getVal()
+ annoData
+ Helper.ContentVars.REPEATABLEANNO.getVal()
+ "\nclass "+ className + "{}";
return contents;
}
private void error(String msg, String... contents) {
System.out.println("error: " + msg);
errors++;
if (contents.length == 1) {
System.out.println("Contents = " + contents[0]);
}
}
}

View file

@ -0,0 +1,214 @@
/*
* Copyright (c) 2012, 2020, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.Iterator;
import javax.tools.Diagnostic;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompiler;
import javax.tools.JavaCompiler.CompilationTask;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.StandardLocation;
import javax.tools.ToolProvider;
import com.sun.source.util.JavacTask;
public class Helper {
enum ContentVars {
IMPORTCONTAINERSTMTS("\nimport java.lang.annotation.Repeatable;\n"),
IMPORTDEPRECATED("import java.lang.Deprecated;\n"),
IMPORTDOCUMENTED("import java.lang.annotation.Documented;\n"),
IMPORTINHERITED("import java.lang.annotation.Inherited;\n"),
IMPORTRETENTION("import java.lang.annotation.Retention;\n"
+ "\nimport java.lang.annotation.RetentionPolicy;\n"),
IMPORTSTMTS("import java.lang.annotation.*;\n"),
IMPORTEXPECTED("import expectedFiles.*;\n"),
REPEATABLE("\n@Repeatable(FooContainer.class)\n"),
CONTAINER("@interface FooContainer {\n" + " Foo[] value();\n}\n"),
BASE("@interface Foo {int value() default Integer.MAX_VALUE;}\n"),
BASEANNO("@Foo(0)"),
LEGACYCONTAINER("@FooContainer(value = {@Foo(1), @Foo(2)})\n"),
REPEATABLEANNO("\n@Foo(1) @Foo(2)"),
DEPRECATED("\n@Deprecated"),
DOCUMENTED("\n@Documented"),
INHERITED("\n@Inherited"),
TARGET("\n@Target(#VAL)\n"),
RETENTION("@Retention(RetentionPolicy.#VAL)\n"),
RETENTIONRUNTIME("@Retention(RetentionPolicy.RUNTIME)\n");
private String val;
private ContentVars(String val) {
this.val = val;
}
public String getVal() {
return val;
}
}
// Create and compile FileObject using values for className and contents
public static boolean compileCode(String className, String contents,
DiagnosticCollector<JavaFileObject> diagnostics) {
boolean ok = false;
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
if (compiler == null) {
throw new RuntimeException("can't get javax.tools.JavaCompiler!");
}
JavaFileObject file = getFile(className, contents);
Iterable<? extends JavaFileObject> compilationUnit = Arrays.asList(file);
CompilationTask task = compiler.getTask(null, null, diagnostics, null, null, compilationUnit);
ok = task.call();
return ok;
}
// Compile a list of FileObjects
// Used when packages are needed and classes need to be loaded at runtime
static File destDir = new File(System.getProperty("user.dir"));
public static boolean compileCode(DiagnosticCollector<JavaFileObject> diagnostics, Iterable<? extends JavaFileObject> files) {
return compileCode(diagnostics, files, null);
}
public static boolean compileCode(DiagnosticCollector<JavaFileObject> diagnostics, Iterable<? extends JavaFileObject> files, Iterable<String> options) {
boolean ok = false;
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
if (compiler == null) {
throw new RuntimeException("can't get javax.tools.JavaCompiler!");
}
try (StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, null)) {
// Assuming filesCount can maximum be 2 and if true, one file is package-info.java
if (isPkgInfoPresent(files)) {
JavacTask task = (JavacTask) compiler.getTask(null, fm, diagnostics, options, null, files);
try {
fm.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(destDir));
task.generate();
} catch (IOException ioe) {
throw new RuntimeException("Compilation failed for package level tests", ioe);
}
int err = 0;
for (Diagnostic<? extends JavaFileObject> d : diagnostics.getDiagnostics()) {
if(d.getKind() == Diagnostic.Kind.ERROR) {
err++;
}
}
ok = (err == 0);
} else {
CompilationTask task = compiler.getTask(null, null, diagnostics, options, null, files);
ok = task.call();
}
return ok;
} catch (IOException e) {
throw new Error(e);
}
}
static private boolean isPkgInfoPresent(Iterable<? extends JavaFileObject> files) {
Iterator<? extends JavaFileObject> itr = files.iterator();
while (itr.hasNext()) {
String name = itr.next().getName();
if (name.contains("package-info")) {
return true;
}
}
return false;
}
/* String template where /*<TYPE>*/ /*gets replaced by repeating anno
* Used to generate test src for combo tests
* - BasicSyntaxCombo.java
* - TargetAnnoCombo.java
*/
public static final String template =
"/*PACKAGE*/\n"
+ "//pkg test;\n\n"
+ "/*ANNODATA*/\n" // import statements, declaration of Foo/FooContainer
+ "/*TYPE*/ //class\n"
+ "class #ClassName {\n"
+ " /*FIELD*/ //instance var\n"
+ " public int x = 0;\n\n"
+ " /*FIELD*/ //Enum constants\n"
+ " TestEnum testEnum;\n\n"
+ " /*FIELD*/ // Static field\n"
+ " public static int num;\n\n"
+ " /*STATIC_INI*/\n"
+ " static { \n" + "num = 10; \n }\n\n"
+ " /*CONSTRUCTOR*/\n"
+ " #ClassName() {}\n\n"
+ " /*INSTANCE_INI*/\n"
+ " { \n x = 10; \n }"
+ " /*INNER_CLASS*/\n"
+ " class innerClass {}\n"
+ " /*METHOD*/\n"
+ " void bar(/*PARAMETER*/ int baz) {\n"
+ " /*LOCAL_VARIABLE*/\n"
+ " int y = 0;\n"
+ " }\n"
+ "}\n\n"
+ "/*TYPE*/ //Enum\n"
+ "enum TestEnum {}\n\n"
+ "/*TYPE*/ //Interface\n"
+ "interface TestInterface {}\n\n"
+ "/*TYPE*/\n"
+ "/*ANNOTATION_TYPE*/\n"
+ "@interface TestAnnotationType{}\n"
+ "class TestPkg {}\n"
+ "class TestTypeAnno </*TYPE_PARAMETER*/ T extends Object> {\n"
+ " String /*TYPE_USE*/[] arr;\n"
+ "}";
static JavaFileObject getFile(String name, String code) {
JavaFileObject o = null;
try {
o = new JavaStringFileObject(name, code);
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
return o;
}
static class JavaStringFileObject extends SimpleJavaFileObject {
final String theCode;
public JavaStringFileObject(String fileName, String theCode) throws URISyntaxException {
super(new URI("string:///" + fileName.replace('.', '/') + ".java"), Kind.SOURCE);
this.theCode = theCode;
}
@Override
public CharSequence getCharContent(boolean ignoreEncodingErrors) {
return theCode;
}
}
}

View file

@ -0,0 +1,127 @@
/*
* Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 8002157
* @author sogoel
* @summary Positive combo test for use of Inherited on baseAnno/containerAnno
* @modules jdk.compiler
* @build Helper
* @compile InheritedAnnoCombo.java
* @run main InheritedAnnoCombo
*/
import javax.tools.DiagnosticCollector;
import javax.tools.JavaFileObject;
/*
* Generate valid test src for the use of @Inherited on container anno
* or on both base anno and container anno. Both test src should compile.
* Repeating annotations used only on class for these generated test src.
*/
public class InheritedAnnoCombo extends Helper {
static int errors = 0;
enum TestCases {
InheritedonBothAnno(true),
InheritedonBase(true);
TestCases(boolean compile) {
this.compile = compile;
}
boolean compile;
boolean shouldCompile() {
return compile;
}
}
public static void main(String[] args) throws Exception {
new InheritedAnnoCombo().runTest();
}
public void runTest() throws Exception {
int testCtr = 0;
boolean ok = false;
// Create test source content
for (TestCases className : TestCases.values()) {
testCtr++;
String contents = getContent(className.toString());
// Compile the generated code
DiagnosticCollector<JavaFileObject> diagnostics =
new DiagnosticCollector<JavaFileObject>();
ok = compileCode(className.toString(), contents, diagnostics);
if (!ok) {
error("Class="+ className +" did not compile as expected", contents);
} else {
System.out.println("Test passed for className: " + className);
}
}
System.out.println("Total number of tests run: " + testCtr);
System.out.println("Total number of errors: " + errors);
if (errors > 0)
throw new Exception(errors + " errors found");
}
private String getContent(String className) {
StringBuilder annoData = new StringBuilder();
switch(className) {
case "InheritedonBothAnno":
annoData.append(Helper.ContentVars.INHERITED.getVal())
.append(Helper.ContentVars.CONTAINER.getVal())
.append(Helper.ContentVars.INHERITED.getVal())
.append(Helper.ContentVars.REPEATABLE.getVal())
.append(Helper.ContentVars.BASE.getVal());
break;
case "InheritedonBase":
annoData.append(Helper.ContentVars.INHERITED.getVal())
.append(Helper.ContentVars.CONTAINER.getVal())
.append(Helper.ContentVars.REPEATABLE.getVal())
.append(Helper.ContentVars.BASE.getVal());
break;
}
String contents = Helper.ContentVars.IMPORTCONTAINERSTMTS.getVal()
+ Helper.ContentVars.IMPORTINHERITED.getVal()
+ annoData
+ Helper.ContentVars.REPEATABLEANNO.getVal()
+ "\nclass "+ className + "{}";
return contents;
}
private void error(String msg, String... contents) {
System.out.println("error: " + msg);
errors++;
if (contents.length == 1) {
System.out.println("Contents = " + contents[0]);
}
}
}

View file

@ -0,0 +1,201 @@
/*
* Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 8002157
* @author sogoel
* @summary Combo test for all possible combinations for Retention Values
* @modules jdk.compiler
* @build Helper
* @compile RetentionAnnoCombo.java
* @run main RetentionAnnoCombo
*/
import java.util.HashMap;
import java.util.Map;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaFileObject;
import javax.tools.Diagnostic;
/*
* Generate all combinations for the use of @Retention on base anno or container
* anno or both. The test passes if valid test src compile as expected and
* and invalid test src fail as expected.
* Repeating annotations used only on class for these generated test src.
*/
public class RetentionAnnoCombo extends Helper {
static int errors = 0;
static boolean exitMode = false;
static {
String exitOnFail = System.getenv("EXIT_ON_FAIL");
if (exitOnFail == null || exitOnFail == "" ) {
exitMode = false;
}
else {
if (exitOnFail.equalsIgnoreCase("YES") ||
exitOnFail.equalsIgnoreCase("Y") ||
exitOnFail.equalsIgnoreCase("TRUE") ||
exitOnFail.equalsIgnoreCase("T")) {
exitMode = true;
}
}
}
public static void main(String args[]) throws Exception {
new RetentionAnnoCombo().runTest();
}
public void runTest() throws Exception {
/* 4x4 matrix for Retention values SOURCE, DEFAULT, CLASS, RUNTIME
* i -> Retention value on ContainerAnno
* j -> Retention value on BaseAnno
* 1 -> retention value combo should compile
*/
int[][] retention = { {1, 0, 0, 0},
{1, 1, 1, 0},
{1, 1, 1, 0},
{1, 1, 1, 1} };
Map<Integer, String> retMap = setRetentionValMatrix();
String contents = "";
boolean result = false;
int testCtr = 0;
for (int i = 0; i < 4 ; i ++) {
for (int j = 0; j < 4; j++ ) {
testCtr++;
String className = "RetentionTest_"+i+"_"+j;
contents = getContent(className, retMap, i, j);
if (retention[i][j] == 1) {
// Code generated should compile
result = getCompileResult(contents,className, true);
if (!result) {
error("FAIL: " + className + " did not compile as expected!", contents);
}
} else {
result = getCompileResult(contents,className, false);
if (!result) {
error("FAIL: " + className + " compiled unexpectedly!", contents);
}
}
if (result) {
System.out.println("Test passed for className = " + className);
}
}
}
System.out.println("Total number of tests run: " + testCtr);
System.out.println("Total number of errors: " + errors);
if (errors > 0)
throw new Exception(errors + " errors found");
}
private boolean getCompileResult(String contents, String className,
boolean shouldCompile) throws Exception{
DiagnosticCollector<JavaFileObject> diagnostics =
new DiagnosticCollector<JavaFileObject>();
boolean ok = compileCode(className, contents, diagnostics);
String expectedErrKey = "compiler.err.invalid.repeatable" +
".annotation.retention";
if (!shouldCompile && !ok) {
for (Diagnostic<?> d : diagnostics.getDiagnostics()) {
if (!((d.getKind() == Diagnostic.Kind.ERROR) &&
d.getCode().contains(expectedErrKey))) {
error("FAIL: Incorrect error given, expected = "
+ expectedErrKey + ", Actual = " + d.getCode()
+ " for className = " + className, contents);
}
}
}
return (shouldCompile == ok);
}
private Map<Integer,String> setRetentionValMatrix() {
HashMap<Integer,String> hm = new HashMap<>();
hm.put(0,"SOURCE");
hm.put(1,"DEFAULT");
hm.put(2,"CLASS");
hm.put(3,"RUNTIME");
return hm;
}
private String getContent(String className, Map<Integer, String> retMap,
int i, int j) {
String retContainerVal = retMap.get(i).toString();
String retBaseVal = retMap.get(j).toString();
String replacedRetBaseVal = "", replacedRetCAVal = "";
String retention = Helper.ContentVars.RETENTION.getVal();
// @Retention is available as default for both base and container anno
if (retContainerVal.equalsIgnoreCase("DEFAULT")
&& retBaseVal.equalsIgnoreCase("DEFAULT")) {
replacedRetBaseVal = "";
replacedRetCAVal = "";
// @Retention is available as default for container anno
} else if (retContainerVal.equalsIgnoreCase("DEFAULT")) {
replacedRetBaseVal = retention.replace("#VAL", retBaseVal);
replacedRetCAVal = "";
// @Retention is available as default for base anno
} else if (retBaseVal.equalsIgnoreCase("DEFAULT")) {
replacedRetBaseVal = "";
replacedRetCAVal = retention.replace("#VAL", retContainerVal);
// @Retention is not available as default for both base and container anno
} else {
replacedRetBaseVal = retention.replace("#VAL", retBaseVal);
replacedRetCAVal = retention.replace("#VAL", retContainerVal);
}
StringBuilder annoData = new StringBuilder();
annoData.append(Helper.ContentVars.IMPORTCONTAINERSTMTS.getVal())
.append(Helper.ContentVars.IMPORTRETENTION.getVal())
.append(replacedRetCAVal)
.append(Helper.ContentVars.CONTAINER.getVal())
.append(Helper.ContentVars.REPEATABLE.getVal())
.append(replacedRetBaseVal)
.append(Helper.ContentVars.BASE.getVal());
String contents = annoData
+ Helper.ContentVars.REPEATABLEANNO.getVal()
+ "\nclass "+ className + "{}";
return contents;
}
private void error(String msg,String... contents) throws Exception {
System.out.println("error: " + msg);
errors++;
if (contents.length == 1) {
System.out.println("Contents = " + contents[0]);
}
// Test exits as soon as it gets a failure
if (exitMode) throw new Exception();
}
}

View file

@ -0,0 +1,532 @@
/*
* Copyright (c) 2013, 2020, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 7151010 8006547 8007766 8029017 8246774
* @summary Default test cases for running combinations for Target values
* @modules jdk.compiler
* @build Helper
* @run main TargetAnnoCombo
*/
import java.util.Set;
import java.util.List;
import java.io.IOException;
import java.lang.annotation.ElementType;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.EnumSet;
import javax.tools.Diagnostic;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaFileObject;
import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.CONSTRUCTOR;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.ElementType.PACKAGE;
import static java.lang.annotation.ElementType.LOCAL_VARIABLE;
import static java.lang.annotation.ElementType.TYPE_USE;
import static java.lang.annotation.ElementType.TYPE_PARAMETER;
import static java.lang.annotation.ElementType.RECORD_COMPONENT;
public class TargetAnnoCombo {
static final String TESTPKG = "testpkg";
// Set it to true to get more debug information including base and container
// target sets for a given test case.
static final boolean DEBUG = false;
// Define constant target sets to be used for the combination of the target values.
final static Set<ElementType> noSet = null;
final static Set<ElementType> empty = EnumSet.noneOf(ElementType.class);
// [TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE, ANNOTATION_TYPE,
// PACKAGE, TYPE_PARAMETER, TYPE_USE, RECORD_COMPONENT]
final static Set<ElementType> allTargets = EnumSet.allOf(ElementType.class);
// [TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE, ANNOTATION_TYPE,
// PACKAGE]
final static Set<ElementType> jdk7 = EnumSet.range(TYPE, PACKAGE);
// [TYPE_USE, TYPE_PARAMETER]
final static Set<ElementType> jdk8 = EnumSet.range(TYPE_PARAMETER, TYPE_USE);
// List of test cases to run. This list is created in generate().
// To run a specific test cases add case number in @run main line.
List<TestCase> testCases = new ArrayList<TestCase>();
int errors = 0;
// Identify test cases that fail.
enum IgnoreKind {
RUN,
IGNORE
};
private class TestCase {
private Set<ElementType> baseAnnotations;
private Set<ElementType> containerAnnotations;
private IgnoreKind ignore;
java.util.List<String> options;
public TestCase(Set<ElementType> baseAnnotations, Set<ElementType> containerAnnotations) {
this(baseAnnotations, containerAnnotations, IgnoreKind.RUN, null);
}
public TestCase(Set<ElementType> baseAnnotations, Set<ElementType> containerAnnotations, List<String> options) {
this(baseAnnotations, containerAnnotations, IgnoreKind.RUN, options);
}
public TestCase(Set<ElementType> baseAnnotations, Set<ElementType> containerAnnotations,
IgnoreKind ignoreKind, java.util.List<String> options) {
this.baseAnnotations = baseAnnotations;
this.containerAnnotations = containerAnnotations;
this.ignore = ignoreKind;
this.options = options;
}
public Set getBaseAnnotations() {
return baseAnnotations;
}
public Set getContainerAnnotations() {
return containerAnnotations;
}
public boolean isIgnored() {
return ignore == IgnoreKind.IGNORE;
}
// Determine if a testCase should compile or not.
private boolean isValidSubSet() {
/*
* RULE 1: conAnnoTarget should be a subset of baseAnnoTarget
* RULE 2: For empty @Target ({}) - annotation cannot be applied anywhere
* - Empty sets for both is valid
* - Empty baseTarget set is invalid with non-empty conTarget set
* - Non-empty baseTarget set is valid with empty conTarget set
* RULE 3: For no @Target specified - annotation can be applied to any JDK 7 targets
* - No @Target for both is valid
* - No @Target for baseTarget set with @Target conTarget set is valid
* - @Target for baseTarget set with no @Target for conTarget is invalid
*/
/* If baseAnno has no @Target, Foo can be either applied to @Target specified
* for container annotation else will be applicable for all default targets
* if no @Target is present for container annotation.
* In both cases, the set will be a valid set with no @Target for base annotation
*/
if (baseAnnotations == null) {
if (containerAnnotations == null) {
return true;
}
return !(containerAnnotations.contains(TYPE_USE) ||
containerAnnotations.contains(TYPE_PARAMETER));
}
Set<ElementType> tempBaseSet = EnumSet.noneOf(ElementType.class);
tempBaseSet.addAll(baseAnnotations);
// If BaseAnno has TYPE, then ANNOTATION_TYPE is allowed by default.
if (baseAnnotations.contains(TYPE)) {
tempBaseSet.add(ANNOTATION_TYPE);
}
// If BaseAnno has TYPE_USE, then add the extra allowed types
if (baseAnnotations.contains(TYPE_USE)) {
tempBaseSet.add(ANNOTATION_TYPE);
tempBaseSet.add(TYPE);
tempBaseSet.add(TYPE_PARAMETER);
}
// If containerAnno has no @Target, only valid case if baseAnnoTarget has
// all targets defined else invalid set.
if (containerAnnotations == null) {
return tempBaseSet.containsAll(jdk7);
}
// At this point, neither conAnnoTarget or baseAnnoTarget are null.
if (containerAnnotations.isEmpty()) {
return true;
}
// At this point, conAnnoTarget is non-empty.
if (baseAnnotations.isEmpty()) {
return false;
}
// At this point, neither conAnnoTarget or baseAnnoTarget are empty.
return tempBaseSet.containsAll(containerAnnotations);
}
}
public static void main(String args[]) throws Exception {
TargetAnnoCombo tac = new TargetAnnoCombo();
// Generates all test cases to be run.
tac.generate();
List<Integer> cases = new ArrayList<Integer>();
for (int i = 0; i < args.length; i++) {
cases.add(Integer.parseInt(args[i]));
}
if (cases.isEmpty()) {
tac.run();
} else {
for (int index : cases) {
tac.executeTestCase(tac.testCases.get(index), index);
}
}
}
// options to be passed if target RECORD_COMPONENT can't be considered
List<String> source8 = List.of("-source", "8");
private void generate() {
// Adding test cases to run.
testCases.addAll(Arrays.asList(
// No base target against no container target.
/* 0*/ new TestCase(noSet, noSet),
// No base target against empty container target.
/* 1*/ new TestCase(noSet, empty),
// No base target against TYPE_USE only container target.
new TestCase(noSet, less(jdk8, TYPE_PARAMETER), source8),
// No base target against TYPE_PARAMETER only container target.
new TestCase(noSet, less(jdk8, TYPE_USE), source8),
// No base target against TYPE_USE + TYPE_PARAMETER only container target.
new TestCase(noSet, jdk8, source8),
// No base target against TYPE_USE + some selection of jdk7 targets.
new TestCase(noSet,
plus(EnumSet.range(TYPE, LOCAL_VARIABLE), TYPE_USE)),
// No base target against TYPE_PARAMETER + some selection of jdk7 targets.
new TestCase(noSet,
plus(EnumSet.range(TYPE, LOCAL_VARIABLE), TYPE_PARAMETER)),
// No base target against each jdk7 target alone as container target.
new TestCase(noSet, plus(empty, TYPE)),
new TestCase(noSet, plus(empty, PARAMETER)),
new TestCase(noSet, plus(empty, PACKAGE)),
/* 10*/ new TestCase(noSet, plus(empty, METHOD)),
new TestCase(noSet, plus(empty, LOCAL_VARIABLE)),
new TestCase(noSet, plus(empty, FIELD)),
new TestCase(noSet, plus(empty, CONSTRUCTOR)),
new TestCase(noSet, plus(empty, ANNOTATION_TYPE)),
// Empty base target against no container target.
new TestCase(empty, noSet),
// Empty base target against empty container target.
new TestCase(empty, empty),
// Empty base target against any lone container target.
new TestCase(empty, plus(empty, TYPE)),
new TestCase(empty, plus(empty, PARAMETER)),
new TestCase(empty, plus(empty, PACKAGE)),
/* 20*/ new TestCase(empty, plus(empty, METHOD)),
new TestCase(empty, plus(empty, LOCAL_VARIABLE)),
new TestCase(empty, plus(empty, FIELD)),
new TestCase(empty, plus(empty, CONSTRUCTOR)),
new TestCase(empty, plus(empty, ANNOTATION_TYPE)),
new TestCase(empty, less(jdk8, TYPE_USE), source8),
new TestCase(empty, less(jdk8, TYPE_PARAMETER), source8),
// No container target against all all-but one jdk7 targets.
new TestCase(less(jdk7, TYPE), noSet, source8),
new TestCase(less(jdk7, PARAMETER), noSet, source8),
new TestCase(less(jdk7, PACKAGE), noSet, source8),
/* 30*/ new TestCase(less(jdk7, METHOD), noSet, source8),
new TestCase(less(jdk7, LOCAL_VARIABLE), noSet, source8),
new TestCase(less(jdk7, FIELD), noSet, source8),
new TestCase(less(jdk7, CONSTRUCTOR), noSet, source8),
new TestCase(less(jdk7, ANNOTATION_TYPE), noSet, source8),
// No container against all but TYPE and ANNOTATION_TYPE
new TestCase(less(jdk7, TYPE, ANNOTATION_TYPE), noSet),
// No container against jdk7 targets.
new TestCase(jdk7, noSet, source8),
// No container against jdk7 targets plus one or both of TYPE_USE, TYPE_PARAMETER
new TestCase(plus(jdk7, TYPE_USE), noSet, source8),
new TestCase(plus(jdk7, TYPE_PARAMETER), noSet, source8),
new TestCase(allTargets, noSet, null),
// Empty container target against any lone target.
/* 40*/ new TestCase(plus(empty, TYPE), empty),
new TestCase(plus(empty, PARAMETER), empty),
new TestCase(plus(empty, PACKAGE), empty),
new TestCase(plus(empty, METHOD), empty),
new TestCase(plus(empty, LOCAL_VARIABLE), empty),
new TestCase(plus(empty, FIELD), empty),
new TestCase(plus(empty, CONSTRUCTOR), empty),
new TestCase(plus(empty, ANNOTATION_TYPE), empty),
new TestCase(plus(empty, TYPE_USE), empty),
new TestCase(plus(empty, TYPE_PARAMETER), empty),
// All base targets against all container targets.
/* 50*/ new TestCase(allTargets, allTargets),
// All base targets against all but one container targets.
new TestCase(allTargets, less(allTargets, TYPE)),
new TestCase(allTargets, less(allTargets, PARAMETER)),
new TestCase(allTargets, less(allTargets, PACKAGE)),
new TestCase(allTargets, less(allTargets, METHOD)),
new TestCase(allTargets, less(allTargets, LOCAL_VARIABLE)),
new TestCase(allTargets, less(allTargets, FIELD)),
new TestCase(allTargets, less(allTargets, CONSTRUCTOR)),
new TestCase(allTargets, less(allTargets, ANNOTATION_TYPE)),
new TestCase(allTargets, less(allTargets, TYPE_USE)),
/* 60*/ new TestCase(allTargets, less(allTargets, TYPE_PARAMETER)),
// All container targets against all but one base targets.
new TestCase(less(allTargets, TYPE), allTargets),
new TestCase(less(allTargets, PARAMETER), allTargets),
new TestCase(less(allTargets, PACKAGE), allTargets),
new TestCase(less(allTargets, METHOD), allTargets),
new TestCase(less(allTargets, LOCAL_VARIABLE), allTargets),
new TestCase(less(allTargets, FIELD), allTargets),
new TestCase(less(allTargets, CONSTRUCTOR), allTargets),
new TestCase(less(allTargets, ANNOTATION_TYPE), allTargets),
new TestCase(less(allTargets, TYPE_USE), allTargets),
/* 70*/ new TestCase(less(allTargets, TYPE_PARAMETER), allTargets)));
// Generates 100 test cases for any lone base target contained in Set
// allTargets against any lone container target.
for (ElementType b : allTargets) {
for (ElementType c : allTargets) {
testCases.add(new TestCase(plus(empty, b), plus(empty, c)));
}
}
}
void run() throws Exception {
int testCtr = 0;
for (TestCase tc : testCases) {
if (!tc.isIgnored()) {
executeTestCase(tc, testCases.indexOf(tc));
testCtr++;
}
}
System.out.println("Total tests run: " + testCtr);
if (errors > 0) {
throw new Exception(errors + " errors found");
}
}
private void executeTestCase(TestCase testCase, int index) {
debugPrint("Test case number = " + index);
debugPrint(" => baseAnnoTarget = " + testCase.getBaseAnnotations());
debugPrint(" => containerAnnoTarget = " + testCase.getContainerAnnotations());
String className = "TC" + index;
boolean shouldCompile = testCase.isValidSubSet();
Iterable<? extends JavaFileObject> files = getFileList(className, testCase, shouldCompile);
// Get result of compiling test src file(s).
boolean result = getCompileResult(className, shouldCompile, files, testCase.options);
// List test src code if test fails.
if (!result) {
System.out.println("FAIL: Test " + index);
try {
for (JavaFileObject f : files) {
System.out.println("File: " + f.getName() + "\n" + f.getCharContent(true));
}
} catch (IOException ioe) {
System.out.println("Exception: " + ioe);
}
} else {
debugPrint("PASS: Test " + index);
}
}
// Create src code and corresponding JavaFileObjects.
private Iterable<? extends JavaFileObject> getFileList(String className,
TestCase testCase, boolean shouldCompile) {
Set<ElementType> baseAnnoTarget = testCase.getBaseAnnotations();
Set<ElementType> conAnnoTarget = testCase.getContainerAnnotations();
String srcContent = "";
String pkgInfoContent = "";
String template = Helper.template;
String baseTarget = "", conTarget = "";
String target = Helper.ContentVars.TARGET.getVal();
if (baseAnnoTarget != null) {
String tmp = target.replace("#VAL", convertToString(baseAnnoTarget).toString());
baseTarget = tmp.replace("[", "{").replace("]", "}");
}
if (conAnnoTarget != null) {
String tmp = target.replace("#VAL", convertToString(conAnnoTarget).toString());
conTarget = tmp.replace("[", "{").replace("]", "}");
}
String annoData = Helper.ContentVars.IMPORTSTMTS.getVal()
+ conTarget
+ Helper.ContentVars.CONTAINER.getVal()
+ baseTarget
+ Helper.ContentVars.REPEATABLE.getVal()
+ Helper.ContentVars.BASE.getVal();
JavaFileObject pkgInfoFile = null;
// If shouldCompile = true and no @Target is specified for container annotation,
// then all 8 ElementType enum constants are applicable as targets for
// container annotation.
if (shouldCompile && conAnnoTarget == null) {
Set<ElementType> copySet = EnumSet.noneOf(ElementType.class);
copySet.addAll(jdk7);
conAnnoTarget = copySet;
}
if (shouldCompile) {
boolean isPkgCasePresent = conAnnoTarget.contains(PACKAGE);
String repeatableAnno = Helper.ContentVars.BASEANNO.getVal()
+ " " + Helper.ContentVars.BASEANNO.getVal();
for (ElementType s : conAnnoTarget) {
String replaceStr = "/*" + s.name() + "*/";
if (s.name().equalsIgnoreCase("PACKAGE")) {
//Create packageInfo file.
String pkgInfoName = TESTPKG + "." + "package-info";
pkgInfoContent = repeatableAnno + "\npackage " + TESTPKG + ";" + annoData;
pkgInfoFile = Helper.getFile(pkgInfoName, pkgInfoContent);
} else {
template = template.replace(replaceStr, repeatableAnno);
if (!isPkgCasePresent) {
srcContent = template.replace(
"/*ANNODATA*/", annoData).replace("#ClassName", className);
} else {
replaceStr = "/*PACKAGE*/";
String tmp = template.replace(replaceStr, "package " + TESTPKG + ";");
srcContent = tmp.replace("#ClassName", className);
}
}
}
} else {
// For invalid cases, compilation should fail at declaration site.
template = "class #ClassName {}";
srcContent = annoData + template.replace("#ClassName", className);
}
JavaFileObject srcFile = Helper.getFile(className, srcContent);
Iterable<? extends JavaFileObject> files = null;
if (pkgInfoFile != null) {
files = Arrays.asList(pkgInfoFile, srcFile);
} else {
files = Arrays.asList(srcFile);
}
return files;
}
// Compile the test source file(s) and return test result.
private boolean getCompileResult(String className, boolean shouldCompile,
Iterable<? extends JavaFileObject> files, Iterable<String> options) {
DiagnosticCollector<JavaFileObject> diagnostics =
new DiagnosticCollector<JavaFileObject>();
Helper.compileCode(diagnostics, files, options);
// Test case pass or fail.
boolean ok = false;
String errMesg = "";
int numDiags = diagnostics.getDiagnostics().size();
if (numDiags == 0) {
if (shouldCompile) {
debugPrint("Test passed, compiled as expected.");
ok = true;
} else {
errMesg = "Test failed, compiled unexpectedly.";
ok = false;
}
} else {
if (shouldCompile) {
// did not compile.
List<Diagnostic<? extends JavaFileObject>> allDiagnostics = diagnostics.getDiagnostics();
if (allDiagnostics.stream().noneMatch(d -> d.getKind() == javax.tools.Diagnostic.Kind.ERROR)) {
ok = true;
} else {
errMesg = "Test failed, should have compiled successfully.";
ok = false;
}
} else {
// Error in compilation as expected.
String expectedErrKey = "compiler.err.invalid.repeatable."
+ "annotation.incompatible.target";
for (Diagnostic<?> d : diagnostics.getDiagnostics()) {
if ((d.getKind() == Diagnostic.Kind.ERROR)
&& d.getCode().contains(expectedErrKey)) {
// Error message as expected.
debugPrint("Error message as expected.");
ok = true;
break;
} else {
// error message is incorrect.
ok = false;
}
}
if (!ok) {
errMesg = "Incorrect error received when compiling "
+ className + ", expected: " + expectedErrKey;
}
}
}
if (!ok) {
error(errMesg);
for (Diagnostic<?> d : diagnostics.getDiagnostics()) {
System.out.println(" Diags: " + d);
}
}
return ok;
}
private Set<ElementType> less(Set<ElementType> base, ElementType... sub) {
Set<ElementType> res = EnumSet.noneOf(ElementType.class);
res.addAll(base);
for (ElementType t : sub) {
res.remove(t);
}
return res;
}
private Set<ElementType> plus(Set<ElementType> base, ElementType... add) {
Set<ElementType> res = EnumSet.noneOf(ElementType.class);
res.addAll(base);
for (ElementType t : add) {
res.add(t);
}
return res;
}
// Iterate target set and add "ElementType." in front of every target type.
private List<String> convertToString(Set<ElementType> annoTarget) {
if (annoTarget == null) {
return null;
}
List<String> annoTargets = new ArrayList<String>();
for (ElementType e : annoTarget) {
annoTargets.add("ElementType." + e.name());
}
return annoTargets;
}
private void debugPrint(String string) {
if (DEBUG) {
System.out.println(string);
}
}
private void error(String msg) {
System.out.println("ERROR: " + msg);
errors++;
}
}

View file

@ -0,0 +1,39 @@
/*
* Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package expectedFiles;
import java.lang.annotation.Annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface ExpectedBase {
Class<? extends Annotation> value() default Annotation.class;
String getAnnotationVal() default "";
String[] getAnnotationsVals() default {};
String[] getDeclAnnosVals() default {};
// JDK8 methods
String getDeclAnnoVal() default "";
String[] getAnnosArgs() default{};
String[] getDeclAnnosArgs() default {};
}

View file

@ -0,0 +1,39 @@
/*
* Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package expectedFiles;
import java.lang.annotation.Annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface ExpectedContainer {
Class<? extends Annotation> value() default Annotation.class;
String getAnnotationVal() default "";
String[] getAnnotationsVals() default {};
String[] getDeclAnnosVals() default {};
// JDK8 methods
String getDeclAnnoVal() default "";
String[] getAnnosArgs() default{};
String[] getDeclAnnosArgs() default {};
}