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

The following examples show how to use javax.tools.Diagnostic#getCode() . 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: DremioDiagnosticListener.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@Override
public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
  if (diagnostic.getKind() == javax.tools.Diagnostic.Kind.ERROR) {
    String message = diagnostic.toString() + " (" + diagnostic.getCode() + ")";
    logger.error(message);
    Location loc = new Location( //
        diagnostic.getSource().toString(), //
        (short) diagnostic.getLineNumber(), //
        (short) diagnostic.getColumnNumber() //
    );
    // Wrap the exception in a RuntimeException, because "report()"
    // does not declare checked exceptions.
    throw new RuntimeException(new CompileException(message, loc));
  } else if (logger.isTraceEnabled()) {
    logger.trace(diagnostic.toString() + " (" + diagnostic.getCode() + ")");
  }
}
 
Example 2
Source File: DrillDiagnosticListener.java    From Bats with Apache License 2.0 6 votes vote down vote up
@Override
public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
  if (diagnostic.getKind() == javax.tools.Diagnostic.Kind.ERROR) {
    String message = diagnostic.toString() + " (" + diagnostic.getCode() + ")";
    logger.error(message);
    Location loc = new Location( //
        diagnostic.getSource().toString(), //
        (short) diagnostic.getLineNumber(), //
        (short) diagnostic.getColumnNumber() //
    );
    // Wrap the exception in a RuntimeException, because "report()"
    // does not declare checked exceptions.
    throw new RuntimeException(new CompileException(message, loc));
  } else if (logger.isTraceEnabled()) {
    logger.trace(diagnostic.toString() + " (" + diagnostic.getCode() + ")");
  }
}
 
Example 3
Source File: JavacParser.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private String diagnosticToString(Diagnostic<JavaFileObject> d) {
    return d.getSource().toUri().toString() + ":" +
           d.getKind() + ":" +
           d.getStartPosition() + ":" +
           d.getPosition() + ":" +
           d.getEndPosition() + ":" +
           d.getLineNumber() + ":" +
           d.getColumnNumber() + ":" +
           d.getCode() + ":" +
           d.getMessage(null);
}
 
Example 4
Source File: EndPositions.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String... args) throws IOException {
    class MyFileObject extends SimpleJavaFileObject {
        MyFileObject() {
            super(URI.create("myfo:///Test.java"), SOURCE);
        }
        @Override
        public String getCharContent(boolean ignoreEncodingErrors) {
            //      0         1         2         3
            //      012345678901234567890123456789012345
            return "class Test { String s = 1234; }";
        }
    }
    JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
    List<JavaFileObject> compilationUnits =
            Collections.<JavaFileObject>singletonList(new MyFileObject());
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
    List<String> options = Arrays.asList("-processor", EndPositions.class.getCanonicalName());
    JavacTask task = (JavacTask)javac.getTask(null, null, diagnostics, options, null, compilationUnits);
    boolean valid = task.call();
    if (valid)
        throw new AssertionError("Expected one error, but found none.");

    List<Diagnostic<? extends JavaFileObject>> errors = diagnostics.getDiagnostics();
    if (errors.size() != 1)
        throw new AssertionError("Expected one error only, but found " + errors.size() + "; errors: " + errors);

    Diagnostic<?> error = errors.get(0);
    if (error.getStartPosition() >= error.getEndPosition())
        throw new AssertionError("Expected start to be less than end position: start [" +
                error.getStartPosition() + "], end [" + error.getEndPosition() +"]" +
                "; diagnostics code: " + error.getCode());

    System.out.println("All is good!");
}
 
Example 5
Source File: TaskFactory.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Diag diag(final Diagnostic<? extends JavaFileObject> d) {
    return new Diag() {

        @Override
        public boolean isError() {
            return d.getKind() == Diagnostic.Kind.ERROR;
        }

        @Override
        public long getPosition() {
            return d.getPosition();
        }

        @Override
        public long getStartPosition() {
            return d.getStartPosition();
        }

        @Override
        public long getEndPosition() {
            return d.getEndPosition();
        }

        @Override
        public String getCode() {
            return d.getCode();
        }

        @Override
        public String getMessage(Locale locale) {
            return expunge(d.getMessage(locale));
        }
    };
}
 
