Java Code Examples for javax.tools.Diagnostic#getMessage()

The following examples show how to use javax.tools.Diagnostic#getMessage() . 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-8-source with GNU General Public License v2.0 6 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: JavapTaskCtorFailWithNPE.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
private void run() {
    File classToCheck = new File(System.getProperty("test.classes"),
        getClass().getSimpleName() + ".class");

    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, null,
            Arrays.asList(classToCheck.getPath()));
    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 AssertionError(d.getMessage(Locale.ENGLISH));
    }
    String lineSep = System.getProperty("line.separator");
    String out = sw.toString().replace(lineSep, "\n");
    if (!out.equals(expOutput)) {
        throw new AssertionError("The output is not equal to the one expected");
    }
}
 
Example 3
Source File: T7190862.java    From jdk8u60 with GNU General Public License v2.0 6 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 4
Source File: LocationSuppressRule.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public String createMessage(CompilationInfo info, Diagnostic d, int offset, TreePath treePath, ErrorRule.Data data) {
    String msg = d.getMessage(null);
    Matcher m = LOCATION_LINE.matcher(msg);
    if (!m.find()) {
        return null;
    }
    String location = m.group(1);
    int idx = location.indexOf("$JShell$"); // NOI18N
    if (idx == -1) {
        idx = location.indexOf("$JSHELL$"); // NOI18N
        if (idx == -1) {
            return null;
        }
    }
    String[] components = location.substring(idx).split("\\."); // NOI18N
    String last = components[components.length - 1];
    if (last.startsWith("$JShell$") || last.startsWith("$JSHELL$")) { // NOI18N
        // leave out the location at all
        return msg.substring(0, m.start(0));
    } else {
        return msg.substring(0, m.start(0)) + Bundle.Format_Location(last) + 
                msg.substring(m.end(0));
    }
}
 
Example 5
Source File: CompilerHelper.java    From avro-util with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private static String summarize(Diagnostic<? extends JavaFileObject> diagnostic) {
    StringBuilder sb = new StringBuilder();
    sb.append(diagnostic.getKind()).append(": ");
    JavaFileObject sourceObject = diagnostic.getSource();
    if (sourceObject != null) {
        sb.append("file ").append(sourceObject.toString()).append(" ");
    }
    String message = diagnostic.getMessage(Locale.ROOT);
    if (message != null && !message.isEmpty()) {
        sb.append(message).append(" ");
    }
    long line = diagnostic.getLineNumber();
    long column = diagnostic.getColumnNumber();
    if (line != -1 || column != -1) {
        sb.append("at line ").append(line).append(" column ").append(column);
    }
    return sb.toString().trim();
}
 
Example 6
Source File: HTMLViewProcessorTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Test public void needActionId() throws Exception {
    String html = "<html><body>"
            + "</body></html>";
    String code = "package x.y.z;\n"
            + "import org.netbeans.api.htmlui.OpenHTMLRegistration;\n"
            + "public class X {\n"
            + "  @OpenHTMLRegistration(url=\"empty.html\", displayName=\"X\")\n"
            + "  public static void someMethod() {\n"
            + "  }\n"
            + "}\n";

    Compile c = Compile.create("empty.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("ActionID")) {
            ok = true;
        }
        msgs.append("\n").append(msg);
    }
    if (!ok) {
        fail("Should contain warning about ActionID:" + msgs);
    }
}
 
Example 7
Source File: JavapTaskCtorFailWithNPE.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
private void run() {
    File classToCheck = new File(System.getProperty("test.classes"),
        getClass().getSimpleName() + ".class");

    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, null,
            Arrays.asList(classToCheck.getPath()));
    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 AssertionError(d.getMessage(Locale.ENGLISH));
    }
    String lineSep = System.getProperty("line.separator");
    String out = sw.toString().replace(lineSep, "\n");
    if (!out.equals(expOutput)) {
        throw new AssertionError("The output is not equal to the one expected");
    }
}
 
Example 8
Source File: ErrorUtil.java    From j2objc with Apache License 2.0 6 votes vote down vote up
@Override
public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
  JavaFileObject sourceFile = diagnostic.getSource();
  String text = diagnostic.getMessage(null);
  String msg = diagnostic.getPosition() != Diagnostic.NOPOS
      ? String.format("%s:%s: %s", sourceFile.getName(), diagnostic.getLineNumber(), text)
      : String.format("%s: %s", sourceFile.getName(), text);
  switch (diagnostic.getKind()) {
    case ERROR:
      error(msg);
      break;
    case WARNING:
      warning(msg);
      break;
    default:
      Logger.getGlobal().info(msg);
  }
}
 
