下面列出了javax.annotation.processing.AbstractProcessor#javax.tools.Diagnostic 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
protected boolean doProcess(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
// 该注解只有类才可以使用
@SuppressWarnings("unchecked")
Set<TypeElement> typeElementSet = (Set<TypeElement>) roundEnv.getElementsAnnotatedWith(rpcServiceElement);
for (TypeElement typeElement : typeElementSet) {
try {
checkBase(typeElement);
genProxyClass(typeElement);
} catch (Throwable e) {
messager.printMessage(Diagnostic.Kind.ERROR, AutoUtils.getStackTrace(e), typeElement);
}
}
return true;
}
private String javap(List<String> args, List<String> classes) {
DiagnosticCollector<JavaFileObject> dc = new DiagnosticCollector<JavaFileObject>();
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
JavaFileManager fm = JavapFileManager.create(dc, pw);
JavapTask t = new JavapTask(pw, fm, dc, args, classes);
if (t.run() != 0)
throw new Error("javap failed unexpectedly");
List<Diagnostic<? extends JavaFileObject>> diags = dc.getDiagnostics();
for (Diagnostic<? extends JavaFileObject> d: diags) {
if (d.getKind() == Diagnostic.Kind.ERROR)
throw new Error(d.getMessage(Locale.ENGLISH));
}
return sw.toString();
}
@Test
public void testAnnotatedClass_methodReference() {
List<Diagnostic<? extends JavaFileObject>> diagnostics = compiler.compile(
BETA, ANNOTATED_CLASS,
JavaFileObjects.forSourceLines("example.Test",
"package example;",
"",
"import static java.util.stream.Collectors.joining;",
"",
"import com.google.common.foo.AnnotatedClass;",
"import java.util.List;",
"",
"public class Test {",
" public static void foo(List<? extends AnnotatedClass> list) {", // error
" String s = list.stream()",
" .map(AnnotatedClass::instanceMethod)", // error
" .collect(joining(", "));",
" }",
"}")
);
compiler.assertErrorsOnLines("example/Test.java", diagnostics, 9, 11);
}
@Test
public void compilesWithoutError_noteNotInFile() {
JavaFileObject otherSource = JavaFileObjects.forResource("HelloWorld.java");
expectFailure
.whenTesting()
.about(javaSource())
.that(HELLO_WORLD)
.processedWith(new DiagnosticMessage.Processor(Diagnostic.Kind.NOTE))
.compilesWithoutError()
.withNoteContaining("this is a message")
.in(otherSource);
AssertionError expected = expectFailure.getFailure();
assertThat(expected.getMessage())
.contains(
String.format(
"Expected a note containing \"this is a message\" in %s", otherSource.getName()));
assertThat(expected.getMessage()).contains(HELLO_WORLD.getName());
}
@Override
public synchronized void init(ProcessingEnvironment processingEnvironment) {
super.init(processingEnvironment);
messager = processingEnvironment.getMessager();
types = processingEnvironment.getTypeUtils();
elementUtils = processingEnvironment.getElementUtils();
filer = processingEnvironment.getFiler();
moduleName = processingEnvironment.getOptions().get(Consts.MODULE_NAME);
if (moduleName == null) {
// Developer has not set ModuleName in build.gradle, stop compile
messager.printMessage(Diagnostic.Kind.ERROR, Consts.MODULE_NAME + " is null!!");
}
messager.printMessage(Diagnostic.Kind.NOTE, "Init process success");
}
/**
* Build the extern package list from given URL or the directory path.
* Flag error if the "-link" or "-linkoffline" option is already used.
*
* @param url URL or Directory path.
* @param pkglisturl This can be another URL for "package-list" or ordinary
* file.
* @param reporter The <code>DocErrorReporter</code> used to report errors.
* @param linkoffline True if -linkoffline is used and false if -link is used.
* @return true if successful, false otherwise
* @throws DocFileIOException if there is a problem reading a package list file
*/
public boolean link(String url, String pkglisturl, Reporter reporter, boolean linkoffline)
throws DocFileIOException {
this.linkoffline = linkoffline;
try {
url = adjustEndFileSeparator(url);
if (isUrl(pkglisturl)) {
readPackageListFromURL(url, toURL(adjustEndFileSeparator(pkglisturl)));
} else {
readPackageListFromFile(url, DocFile.createFileForInput(configuration, pkglisturl));
}
return true;
} catch (Fault f) {
reporter.print(Diagnostic.Kind.WARNING, f.getMessage());
return false;
}
}
@Override
public Void visitIdentifier(IdentifierTree tree, Void d) {
Element el = info.getTrees().getElement(getCurrentPath());
if (toFind.equals(el)) {
try {
long start = sp.getStartPosition(info.getCompilationUnit(), tree);
long end = sp.getEndPosition(info.getCompilationUnit(), tree);
if(start != Diagnostic.NOPOS) {
MutablePositionRegion region = createRegion(doc, (int) start, (int) end);
usages.add(region);
}
} catch (BadLocationException ex) {
Exceptions.printStackTrace(ex);
}
}
return super.visitIdentifier(tree, d);
}
@Override
public Void visitType(TypeElement type, TypeElement annotation) {
try {
visitTypeInternal(type, annotation);
} catch (Exception e) {
processingEnv
.getMessager()
.printMessage(
Diagnostic.Kind.ERROR,
"Cannot collect information about Buck modules: " + ThrowablesUtils.toString(e),
type);
hadError = true;
}
return null;
}
@Test
void testVariableInIfThen4() throws IOException {
String code = "package t; class Test { "+
"private static void t(String name) { " +
"if (name != null) interface X {} } }";
DiagnosticCollector<JavaFileObject> coll =
new DiagnosticCollector<JavaFileObject>();
JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, coll, null,
null, Arrays.asList(new MyFileObject(code)));
ct.parse();
List<String> codes = new LinkedList<String>();
for (Diagnostic<? extends JavaFileObject> d : coll.getDiagnostics()) {
codes.add(d.getCode());
}
assertEquals("testVariableInIfThen4",
Arrays.<String>asList("compiler.err.class.not.allowed"), codes);
}
private String getRequiredJavadoc(Element e) {
String docComment = processingEnv.getElementUtils().getDocComment(e);
if (docComment == null) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Unable to find javadoc for config item " + e, e);
return "";
}
// javax.lang.model keeps the leading space after the "*" so we need to remove it.
return REMOVE_LEADING_SPACE.matcher(docComment).replaceAll("").trim();
}
List<JCDiagnostic> subDiagnostics(Diagnostic<? extends JavaFileObject> diagnostic) {
JCDiagnostic diag = asJCDiagnostic(diagnostic);
if (diag instanceof JCDiagnostic.MultilineDiagnostic) {
return ((JCDiagnostic.MultilineDiagnostic)diag).getSubdiagnostics();
} else {
throw new AssertionError("Cannot extract subdiagnostics: " + diag.getClass().getName());
}
}
JCDiagnostic asJCDiagnostic(Diagnostic<? extends JavaFileObject> diagnostic) {
if (diagnostic instanceof JCDiagnostic) {
return (JCDiagnostic)diagnostic;
} else if (diagnostic instanceof DiagnosticSourceUnwrapper) {
return ((DiagnosticSourceUnwrapper)diagnostic).d;
} else {
throw new AssertionError("Cannot convert diagnostic to JCDiagnostic: " + diagnostic.getClass().getName());
}
}
private TypeMirror findFutureTypeArgument(ExecutableElement method) {
TypeMirror firstTypeParameter = AutoUtils.findFirstTypeParameter(method.getReturnType());
if (firstTypeParameter == null) {
messager.printMessage(Diagnostic.Kind.ERROR, "Future missing type parameter!", method);
return elementUtils.getTypeElement(Object.class.getCanonicalName()).asType();
} else {
return firstTypeParameter;
}
}
private static boolean logDiagnostic(Diagnostic<? extends JavaFileObject> d) {
Level logLevel = findLogLevel(d);
if (ERROR_LOG.isLoggable(logLevel)) {
ERROR_LOG.log(logLevel, d.getSource().toUri().toASCIIString() + ":" + d.getCode() + ":" + d.getLineNumber() + ":" + d.getMessage(null), new Exception());
}
return true;
}
@Test public void failIfHTMLPageDoesNotExist() throws Exception {
String html = "<html><body>"
+ "</body></html>";
String code = "package x.y.z;\n"
+ "import org.netbeans.api.htmlui.OpenHTMLRegistration;\n"
+ "import org.openide.awt.ActionID;\n"
+ "class X {\n"
+ " @ActionID(category=\"test\", id=\"test.id.at.x\")\n"
+ " @OpenHTMLRegistration(url=\"does-not-exist.html\", displayName=\"X\")\n"
+ " public static void someMethod() {\n"
+ " }\n"
+ "}\n";
Compile c = Compile.create("different.html", html, code);
assertFalse(c.getErrors().isEmpty(), "One error: " + c.getErrors());
boolean ok = false;
StringBuilder msgs = new StringBuilder();
for (Diagnostic<? extends JavaFileObject> e : c.getErrors()) {
String msg = e.getMessage(Locale.ENGLISH);
if (msg.contains("Cannot find resource")) {
ok = true;
}
msgs.append("\n").append(msg);
}
if (!ok) {
fail("Should contain warning about Cannot find resource:" + msgs);
}
}
private void deriveAdditionalSourcePath( List<String> inputFiles, Set<String> sourcePath )
{
outer:
for( String inputFile : inputFiles )
{
for( String sp : sourcePath )
{
if( inputFile.startsWith( sp + File.separatorChar ) )
{
continue outer;
}
}
String pkg = extractPackageName( inputFile );
if( pkg != null )
{
int iDot = inputFile.lastIndexOf( '.' );
String ext = iDot > 0 ? inputFile.substring( iDot ) : "";
String fqn = pkg + '.' + new File( inputFile ).getName();
fqn = fqn.substring( 0, fqn.length() - ext.length() );
String path = derivePath( fqn, inputFile );
sourcePath.add( path );
}
else
{
//noinspection unchecked
getIssueReporter().report( new JavacDiagnostic( null, Diagnostic.Kind.WARNING, 0, 0, 0, IssueMsg.MSG_COULD_NOT_FIND_TYPE_FOR_FILE.get( inputFile ) ) );
}
}
}
/**
* If the processor class is annotated with {@link
* SupportedSourceVersion}, return the source version in the
* annotation. If the class is not so annotated, {@link
* SourceVersion#RELEASE_6} is returned.
*
* @return the latest source version supported by this processor
*/
public SourceVersion getSupportedSourceVersion() {
SupportedSourceVersion ssv = this.getClass().getAnnotation(SupportedSourceVersion.class);
SourceVersion sv = null;
if (ssv == null) {
sv = SourceVersion.RELEASE_6;
if (isInitialized())
processingEnv.getMessager().printMessage(Diagnostic.Kind.WARNING,
"No SupportedSourceVersion annotation " +
"found on " + this.getClass().getName() +
", returning " + sv + ".");
} else
sv = ssv.value();
return sv;
}
private static void createPluginFactory(ProcessingEnvironment env, Element topLevelClass, List<GeneratedPlugin> plugins) {
PackageElement pkg = (PackageElement) topLevelClass.getEnclosingElement();
String genClassName = "PluginFactory_" + topLevelClass.getSimpleName();
try {
JavaFileObject factory = env.getFiler().createSourceFile(pkg.getQualifiedName() + "." + genClassName, topLevelClass);
try (PrintWriter out = new PrintWriter(factory.openWriter())) {
out.printf("// CheckStyle: stop header check\n");
out.printf("// CheckStyle: stop line length check\n");
out.printf("// GENERATED CONTENT - DO NOT EDIT\n");
out.printf("// GENERATORS: %s, %s\n", VerifierAnnotationProcessor.class.getName(), PluginGenerator.class.getName());
out.printf("package %s;\n", pkg.getQualifiedName());
out.printf("\n");
createImports(out, plugins);
out.printf("\n");
out.printf("@ServiceProvider(NodeIntrinsicPluginFactory.class)\n");
out.printf("public class %s implements NodeIntrinsicPluginFactory {\n", genClassName);
for (GeneratedPlugin plugin : plugins) {
out.printf("\n");
plugin.generate(env, out);
}
out.printf("\n");
createPluginFactoryMethod(out, plugins);
out.printf("}\n");
}
} catch (IOException e) {
env.getMessager().printMessage(Diagnostic.Kind.ERROR, e.getMessage());
}
}
public void createWarningMessage(String warningMessage) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
pw.println(warningMessage);
pw.close();
messager.printMessage(Diagnostic.Kind.WARNING,
sw.toString());
}
/**
* Returns true if a non-deferrable error was raised during annotation processing, i.e. an error
* reported by an annotation processor.
*
* <p>Errors reported by turbine (e.g. missing symbols) are non-fatal, since they may be fixed by
* code generated in later processing rounds.
*/
public boolean errorRaised() {
for (TurbineDiagnostic error : errors) {
if (error.kind().equals(ErrorKind.PROC) && error.severity().equals(Diagnostic.Kind.ERROR)) {
return true;
}
}
return false;
}
void performWildcardPositionsTest(final String code,
List<String> golden) throws IOException {
final List<Diagnostic<? extends JavaFileObject>> errors =
new LinkedList<Diagnostic<? extends JavaFileObject>>();
JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null,
new DiagnosticListener<JavaFileObject>() {
public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
errors.add(diagnostic);
}
}, null, null, Arrays.asList(new MyFileObject(code)));
final CompilationUnitTree cut = ct.parse().iterator().next();
final List<String> content = new LinkedList<String>();
final Trees trees = Trees.instance(ct);
new TreeScanner<Void, Void>() {
@Override
public Void scan(Tree node, Void p) {
if (node == null) {
return null;
}
long start = trees.getSourcePositions().getStartPosition(cut, node);
if (start == (-1)) {
return null; // synthetic tree
}
long end = trees.getSourcePositions().getEndPosition(cut, node);
String s = code.substring((int) start, (int) end);
content.add(s);
return super.scan(node, p);
}
}.scan(((MethodTree) ((ClassTree) cut.getTypeDecls().get(0)).getMembers().get(0)).getBody().getStatements().get(0), null);
assertEquals("performWildcardPositionsTest",golden.toString(),
content.toString());
}
@Override
boolean run(PrintWriter out, Set<String> keys, boolean raw, List<String> opts, List<File> files) {
if (out != null && keys != null)
throw new IllegalArgumentException();
if (verbose)
System.err.println("run_jsr199: " + opts + " " + files);
DiagnosticCollector<JavaFileObject> dc = null;
if (keys != null)
dc = new DiagnosticCollector<JavaFileObject>();
if (raw) {
List<String> newOpts = new ArrayList<String>();
newOpts.add("-XDrawDiagnostics");
newOpts.addAll(opts);
opts = newOpts;
}
JavaCompiler c = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fm = c.getStandardFileManager(dc, null, null);
if (fmOpts != null)
fm = new FileManager(fm, fmOpts);
Iterable<? extends JavaFileObject> fos = fm.getJavaFileObjectsFromFiles(files);
CompilationTask t = c.getTask(out, fm, dc, opts, null, fos);
Boolean ok = t.call();
if (keys != null) {
for (Diagnostic<? extends JavaFileObject> d: dc.getDiagnostics()) {
scanForKeys(unwrap(d), keys);
}
}
return ok;
}
@Override
public FormatterDiagnostic apply(Diagnostic<?> input) {
return FormatterDiagnostic.create(
(int) input.getLineNumber(),
(int) input.getColumnNumber(),
input.getMessage(ENGLISH));
}
@Test
public void testAnnotatedInterface_extending() {
List<Diagnostic<? extends JavaFileObject>> diagnostics = compiler.compile(
BETA, ANNOTATED_INTERFACE,
JavaFileObjects.forSourceLines("example.Test",
"package example;",
"",
"import com.google.common.foo.AnnotatedInterface;",
"",
"public interface Test extends AnnotatedInterface {", // error
"}")
);
compiler.assertErrorsOnLines("example/Test.java", diagnostics, 5);
}
private Diagnostic<JavaFileObject> createDiagnostic(
final Diagnostic.Kind kind, final String code, final Object... args) {
return new Diagnostic<JavaFileObject>() {
public String getCode() {
return code;
}
public long getColumnNumber() {
return Diagnostic.NOPOS;
}
public long getEndPosition() {
return Diagnostic.NOPOS;
}
public Kind getKind() {
return kind;
}
public long getLineNumber() {
return Diagnostic.NOPOS;
}
public String getMessage(Locale locale) {
if (code.length() == 0)
return (String) args[0];
return getText(code, args); // FIXME locale
}
public long getPosition() {
return Diagnostic.NOPOS;
}
public JavaFileObject getSource() {
return null;
}
public long getStartPosition() {
return Diagnostic.NOPOS;
}
};
}
@Test
public void onUnknownDefault() {
List<Diagnostic<? extends JavaFileObject>> diagnostics = compileTestCase(ValidCtor.class);
Diagnostic note = diagnostics.get(diagnostics.size() - 1);
Assert.assertEquals(Diagnostic.Kind.NOTE, note.getKind());
String dsl = note.getMessage(Locale.ENGLISH);
Assert.assertFalse(dsl.contains("JSON serialization"));
}
private void validateTestData(ViewTestData[] datas) {
int numberOfParams = datas[0].getValues().length;
for (ViewTestData data : datas) {
if (data.getValues().length != numberOfParams) {
messager.printMessage(Diagnostic.Kind.ERROR,
"Each element in a test must have the same number of values!");
}
if (data.getElementAttachedTo().getModifiers().contains(Modifier.PRIVATE)) {
messager.printMessage(Diagnostic.Kind.ERROR, "You can't annotate a private field!");
}
}
}
private static JCDiagnostic getJCDiagnostic(Diagnostic<?> d) {
if (d instanceof JCDiagnostic) {
return ((JCDiagnostic)d);
} else if (d instanceof RichDiagnostic && ((RichDiagnostic) d).getDelegate() instanceof JCDiagnostic) {
return (JCDiagnostic)((RichDiagnostic)d).getDelegate();
}
return null;
}
/**
* Processes @Require annotations and checks that Device meets requirements.
*
* {@inheritDoc}
*/
@Override
public boolean process(Set<? extends TypeElement> annotations,
RoundEnvironment roundEnv) {
for (Element el : roundEnv.getElementsAnnotatedWith(RequireContainer.class)) {
for (Require req : el.getAnnotationsByType(Require.class)) {
//for every Require annotation checks if device has module of required version.
Integer version = device.getSupportedModules().get(req.value());
if (version == null
|| version < req.minVersion()
|| version > req.maxVersion()) {
//if module is optional then show only warning not error
if (req.optional()) {
processingEnv.getMessager()
.printMessage(Diagnostic.Kind.WARNING,
"Plugin [" + el + "] requires " + req
+ "\n but device " + (version == null
? "doesn't have such module."
+ " This module is optional."
+ " So plugin will work but miss"
+ " some functionality"
: "has " + version
+ " version of that module"));
} else {
processingEnv.getMessager()
.printMessage(Diagnostic.Kind.ERROR,
"Plugin [" + el + "] requires " + req
+ "\n but device "
+ (version == null
? "doesn't have such module"
: "has " + version
+ " version of that module"));
}
}
}
return true;
}
return false;
}
@Override public Set<Element> process(
SetMultimap<Class<? extends Annotation>, Element> elementsByAnnotation) {
Set<Element> processorConfigElements = elementsByAnnotation.get(ProcessorConfig.class);
if (optionsHolder.isOptionsApplied() || processorConfigElements.size() > 1) {
messager.printMessage(Diagnostic.Kind.ERROR, ErrorMessages.MULTIPLE_PROCESSOR_CONFIGS);
} else if (processorConfigElements.size() == 1) {
Element configElement = processorConfigElements.iterator().next();
AnnotationMirror config = getAnnotationMirror(configElement, ProcessorConfig.class).get();
optionsHolder.setOptions(Utils.getModuleOptions(config));
}
return ImmutableSet.of();
}