Example 6
Source File: Formatter.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean apply(Diagnostic<?> input) {
    if (input.getKind() != Diagnostic.Kind.ERROR) {
        return false;
    }
    switch (input.getCode()) {
        case "compiler.err.invalid.meth.decl.ret.type.req":
            // accept constructor-like method declarations that don't match the name of their
            // enclosing class
            return false;
        default:
            break;
    }
    return true;
}
 
Example 7
Source File: EndPositions.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String... args) throws IOException {
    class MyFileObject extends SimpleJavaFileObject {
        MyFileObject() {
            super(URI.create("myfo:///Test.java"), SOURCE);
        }
        @Override
        public String getCharContent(boolean ignoreEncodingErrors) {
            //      0         1         2         3
            //      012345678901234567890123456789012345
            return "class Test { String s = 1234; }";
        }
    }
    JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
    List<JavaFileObject> compilationUnits =
            Collections.<JavaFileObject>singletonList(new MyFileObject());
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
    List<String> options = Arrays.asList("-processor", EndPositions.class.getCanonicalName());
    JavacTask task = (JavacTask)javac.getTask(null, null, diagnostics, options, null, compilationUnits);
    boolean valid = task.call();
    if (valid)
        throw new AssertionError("Expected one error, but found none.");

    List<Diagnostic<? extends JavaFileObject>> errors = diagnostics.getDiagnostics();
    if (errors.size() != 1)
        throw new AssertionError("Expected one error only, but found " + errors.size() + "; errors: " + errors);

    Diagnostic<?> error = errors.get(0);
    if (error.getStartPosition() >= error.getEndPosition())
        throw new AssertionError("Expected start to be less than end position: start [" +
                error.getStartPosition() + "], end [" + error.getEndPosition() +"]" +
                "; diagnostics code: " + error.getCode());

    System.out.println("All is good!");
}
 
Example 8
Source File: EndPositions.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String... args) throws IOException {
    class MyFileObject extends SimpleJavaFileObject {
        MyFileObject() {
            super(URI.create("myfo:///Test.java"), SOURCE);
        }
        @Override
        public String getCharContent(boolean ignoreEncodingErrors) {
            //      0         1         2         3
            //      012345678901234567890123456789012345
            return "class Test { String s = 1234; }";
        }
    }
    JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
    List<JavaFileObject> compilationUnits =
            Collections.<JavaFileObject>singletonList(new MyFileObject());
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
    List<String> options = Arrays.asList("-processor", EndPositions.class.getCanonicalName());
    JavacTask task = (JavacTask)javac.getTask(null, null, diagnostics, options, null, compilationUnits);
    boolean valid = task.call();
    if (valid)
        throw new AssertionError("Expected one error, but found none.");

    List<Diagnostic<? extends JavaFileObject>> errors = diagnostics.getDiagnostics();
    if (errors.size() != 1)
        throw new AssertionError("Expected one error only, but found " + errors.size() + "; errors: " + errors);

    Diagnostic<?> error = errors.get(0);
    if (error.getStartPosition() >= error.getEndPosition())
        throw new AssertionError("Expected start to be less than end position: start [" +
                error.getStartPosition() + "], end [" + error.getEndPosition() +"]" +
                "; diagnostics code: " + error.getCode());

    System.out.println("All is good!");
}
 
Example 9
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 10
Source File: StringLiteralTemplateProcessor.java    From manifold with Apache License 2.0 5 votes vote down vote up
private String debaseMsgCode( Diagnostic<? extends JavaFileObject> diag )
{
  // Log#error() will prepend "compiler.err", so we must remove it to avoid double-basing the message
  String code = diag.getCode();
  if( code != null && code.startsWith( "compiler.err" ) )
  {
    code = code.substring( "compiler.err".length() + 1 );
  }
  return code;
}
 
Example 11
Source File: TestLambdaToMethodStats.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
    try {
        if (diagnostic.getKind() == Diagnostic.Kind.NOTE) {
            switch (diagnostic.getCode()) {
                case "compiler.note.lambda.stat":
                    lambda = true;
                    break;
                case "compiler.note.mref.stat":
                    lambda = false;
                    bridge = false;
                    break;
                case "compiler.note.mref.stat.1":
                    lambda = false;
                    bridge = true;
                    break;
                default:
                    throw new AssertionError("unexpected note: " + diagnostic.getCode());
            }
            ClientCodeWrapper.DiagnosticSourceUnwrapper dsu =
                (ClientCodeWrapper.DiagnosticSourceUnwrapper)diagnostic;
            altMetafactory = (Boolean)dsu.d.getArgs()[0];
        }
    } catch (RuntimeException t) {
        t.printStackTrace();
        throw t;
    }
}
 