Example 9
Source File: Compile.java    From netbeans with Apache License 2.0 5 votes vote down vote up
void assertError(String expMsg) {
    StringBuilder sb = new StringBuilder();
    sb.append("Can't find ").append(expMsg).append(" among:");
    for (Diagnostic<? extends JavaFileObject> e : errors) {
        String msg = e.getMessage(Locale.US);
        if (msg.contains(expMsg)) {
            return;
        }
        sb.append("\n");
        sb.append(msg);
    }
    fail(sb.toString());
}
 
Example 10
Source File: CapturingDiagnosticListener.java    From EasyMPermission with MIT License 5 votes vote down vote up
@Override public void report(Diagnostic<? extends JavaFileObject> d) {
	String msg = d.getMessage(Locale.ENGLISH);
	Matcher m = Pattern.compile(
			"^" + Pattern.quote(file.getAbsolutePath()) +
			"\\s*:\\s*\\d+\\s*:\\s*(?:warning:\\s*)?(.*)$", Pattern.DOTALL).matcher(msg);
	if (m.matches()) msg = m.group(1);
	messages.add(new CompilerMessage(d.getLineNumber(), d.getStartPosition(), d.getKind() == Kind.ERROR, msg));
}
 
Example 11
Source File: PartialReparseTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public DiagnosticDescription(Diagnostic diag) {
    this.code = diag.getCode();
    this.message = diag.getMessage(Locale.ROOT);
    this.column = diag.getColumnNumber();
    this.endPos = diag.getEndPosition();
    this.kind = diag.getKind();
    this.line = diag.getLineNumber();
    this.pos = diag.getPosition();
    this.source = diag.getSource();
    this.startPos = diag.getStartPosition();
}
 
Example 12
Source File: DslValidationTest.java    From dsl-json with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void fieldsAreRecognized() {
	List<Diagnostic<? extends JavaFileObject>> diagnostics = compileTestCase(ValidType.class);
	Diagnostic note = diagnostics.get(diagnostics.size() - 1);
	Assert.assertEquals(Diagnostic.Kind.NOTE, note.getKind());
	String dsl = note.getMessage(Locale.ENGLISH);
	Assert.assertTrue(dsl.contains("string? simpleField {  simple Java access;"));
	Assert.assertTrue(dsl.contains("List<string?>? listField {  simple Java access;"));
}
 
Example 13
Source File: HTMLViewProcessorTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Test public void methodIsNotStatic() 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"
            + "public final class X {\n"
            + "  @ActionID(category=\"test\", id=\"test.id.at.x\")\n"
            + "  @OpenHTMLRegistration(url=\"page.html\", displayName=\"X\")\n"
            + "  public void someMethod() {\n"
            + "  }\n"
            + "}\n";

    Compile c = Compile.create("page.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("needs to be static")) {
            ok = true;
        }
        msgs.append("\n").append(msg);
    }
    if (!ok) {
        fail("Should contain warning about static:" + msgs);
    }
}
 
Example 14
Source File: DslValidationTest.java    From dsl-json with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void supportsInterfacesWithConfiguration() {
	List<Diagnostic<? extends JavaFileObject>> diagnostics = compileTestCase(UsesInterfaceWithConfiguration.class, Implements1Type.class, InterfaceTypeWithoutSignature.class);
	Diagnostic note = diagnostics.get(diagnostics.size() - 1);
	Assert.assertEquals(Diagnostic.Kind.NOTE, note.getKind());
	String dsl = note.getMessage(Locale.ENGLISH);
	Assert.assertTrue(dsl.contains("? if1;"));
	Assert.assertTrue(dsl.contains("?>? if2 {  exclude serialization signature;  }"));
	Assert.assertTrue(dsl.contains("? if3 {  exclude serialization signature;  }"));
	Assert.assertTrue(dsl.contains("? if4 {  simple Java access;  }"));
	Assert.assertTrue(dsl.contains("int i;"));
}
 
Example 15
Source File: HintTestBase.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void ensureCompilable(FileObject file) throws IOException, AssertionError, IllegalArgumentException {
    CompilationInfo info = parse(file);

    assertNotNull(info);

    for (Diagnostic d : info.getDiagnostics()) {
        if (d.getKind() == Diagnostic.Kind.ERROR)
            throw new AssertionError(d.getLineNumber() + ":" + d.getColumnNumber() + " " + d.getMessage(null));
    }
}
 
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 mandatoryProperties() {
	List<Diagnostic<? extends JavaFileObject>> diagnostics = compileTestCase(RequiredProperty.class);
	Diagnostic note = diagnostics.get(diagnostics.size() - 1);
	Assert.assertEquals(Diagnostic.Kind.NOTE, note.getKind());
	String dsl = note.getMessage(Locale.ENGLISH);
	Assert.assertTrue(dsl.contains("string? field1 {  simple Java access;  mandatory;  }"));
	Assert.assertTrue(dsl.contains("string? field2 {  simple Java access;  mandatory;  }"));
	Assert.assertTrue(dsl.contains("string? field3 {  simple Java access;  }"));
	Assert.assertTrue(dsl.contains("string? field4 {  simple Java access;  }"));
}
 
