javax.tools.Diagnostic Java Examples

The following examples show how to use javax.tools.Diagnostic. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: T7190862.java    From openjdk-jdk8u with GNU General Public License v2.0 7 votes vote down vote up
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();

}
 
Example #2
Source File: RpcServiceProcessor.java    From fastjgame with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #3
Source File: BetaCheckerTest.java    From guava-beta-checker with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #4
Source File: JavaSourcesSubjectFactoryTest.java    From compile-testing with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #5
Source File: RouteProcessor.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
@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");
}
 
Example #6
Source File: Extern.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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;
    }
}
 
Example #7
Source File: FindLocalUsagesQuery.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #8
Source File: BuckModuleVisitor.java    From buck with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #9
Source File: JavacParserTest.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
@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);
}
 
Example #10
Source File: JavaSourcesSubjectFactoryTest.java    From compile-testing with Apache License 2.0 5 votes vote down vote up
@Test
public void failsToCompile_wrongWarningCount() {
  expectFailure
      .whenTesting()
      .about(javaSource())
      .that(HELLO_WORLD_BROKEN)
      .processedWith(new DiagnosticMessage.Processor(Diagnostic.Kind.WARNING))
      .failsToCompile()
      .withWarningCount(42);
  AssertionError expected = expectFailure.getFailure();
  assertThat(expected.getMessage())
      .contains("Expected 42 warnings, but found the following 2 warnings:\n");
}
 
Example #11
Source File: HTMLViewProcessorTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@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);
    }
}
 
Example #12
Source File: FormattingError.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
@Override
public FormatterDiagnostic apply(Diagnostic<?> input) {
  return FormatterDiagnostic.create(
      (int) input.getLineNumber(),
      (int) input.getColumnNumber(),
      input.getMessage(ENGLISH));
}
 
Example #13
Source File: Util.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
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;
        }
    };
}
 
Example #14
Source File: ErrorHintsTestBase.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private String diagnosticsToString(Iterable<? extends Diagnostic> diagnostics) {
    StringBuilder result = new StringBuilder();
    
    for (Diagnostic<?> d : diagnostics) {
        result.append(d.getCode()).append(":").append(d.getMessage(null)).append("\n");
    }
    
    return result.toString();
}
 
Example #15
Source File: Example.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
private JCDiagnostic unwrap(Diagnostic<? extends JavaFileObject> diagnostic) {
    if (diagnostic instanceof JCDiagnostic)
        return (JCDiagnostic) diagnostic;
    if (diagnostic instanceof ClientCodeWrapper.DiagnosticSourceUnwrapper)
        return ((ClientCodeWrapper.DiagnosticSourceUnwrapper)diagnostic).d;
    throw new IllegalArgumentException();
}
 
Example #16
Source File: DslValidationTest.java    From dsl-json with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@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"));
}
 
Example #17
Source File: MvpCompiler.java    From Moxy with MIT License 5 votes vote down vote up
private List<String> getAdditionalMoxyReflectorPackages(RoundEnvironment roundEnv) {
	List<String> result = new ArrayList<>();

	for (Element element : roundEnv.getElementsAnnotatedWith(RegisterMoxyReflectorPackages.class)) {
		if (element.getKind() != ElementKind.CLASS) {
			getMessager().printMessage(Diagnostic.Kind.ERROR, element + " must be " + ElementKind.CLASS.name() + ", or not mark it as @" + RegisterMoxyReflectorPackages.class.getSimpleName());
		}

		String[] packages = element.getAnnotation(RegisterMoxyReflectorPackages.class).value();

		Collections.addAll(result, packages);
	}

	return result;
}
 
Example #18
Source File: ABTestProcessor.java    From abtestgen with Apache License 2.0 5 votes vote down vote up
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!");
    }
  }
}
 
Example #19
Source File: Hacks.java    From netbeans with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #20
Source File: PluginChecker.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #21
Source File: Utilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static JCExpression parseExpression(Context context, CharSequence expr, boolean onlyFullInput, SourcePositions[] pos, final List<Diagnostic<? extends JavaFileObject>> errors) {
    if (expr == null || (pos != null && pos.length != 1))
        throw new IllegalArgumentException();
    JavaCompiler compiler = JavaCompiler.instance(context);
    JavaFileObject prev = compiler.log.useSource(new DummyJFO());
    Log.DiagnosticHandler discardHandler = new Log.DiscardDiagnosticHandler(compiler.log) {
        @Override
        public void report(JCDiagnostic diag) {
            errors.add(diag);
        }            
    };
    try {
        CharBuffer buf = CharBuffer.wrap((expr+"\u0000").toCharArray(), 0, expr.length());
        ParserFactory factory = ParserFactory.instance(context);
        ScannerFactory scannerFactory = ScannerFactory.instance(context);
        Names names = Names.instance(context);
        Scanner scanner = scannerFactory.newScanner(buf, false);
        Parser parser = newParser(context, (NBParserFactory) factory, scanner, false, false, CancelService.instance(context), names);
        if (parser instanceof JavacParser) {
            if (pos != null)
                pos[0] = new ParserSourcePositions((JavacParser)parser);
            JCExpression result = parser.parseExpression();

            if (!onlyFullInput || scanner.token().kind == TokenKind.EOF) {
                return result;
            }
        }
        return null;
    } finally {
        compiler.log.useSource(prev);
        compiler.log.popDiagnosticHandler(discardHandler);
    }
}
 