Example 12
Source File: Formatter.java    From java-n-IDE-for-Android with Apache License 2.0 5 votes vote down vote up
@Override
public boolean apply(Diagnostic<?> input) {
    if (input.getKind() != Diagnostic.Kind.ERROR) {
        return false;
    }
    switch (input.getCode()) {
        case "compiler.err.invalid.meth.decl.ret.type.req":
            // accept constructor-like method declarations that don't match the name of their
            // enclosing class
            return false;
        default:
            break;
    }
    return true;
}
 
Example 13
Source File: DiagnosticAdapter.java    From java-n-IDE-for-Android with Apache License 2.0 5 votes vote down vote up
@Override
public void onBindViewHolder(ErrorHolder holder, int position) {
    final Diagnostic diagnostic = mDiagnostics.get(position);
    holder.line.setText(SpanUtil.createSrcSpan(mContext.getResources(), diagnostic));
    switch (diagnostic.getKind()) {
        case ERROR:
            holder.icon.setImageResource(R.drawable.ic_error_red);
            break;
        case WARNING:
            holder.icon.setImageResource(R.drawable.ic_warning_yellow);
            break;
        case MANDATORY_WARNING:
            holder.icon.setImageResource(R.drawable.ic_warning_yellow);
            break;
        case NOTE:
            holder.icon.setImageResource(R.drawable.ic_note_organe_24dp);
            break;
        case OTHER:
            holder.icon.setImageResource(R.drawable.ic_warning_yellow);
            break;
    }
    holder.message.setTypeface(FontManager.getFontFromAsset(mContext, "Roboto-Light.ttf"));
    holder.message.setText(diagnostic.getMessage(null));
    holder.root.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (listener != null) listener.onClick(diagnostic);
        }
    });
    String code = diagnostic.getCode();
}
 
Example 14
Source File: EndPositions.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String... args) throws IOException {
    class MyFileObject extends SimpleJavaFileObject {
        MyFileObject() {
            super(URI.create("myfo:///Test.java"), SOURCE);
        }
        @Override
        public String getCharContent(boolean ignoreEncodingErrors) {
            //      0         1         2         3
            //      012345678901234567890123456789012345
            return "class Test { String s = 1234; }";
        }
    }
    JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
    List<JavaFileObject> compilationUnits =
            Collections.<JavaFileObject>singletonList(new MyFileObject());
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
    List<String> options = Arrays.asList("-processor", EndPositions.class.getCanonicalName());
    JavacTask task = (JavacTask)javac.getTask(null, null, diagnostics, options, null, compilationUnits);
    boolean valid = task.call();
    if (valid)
        throw new AssertionError("Expected one error, but found none.");

    List<Diagnostic<? extends JavaFileObject>> errors = diagnostics.getDiagnostics();
    if (errors.size() != 1)
        throw new AssertionError("Expected one error only, but found " + errors.size() + "; errors: " + errors);

    Diagnostic<?> error = errors.get(0);
    if (error.getStartPosition() >= error.getEndPosition())
        throw new AssertionError("Expected start to be less than end position: start [" +
                error.getStartPosition() + "], end [" + error.getEndPosition() +"]" +
                "; diagnostics code: " + error.getCode());

    System.out.println("All is good!");
}
 
Example 15
Source File: TestLambdaToMethodStats.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
    try {
        if (diagnostic.getKind() == Diagnostic.Kind.NOTE) {
            switch (diagnostic.getCode()) {
                case "compiler.note.lambda.stat":
                    lambda = true;
                    break;
                case "compiler.note.mref.stat":
                    lambda = false;
                    bridge = false;
                    break;
                case "compiler.note.mref.stat.1":
                    lambda = false;
                    bridge = true;
                    break;
                default:
                    throw new AssertionError("unexpected note: " + diagnostic.getCode());
            }
            ClientCodeWrapper.DiagnosticSourceUnwrapper dsu =
                (ClientCodeWrapper.DiagnosticSourceUnwrapper)diagnostic;
            altMetafactory = (Boolean)dsu.d.getArgs()[0];
        }
    } catch (RuntimeException t) {
        t.printStackTrace();
        throw t;
    }
}
 