Example 17
Source File: DslValidationTest.java    From dsl-json with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void checkAlias() {
	List<Diagnostic<? extends JavaFileObject>> diagnostics = compileTestCase(PropertyAlias.class);
	Diagnostic note = diagnostics.get(diagnostics.size() - 1);
	Assert.assertEquals(Diagnostic.Kind.NOTE, note.getKind());
	String dsl = note.getMessage(Locale.ENGLISH);
	Assert.assertTrue(dsl.contains("int num {  serialization name 'y';  }"));
	Assert.assertTrue(dsl.contains("string? prop {  serialization name 'x';  deserialization alias 'X';  deserialization alias 'old_prop';  }"));
	Assert.assertTrue(dsl.contains("external name Java 'com.dslplatform.json.models.PropertyAlias';"));
}
 
Example 18
Source File: RuntimeJavaCompiler.java    From spring-init with Apache License 2.0 4 votes vote down vote up
public CompilationResult compile(InputFileDescriptor[] sources,
		InputFileDescriptor[] resources, CompilationOptions compilationOptions,
		List<File> dependencies) {
	logger.debug("Compiling {} source{}", sources.length,
			sources.length == 1 ? "" : "s");
	DiagnosticCollector<JavaFileObject> diagnosticCollector = new DiagnosticCollector<JavaFileObject>();
	MemoryBasedJavaFileManager fileManager = new MemoryBasedJavaFileManager();
	fileManager.addResolvedDependencies(dependencies);
	List<JavaFileObject> compilationUnits = new ArrayList<>();
	for (InputFileDescriptor source : sources) {
		compilationUnits.add(InMemoryJavaFileObject
				.getSourceJavaFileObject(source.getClassName(), source.getContent()));
	}
	List<String> options = new ArrayList<>();
	options.add("-processorpath");
	options.add(new File("../processor/target/classes/").toString());
	options.add("-source");
	options.add("1.8");
	options.add("-processor");
	options.add("org.springframework.init.processor.SlimConfigurationProcessor");
	CompilationTask task = compiler.getTask(null, fileManager, diagnosticCollector,
			options, null, compilationUnits);
	boolean success = task.call();
	CompilationResult compilationResult = new CompilationResult(success);
	compilationResult.setDependencies(new ArrayList<>(
			fileManager.getResolvedAdditionalDependencies().values()));
	compilationResult.setInputResources(resources);
	// If successful there may be no errors but there might be info/warnings
	for (Diagnostic<? extends JavaFileObject> diagnostic : diagnosticCollector
			.getDiagnostics()) {
		CompilationMessage.Kind kind = (diagnostic.getKind() == Kind.ERROR
				? CompilationMessage.Kind.ERROR
				: CompilationMessage.Kind.OTHER);
		String sourceCode = null;
		try {
			sourceCode = (String) diagnostic.getSource().getCharContent(true);
		}
		catch (IOException ioe) {
			// Unexpected, but leave sourceCode null to indicate it was not
			// retrievable
		}
		catch (NullPointerException npe) {
			// TODO: should we skip warning diagnostics in the loop altogether?
		}
		int startPosition = (int) diagnostic.getPosition();
		if (startPosition == Diagnostic.NOPOS) {
			startPosition = (int) diagnostic.getStartPosition();
		}
		CompilationMessage compilationMessage = new CompilationMessage(kind,
				diagnostic.getMessage(null), sourceCode, startPosition,
				(int) diagnostic.getEndPosition());
		compilationResult.recordCompilationMessage(compilationMessage);
	}
	compilationResult.setGeneratedFiles(fileManager.getOutputFiles());
	return compilationResult;
}
 
Example 19
Source File: T7142086.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
    if (diagnostic.getKind() == Diagnostic.Kind.ERROR) {
        throw new AssertionError("unexpected diagnostic: " + diagnostic.getMessage(Locale.getDefault()));
    }
}
 
Example 20
Source File: T7142086.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
    if (diagnostic.getKind() == Diagnostic.Kind.ERROR) {
        throw new AssertionError("unexpected diagnostic: " + diagnostic.getMessage(Locale.getDefault()));
    }
}