Example #22
Source File: Messages.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
void report(PrintWriter out) {
    if (codeCounts == null) {
        return;
    }
    out.println("By group...");
    Table groupTable = new Table();
    for (Messages.Group g : Messages.Group.values()) {
        groupTable.put(g.optName(), groupCounts[g.ordinal()]);
    }
    groupTable.print(out);
    out.println();
    out.println("By diagnostic kind...");
    Table dkindTable = new Table();
    for (Diagnostic.Kind k : Diagnostic.Kind.values()) {
        dkindTable.put(k.toString().toLowerCase(), dkindCounts[k.ordinal()]);
    }
    dkindTable.print(out);
    out.println();
    out.println("By message kind...");
    Table codeTable = new Table();
    for (Map.Entry<String, Integer> e : codeCounts.entrySet()) {
        String code = e.getKey();
        String msg;
        try {
            msg = code.equals(NO_CODE) ? "OTHER" : bundle.getString(code);
        } catch (MissingResourceException ex) {
            msg = code;
        }
        codeTable.put(msg, e.getValue());
    }
    codeTable.print(out);
}
 
Example #23
Source File: OptionsProcessingStep.java    From paperparcel with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example #24
Source File: T7042566.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
    if (diagnostic.getKind() == Diagnostic.Kind.ERROR) {
        errDiags = errDiags
                .append(diagnostic.getMessage(Locale.getDefault()));
        errorFound = true;
    }
}
 
Example #25
Source File: Warn4.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
    if (diagnostic.getKind() == Diagnostic.Kind.MANDATORY_WARNING ||
            diagnostic.getKind() == Diagnostic.Kind.WARNING) {
        if (diagnostic.getCode().contains(Warning.VARARGS.key)) {
            warnings.add(Warning.VARARGS);
        } else if(diagnostic.getCode().contains(Warning.UNCHECKED.key)) {
            warnings.add(Warning.UNCHECKED);
        }
    }
}
 
Example #26
Source File: Messages.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
protected void report(Group group, Diagnostic.Kind dkind, Tree tree, String code, Object... args) {
    if (options.isEnabled(group, env.currAccess)) {
        String msg = localize(code, args);
        env.trees.printMessage(dkind, msg, tree, env.currPath.getCompilationUnit());

        stats.record(group, dkind, code);
    }
}
 
Example #27
Source File: TypeSimplifierTest.java    From RetroFacebook with Apache License 2.0 5 votes vote down vote up
private void runTests() {
  for (Method method : getClass().getMethods()) {
    if (method.getName().startsWith("test")) {
      try {
        method.invoke(this);
      } catch (Exception e) {
        Throwable cause = (e instanceof InvocationTargetException) ? e.getCause() : e;
        StringWriter stringWriter = new StringWriter();
        cause.printStackTrace(new PrintWriter(stringWriter));
        processingEnv.getMessager().printMessage(
            Diagnostic.Kind.ERROR, stringWriter.toString());
      }
    }
  }
}
 
Example #28
Source File: TemplateModel.java    From manifold with Apache License 2.0 5 votes vote down vote up
void report( DiagnosticListener errorHandler )
{
  if( _issues.isEmpty() || errorHandler == null )
  {
    return;
  }

  JavaFileObject file = new SourceJavaFileObject( getFile().toURI() );
  for( IIssue issue: _issues.getIssues() )
  {
    Diagnostic.Kind kind = issue.getKind() == IIssue.Kind.Error ? Diagnostic.Kind.ERROR : Diagnostic.Kind.WARNING;
    errorHandler.report( new JavacDiagnostic( file, kind, issue.getStartOffset(), issue.getLine(), issue.getColumn(), issue.getMessage() ) );
  }
}
 
Example #29
Source File: Visitor.java    From helidon-build-tools with Apache License 2.0 5 votes vote down vote up
private boolean checkOptionDescription(String description, VariableElement var) {
    if (description.isEmpty()) {
        env.getMessager().printMessage(Diagnostic.Kind.ERROR, "description cannot be empty", var);
        return false;
    }
    return true;
}
 
Example #30
Source File: PluggableProcessor.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
private void generateServiceFiles(Filer filer)
{
    for(String serviceName : factoryImplementations.keySet())
    {
        processingEnv.getMessager()
                .printMessage(Diagnostic.Kind.NOTE, "Generating service file for " + serviceName);

        String relativeName = "META-INF/services/" + serviceName;
        loadExistingServicesFile(filer, serviceName);
        try
        {
            FileObject serviceFile = filer.createResource(StandardLocation.CLASS_OUTPUT, "", relativeName);
            try(PrintWriter pw = new PrintWriter(new OutputStreamWriter(serviceFile.openOutputStream(), "UTF-8")))
            {
                for (String headerLine : License.LICENSE)
                {
                    pw.println("#" + headerLine);
                }
                pw.println("#");
                pw.println("# Note: Parts of this file are auto-generated from annotations.");
                pw.println("#");
                for (String implementation : factoryImplementations.get(serviceName))
                {
                    pw.println(implementation);
                }
            }
        }
        catch (IOException e)
        {
            processingEnv.getMessager()
                    .printMessage(Diagnostic.Kind.ERROR,
                                  "Failed to write services file: "
                                  + relativeName
                                  + " - "
                                  + e.getLocalizedMessage()
                                 );
        }
    }
}