Example 16
Source File: EndPositions.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String... args) throws IOException {
    class MyFileObject extends SimpleJavaFileObject {
        MyFileObject() {
            super(URI.create("myfo:///Test.java"), SOURCE);
        }
        @Override
        public String getCharContent(boolean ignoreEncodingErrors) {
            //      0         1         2         3
            //      012345678901234567890123456789012345
            return "class Test { String s = 1234; }";
        }
    }
    JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
    List<JavaFileObject> compilationUnits =
            Collections.<JavaFileObject>singletonList(new MyFileObject());
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
    List<String> options = Arrays.asList("-processor", EndPositions.class.getCanonicalName());
    JavacTask task = (JavacTask)javac.getTask(null, null, diagnostics, options, null, compilationUnits);
    boolean valid = task.call();
    if (valid)
        throw new AssertionError("Expected one error, but found none.");

    List<Diagnostic<? extends JavaFileObject>> errors = diagnostics.getDiagnostics();
    if (errors.size() != 1)
        throw new AssertionError("Expected one error only, but found " + errors.size() + "; errors: " + errors);

    Diagnostic<?> error = errors.get(0);
    if (error.getStartPosition() >= error.getEndPosition())
        throw new AssertionError("Expected start to be less than end position: start [" +
                error.getStartPosition() + "], end [" + error.getEndPosition() +"]" +
                "; diagnostics code: " + error.getCode());

    System.out.println("All is good!");
}
 
Example 17
Source File: TestLambdaToMethodStats.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
    try {
        if (diagnostic.getKind() == Diagnostic.Kind.NOTE) {
            switch (diagnostic.getCode()) {
                case "compiler.note.lambda.stat":
                    lambda = true;
                    break;
                case "compiler.note.mref.stat":
                    lambda = false;
                    bridge = false;
                    break;
                case "compiler.note.mref.stat.1":
                    lambda = false;
                    bridge = true;
                    break;
                default:
                    throw new AssertionError("unexpected note: " + diagnostic.getCode());
            }
            ClientCodeWrapper.DiagnosticSourceUnwrapper dsu =
                (ClientCodeWrapper.DiagnosticSourceUnwrapper)diagnostic;
            altMetafactory = (Boolean)dsu.d.getArgs()[0];
        }
    } catch (RuntimeException t) {
        t.printStackTrace();
        throw t;
    }
}
 
Example 18
Source File: JavaCustomIndexer.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public static void brokenPlatform(
        @NonNull final Context ctx,
        @NonNull final Iterable<? extends CompileTuple> files,
        @NullAllowed final Diagnostic<JavaFileObject> diagnostic) {
    if (diagnostic == null) {
        return;
    }
    final Diagnostic<JavaFileObject> error = new Diagnostic<JavaFileObject>() {

        @Override
        public Kind getKind() {
            return Kind.ERROR;
        }

        @Override
        public JavaFileObject getSource() {
            return diagnostic.getSource();
        }

        @Override
        public long getPosition() {
            return diagnostic.getPosition();
        }

        @Override
        public long getStartPosition() {
            return diagnostic.getStartPosition();
        }

        @Override
        public long getEndPosition() {
            return diagnostic.getEndPosition();
        }

        @Override
        public long getLineNumber() {
            return diagnostic.getLineNumber();
        }

        @Override
        public long getColumnNumber() {
            return diagnostic.getColumnNumber();
        }

        @Override
        public String getCode() {
            return diagnostic.getCode();
        }

        @Override
        public String getMessage(Locale locale) {
            return diagnostic.getMessage(locale);
        }
    };
    for (CompileTuple file : files) {
        if (!file.virtual) {
            ErrorsCache.setErrors(
                ctx.getRootURI(),
                file.indexable,
                Collections.<Diagnostic<JavaFileObject>>singleton(error),
                ERROR_CONVERTOR);
        }
    }
}
 
Example 19
Source File: VanillaJavaBuilder.java    From bazel with Apache License 2.0 4 votes vote down vote up
public VanillaJavaBuilderResult run(List<String> args) throws IOException {
  OptionsParser optionsParser;
  try {
    optionsParser = new OptionsParser(args);
  } catch (InvalidCommandLineException e) {
    return new VanillaJavaBuilderResult(false, e.getMessage());
  }
  DiagnosticCollector<JavaFileObject> diagnosticCollector = new DiagnosticCollector<>();
  StringWriter output = new StringWriter();
  JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
  Path tempDir = Paths.get(firstNonNull(optionsParser.getTempDir(), "_tmp"));
  Path nativeHeaderDir = tempDir.resolve("native_headers");
  Files.createDirectories(nativeHeaderDir);
  boolean ok;
  try (StandardJavaFileManager fileManager =
      javaCompiler.getStandardFileManager(diagnosticCollector, ENGLISH, UTF_8)) {
    setLocations(optionsParser, fileManager, nativeHeaderDir);
    ImmutableList<JavaFileObject> sources = getSources(optionsParser, fileManager);
    if (sources.isEmpty()) {
      ok = true;
    } else {
      CompilationTask task =
          javaCompiler.getTask(
              new PrintWriter(output, true),
              fileManager,
              diagnosticCollector,
              JavacOptions.removeBazelSpecificFlags(optionsParser.getJavacOpts()),
              ImmutableList.<String>of() /*classes*/,
              sources);
      setProcessors(optionsParser, fileManager, task);
      ok = task.call();
    }
  }
  if (ok) {
    writeOutput(optionsParser);
    writeNativeHeaderOutput(optionsParser, nativeHeaderDir);
  }
  writeGeneratedSourceOutput(optionsParser);
  // the jdeps output doesn't include any information about dependencies, but Bazel still expects
  // the file to be created
  if (optionsParser.getOutputDepsProtoFile() != null) {
    try (OutputStream os =
        Files.newOutputStream(Paths.get(optionsParser.getOutputDepsProtoFile()))) {
      Deps.Dependencies.newBuilder()
          .setRuleLabel(optionsParser.getTargetLabel())
          .setSuccess(ok)
          .build()
          .writeTo(os);
    }
  }
  // TODO(cushon): support manifest protos & genjar
  if (optionsParser.getManifestProtoPath() != null) {
    try (OutputStream os =
        Files.newOutputStream(Paths.get(optionsParser.getManifestProtoPath()))) {
      Manifest.getDefaultInstance().writeTo(os);
    }
  }

  for (Diagnostic<? extends JavaFileObject> diagnostic : diagnosticCollector.getDiagnostics()) {
    String code = diagnostic.getCode();
    if (code.startsWith("compiler.note.deprecated")
        || code.startsWith("compiler.note.unchecked")
        || code.equals("compiler.warn.sun.proprietary")) {
      continue;
    }
    StringBuilder message = new StringBuilder();
    if (diagnostic.getSource() != null) {
      message.append(diagnostic.getSource().getName());
      if (diagnostic.getLineNumber() != -1) {
        message.append(':').append(diagnostic.getLineNumber());
      }
      message.append(": ");
    }
    message.append(diagnostic.getKind().toString().toLowerCase(ENGLISH));
    message.append(": ").append(diagnostic.getMessage(ENGLISH)).append(System.lineSeparator());
    output.write(message.toString());
  }
  return new VanillaJavaBuilderResult(ok, output.toString());
}
 
Example 20
Source File: CompileResult.java    From meghanada-server with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void store(StoreTransaction txn, Entity entity) {

  long now = Instant.now().getEpochSecond();
  entity.setProperty("createdAt", now);
  entity.setProperty("result", this.success);
  entity.setProperty("problems", this.diagnostics.size());

  for (Diagnostic<? extends JavaFileObject> diagnostic : this.diagnostics) {
    String kind = diagnostic.getKind().toString();
    long line = diagnostic.getLineNumber();
    long column = diagnostic.getColumnNumber();

    String message = diagnostic.getMessage(null);
    if (isNull(message)) {
      message = "";
    }
    JavaFileObject fileObject = diagnostic.getSource();
    String path = null;
    if (fileObject != null) {
      final URI uri = fileObject.toUri();
      final File file = new File(uri);
      try {
        path = file.getCanonicalPath();
      } catch (IOException e) {
        throw new UncheckedIOException(e);
      }
    }

    String code = diagnostic.getCode();
    Entity subEntity = txn.newEntity(CompileResult.DIAGNOSTIC_ENTITY_TYPE);
    subEntity.setProperty("kind", kind);
    subEntity.setProperty("line", line);
    subEntity.setProperty("column", column);
    subEntity.setProperty("message", message);
    if (nonNull(path)) {
      subEntity.setProperty("path", path);
    }
    if (nonNull(code)) {
      subEntity.setProperty("code", code);
    }

    entity.addLink("diagnostic", entity);
  }
}