Java 类javax.tools.Diagnostic 实例源码

项目:javaide    文件:SpanUtil.java   
public static Spannable createSrcSpan(Resources resources, @NonNull Diagnostic diagnostic) {
    if (diagnostic.getSource() == null) {
        return new SpannableString("Unknown");
    }
    if (!(diagnostic.getSource() instanceof JavaFileObject)) {
        return new SpannableString(diagnostic.getSource().toString());
    }
    try {
        JavaFileObject source = (JavaFileObject) diagnostic.getSource();
        File file = new File(source.getName());
        String name = file.getName();
        String line = diagnostic.getLineNumber() + ":" + diagnostic.getColumnNumber();
        SpannableString span = new SpannableString(name + ":" + line);
        span.setSpan(new ForegroundColorSpan(resources.getColor(R.color.dark_color_diagnostic_file)),
                0, span.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        return span;
    } catch (Exception e) {

    }
    return new SpannableString(diagnostic.getSource().toString());
}
项目:openapi-annotation-processor    文件:OpenAPIProcessor.java   
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    boolean lastRound = roundEnv.processingOver();
    if (lastRound) {
        LOG.debug("Processing last round");
    } else {
        LOG.debug("Processing");
    }
    AtomicReference<Element> currentAnnotatedElement = new AtomicReference<>();
    try {
        doProcess(roundEnv, currentAnnotatedElement, new RoundDescriptor(roundNumber.incrementAndGet(), lastRound));
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
        messager.printMessage(Diagnostic.Kind.ERROR, e.getMessage(), currentAnnotatedElement.get());
    }
    return true;
}
项目:auto-nav    文件:NavProcessor.java   
private ActivityIntentModel getActivityModel(TypeElement typeElement) {
    ActivityIntentModel activityModel = new ActivityIntentModel(
            elementsUtil.getPackageOf(typeElement).getQualifiedName().toString(),
            typeElement.getSimpleName().toString());

    messager.printMessage(Diagnostic.Kind.NOTE, "\ntype:" + typeElement.getQualifiedName());

    activityModel.addParamModels(getParamModels(typeElement));

    TypeMirror superType = typeElement.getSuperclass();

    while (superType != null && !Object.class.getName().equals(superType.toString())) {
        messager.printMessage(Diagnostic.Kind.NOTE, "\n   superType:" + superType.toString());
        Element element = typesUtil.asElement(superType);
        if (element != null && element instanceof TypeElement) {
            TypeElement superE = (TypeElement) element;
            activityModel.addParamModels(getParamModels(superE));

            superType = superE.getSuperclass();
        } else {
            superType = null;
        }
    }

    return activityModel;
}
项目:openjdk-jdk10    文件:JavacParserTest.java   
@Test
void testVariableInIfThen1() throws IOException {

    String code = "package t; class Test { " +
            "private static void t(String name) { " +
            "if (name != null) String nn = name.trim(); } }";

    DiagnosticCollector<JavaFileObject> coll =
            new DiagnosticCollector<JavaFileObject>();

    JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, fm, 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("testVariableInIfThen1",
            Arrays.<String>asList("compiler.err.variable.not.allowed"),
            codes);
}
项目:prefpin    文件:PrefPinProcessor.java   
private void parsePreferenceBinding(RoundEnvironment roundEnv,
    Map<TypeElement, Set<Element>> bindingMap, Class<? extends Annotation> annotation) {
  for (Element element : roundEnv.getElementsAnnotatedWith(annotation)) {
    if (element.getModifiers().contains(Modifier.PRIVATE)) {
      processingEnv.getMessager()
          .printMessage(Diagnostic.Kind.ERROR,
              "Binding annotation can not applied to private fields or methods.", element);
    }

    if (annotation == BindPref.class) {
      checkPreferenceAnnotation(element);
    }

    TypeElement targetPrefFragment = (TypeElement) element.getEnclosingElement();
    if (bindingMap.containsKey(targetPrefFragment)) {
      bindingMap.get(targetPrefFragment).add(element);
    } else {
      Set<Element> fields = new LinkedHashSet<>();
      fields.add(element);
      bindingMap.put(targetPrefFragment, fields);
    }
  }
}
项目:immu    文件:ImmuCompilerTest.java   
@Test
public void write_withIOException() throws Exception {
  final ProcessingEnvironment env = mock(ProcessingEnvironment.class);
  final Messager messager = mock(Messager.class);
  final Filer filer = mock(Filer.class);

  when(env.getMessager()).thenReturn(messager);
  when(env.getFiler()).thenReturn(filer);

  compiler.init(env);

  final JavaFile javaFile = mock(JavaFile.class);
  doThrow(IOException.class).when(javaFile).writeTo(any(Filer.class));

  compiler.writeSource(javaFile);

  verify(messager, times(1)).printMessage(eq(Diagnostic.Kind.ERROR), any());
}
项目:incubator-netbeans    文件:UtilitiesTest.java   
public void testLambdaPattern() throws Exception {
    prepareTest("test/Test.java", "package test; public class Test{}");

    Scope s = Utilities.constructScope(info, Collections.<String, TypeMirror>emptyMap());
    Tree result = Utilities.parseAndAttribute(info, "new $type() {\n $mods$ $resultType $methodName($args$) {\n $statements$;\n }\n }\n", s);

    assertTrue(result.getKind().name(), result.getKind() == Kind.NEW_CLASS);

    String golden = "new $type(){ $mods$ $resultType $methodName($args$) { $statements$; } }";
    assertEquals(golden.replaceAll("[ \n\r]+", " "), result.toString().replaceAll("[ \n\r]+", " "));

    Collection<Diagnostic<? extends JavaFileObject>> errors = new LinkedList<Diagnostic<? extends JavaFileObject>>();

    result = Utilities.parseAndAttribute(info, "new $type() {\n $mods$ $resultType $methodName($args$) {\n $statements$;\n }\n }\n", null, errors);
    assertTrue(result.getKind().name(), result.getKind() == Kind.NEW_CLASS);

    golden = "new $type(){ $mods$ $resultType $methodName($args$) { $statements$; } }";
    assertEquals(golden.replaceAll("[ \n\r]+", " "), result.toString().replaceAll("[ \n\r]+", " "));
    assertTrue(errors.toString(), errors.isEmpty());
}
项目:GitHub    文件:EventBusAnnotationProcessor.java   
private boolean checkHasNoErrors(ExecutableElement element, Messager messager) {
    if (element.getModifiers().contains(Modifier.STATIC)) {
        messager.printMessage(Diagnostic.Kind.ERROR, "Subscriber method must not be static", element);
        return false;
    }

    if (!element.getModifiers().contains(Modifier.PUBLIC)) {
        messager.printMessage(Diagnostic.Kind.ERROR, "Subscriber method must be public", element);
        return false;
    }

    List<? extends VariableElement> parameters = ((ExecutableElement) element).getParameters();
    if (parameters.size() != 1) {
        messager.printMessage(Diagnostic.Kind.ERROR, "Subscriber method must have exactly 1 parameter", element);
        return false;
    }
    return true;
}
项目:GitHub    文件:MvpCompiler.java   
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    if (annotations.isEmpty()) {
        return false;
    }

    try {
        return throwableProcess(roundEnv);
    } catch (RuntimeException e) {
        getMessager().printMessage(Diagnostic.Kind.OTHER, "Moxy compilation failed. Could you copy stack trace above and write us (or make issue on Githhub)?");
        e.printStackTrace();
        getMessager().printMessage(Diagnostic.Kind.ERROR, "Moxy compilation failed; see the compiler error output for details (" + e + ")");
    }

    return true;
}
项目:AptSpring    文件:VerifiedSpringConfiguration.java   
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment env) {
  try  {
    if (env.processingOver()) {
      definitionAggregator.outputErrors(messager);
    } else {
      AptElementVisitor visitor = new AptElementVisitor(te -> new SpringAnnotationParser().extractDefinition(te, messager));
      for (Element annotatedElement : env.getElementsAnnotatedWith(Verified.class)) {
        visitor.visit(annotatedElement, definitionAggregator);        
      }
    }
    return true;
  } catch (Exception exception) {
    // Catch and print for debugging reasons. This code path is unexpected.
    StringWriter writer = new StringWriter();
    exception.printStackTrace(new PrintWriter(writer));
    messager.printMessage(Diagnostic.Kind.ERROR, writer.toString());
    return true;
  }
}
项目:manifold    文件:ExtCodeGen.java   
private boolean warnIfDuplicate( AbstractSrcMethod method, SrcClass extendedType, DiagnosticListener<JavaFileObject> errorHandler, JavacTaskImpl javacTask )
{
  AbstractSrcMethod duplicate = findMethod( method, extendedType, new JavacTaskImpl[]{javacTask} );

  if( duplicate == null )
  {
    return false;
  }

  JavacElements elems = JavacElements.instance( javacTask.getContext() );
  Symbol.ClassSymbol sym = elems.getTypeElement( ((SrcClass)method.getOwner()).getName() );
  JavaFileObject file = sym.sourcefile;
  SrcAnnotationExpression anno = duplicate.getAnnotation( ExtensionMethod.class );
  if( anno != null )
  {
    errorHandler.report( new JavacDiagnostic( file.toUri().getScheme() == null ? null : new SourceJavaFileObject( file.toUri() ),
                                              Diagnostic.Kind.WARNING, 0, 0, 0, ExtIssueMsg.MSG_EXTENSION_DUPLICATION.get( method.signature(), ((SrcClass)method.getOwner()).getName(), anno.getArgument( ExtensionMethod.extensionClass ).getValue()) ) );
  }
  else
  {
    errorHandler.report( new JavacDiagnostic( file.toUri().getScheme() == null ? null : new SourceJavaFileObject( file.toUri() ),
                                              Diagnostic.Kind.WARNING, 0, 0, 0, ExtIssueMsg.MSG_EXTENSION_SHADOWS.get( method.signature(), ((SrcClass)method.getOwner()).getName(), extendedType.getName()) ) );
  }
  return true;
}
项目:annotation-processor-toolkit    文件:AnnotationProcessorWrapper.java   
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {

    // now set note message before calling the processor
    messager.printMessage(Diagnostic.Kind.NOTE, AbstractAnnotationProcessorTest.TEST_EXECUTION_MESSAGE);

    return wrappedProcessor.process(annotations, roundEnv);
}
项目:OpenJSharp    文件:Messages.java   
protected void report(Group group, Diagnostic.Kind dkind, DocTree tree, String code, Object... args) {
    if (options.isEnabled(group, env.currAccess)) {
        String msg = (code == null) ? (String) args[0] : localize(code, args);
        env.trees.printMessage(dkind, msg, tree,
                env.currDocComment, env.currPath.getCompilationUnit());

        stats.record(group, dkind, code);
    }
}
项目:javaide    文件:AbstractProcessor.java   
/**
 * If the processor class is annotated with {@link
 * SupportedAnnotationTypes}, return an unmodifiable set with the
 * same set of strings as the annotation.  If the class is not so
 * annotated, an empty set is returned.
 *
 * @return the names of the annotation types supported by this
 * processor, or an empty set if none
 */
public Set<String> getSupportedAnnotationTypes() {
        SupportedAnnotationTypes sat = this.getClass().getAnnotation(SupportedAnnotationTypes.class);
        if  (sat == null) {
            if (isInitialized())
                processingEnv.getMessager().printMessage(Diagnostic.Kind.WARNING,
                                                         "No SupportedAnnotationTypes annotation " +
                                                         "found on " + this.getClass().getName() +
                                                         ", returning an empty set.");
            return Collections.emptySet();
        }
        else
            return arrayToSet(sat.value());
    }
项目:openjdk-jdk10    文件:UnusedResourcesTest.java   
public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
    if (diagnostic.getKind() == Diagnostic.Kind.WARNING &&
            diagnostic.getCode().contains("try.resource.not.referenced")) {
        String varName = unwrap(diagnostic).getArgs()[0].toString();
        if (varName.equals(TwrStmt.TWR1.resourceName)) {
            unused_r1 = true;
        } else if (varName.equals(TwrStmt.TWR2.resourceName)) {
            unused_r2 = true;
        } else if (varName.equals(TwrStmt.TWR3.resourceName)) {
            unused_r3 = true;
        }
    }
}
项目:guava-beta-checker    文件:TestCompiler.java   
/**
 * Compiles the given {@code sources} and returns a list of diagnostics produced by the compiler.
 */
public List<Diagnostic<? extends JavaFileObject>> compile(
    Iterable<? extends JavaFileObject> sources) {
  ScannerSupplier scannerSupplier = ScannerSupplier.fromBugCheckerClasses(checker);
  DiagnosticCollector<JavaFileObject> collector = new DiagnosticCollector<>();
  JavaCompiler compiler = new BaseErrorProneJavaCompiler(scannerSupplier);
  File tmpDir = Files.createTempDir();
  CompilationTask task =
      compiler.getTask(
          new PrintWriter(System.err, true),
          null /*filemanager*/,
          collector,
          ImmutableList.of("-d", tmpDir.getAbsolutePath()),
          null /*classes*/,
          sources);
  try {
    task.call();
    return collector.getDiagnostics();
  } finally {
    File[] files = tmpDir.listFiles();
    if (files != null) {
      for (File file : files) {
        file.delete();
      }
    }
    tmpDir.delete();
  }
}
项目:domino    文件:ServerModuleAnnotationProcessor.java   
private void generateServerModule(ProcessorElement processorElement, List<ProcessorElement> handlers,
                                  List<ProcessorElement> interceptors, List<ProcessorElement> globalInterceptors) {
    try (Writer sourceWriter = obtainSourceWriter(processorElement.elementPackage(), processorElement.getAnnotation(ServerModule.class).name() + "ServerModule")) {
        sourceWriter.write(new ServerModuleSourceWriter(processorElement, handlers, interceptors, globalInterceptors).write());
    } catch (IOException e) {
        LOGGER.log(Level.SEVERE, "Could not generate classes : ", e);
        messager.printMessage(Diagnostic.Kind.ERROR, "could not generate class");
    }
}
项目:remoter    文件:RemoterProcessor.java   
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment env) {
    for (Element element : env.getElementsAnnotatedWith(Remoter.class)) {
        if (element.getKind() == ElementKind.INTERFACE) {
            bindingManager.generateProxy(element);
            bindingManager.generateStub(element);
        } else {
            messager.printMessage(Diagnostic.Kind.WARNING, "@Remoter is expected only for interface. Ignoring " + element.getSimpleName());
        }
    }
    return false;
}
项目:manifold    文件:JavascriptCodeGen.java   
private void reportErrors( DiagnosticListener<JavaFileObject> errorHandler, ProgramNode programNode )
{
  if( programNode.errorCount() > 0 )
  {
    JavaFileObject file = new SourceJavaFileObject( _file.toURI() );
    for( ParseError error : programNode.getErrorList() )
    {
      Token token = error.getToken();
      errorHandler.report( new JavacDiagnostic( file, Diagnostic.Kind.ERROR, token.getOffset(), token.getLineNumber(), token.getCol(), error.getMessage() ) );
    }
  }
}
项目:incubator-netbeans    文件:CompilationInfoImpl.java   
@Override
public void report(Diagnostic<? extends JavaFileObject> message) {
    if (partialReparseErrors != null) {
        if (this.jfo != null && this.jfo == message.getSource()) {
            partialReparseErrors.add(message);
            if (message.getKind() == Kind.ERROR) {
                partialReparseRealErrors = true;
            }
        }
    } else {
        Diagnostics errors = getErrors(message.getSource());
        errors.add((int) message.getPosition(), message);
    }
}
项目:openjdk-jdk10    文件:Example.java   
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();
}
项目:java-code-templates    文件:AstSubstitutionProcessor.java   
void clearSubstitutions() {
    if (!substitutionStack.isEmpty()) {
        messager.printMessage(Diagnostic.Kind.MANDATORY_WARNING,
                String.format("Substitution stack cleared while %d elements remained", substitutionStack.size()),
                substitutionInventory.typeElement());
    }
    substitutionStack.clear();
}
项目:incubator-netbeans    文件:DiagnosticListenerImpl.java   
public void report(Diagnostic<? extends JavaFileObject> d) {
    assert logDiagnostic(d);

    JavaFileObject source = d.getSource();

    if (source != null) {
        List<Diagnostic<? extends JavaFileObject>> current = diagnostics.get(source.toUri());

        if (current == null) {
            diagnostics.put(source.toUri(), current = new LinkedList<Diagnostic<? extends JavaFileObject>>());
        }

        current.add(d);
    }
}
项目:javaide    文件:FormattingJavaFileObject.java   
@Override
public Writer openWriter() throws IOException {
  final StringBuilder stringBuilder = new StringBuilder(DEFAULT_FILE_SIZE);
  return new Writer() {
    @Override
    public void write(char[] chars, int start, int end) throws IOException {
      stringBuilder.append(chars, start, end - start);
    }

    @Override
    public void flush() throws IOException {}

    @Override
    public void close() throws IOException {
      try {
        formatter.formatSource(
            CharSource.wrap(stringBuilder),
            new CharSink() {
              @Override
              public Writer openStream() throws IOException {
                return fileObject.openWriter();
              }
            });
      } catch (FormatterException e) {
        // An exception will happen when the code being formatted has an error. It's better to
        // log the exception and emit unformatted code so the developer can view the code which
        // caused a problem.
        try (Writer writer = fileObject.openWriter()) {
          writer.append(stringBuilder.toString());
        }
        if (messager != null) {
          messager.printMessage(Diagnostic.Kind.NOTE, "Error formatting " + getName());
        }
      }
    }
  };
}
项目:openjdk-jdk10    文件:TaskFactory.java   
DiagList getDiagnostics() {
    if (diags == null) {
        LinkedHashMap<String, Diag> diagMap = new LinkedHashMap<>();
        for (Diagnostic<? extends JavaFileObject> in : diagnostics.getDiagnostics()) {
            Diag d = diag(in);
            String uniqueKey = d.getCode() + ":" + d.getPosition() + ":" + d.getMessage(PARSED_LOCALE);
            diagMap.put(uniqueKey, d);
        }
        diags = new DiagList(diagMap.values());
    }
    return diags;
}
项目:jdoocsoup    文件:JDoocsSoupAnnotationProcessor.java   
private void createJavaFile(String packageName, TypeSpec typeSpec) {
    try {
        JavaFile javaFile = JavaFile.builder(packageName, typeSpec)
                .build();
        javaFile.writeTo(processingEnv.getFiler());
    } catch (IOException ex) {
        processingEnv.getMessager()
                .printMessage(Diagnostic.Kind.ERROR, "It was not possible to generate java files due to an error: \n" + ex.getMessage());
    }
}
项目:domino    文件:ContributionsCollector.java   
private boolean addContribution(ProcessorElement c) {
    if(!c.isImplementsGenericInterface(Contribution.class)) {
        messager.printMessage(Diagnostic.Kind.ERROR, "Not implementing contribution interface", c.getElement());
        throw new NotImplementingContributionInterfaceException();
    }
    return contributions
            .add(c.fullQualifiedNoneGenericName() + ":" +
                    getContributionExtensionPoint(c));
}
项目:Coconut-IDE    文件:HighlightCell.java   
private static TreeItem<Path> isCurrTreeItem(Diagnostic diagnostic) {
    JavaFileObject javaFileObject = (JavaFileObject) diagnostic.getSource();
    Optional<TreeItem<Path>> item = treeItems.parallelStream()
            .filter(c -> javaFileObject.getName().equals(c.getValue().toString()))
            .findFirst();

    if (item.isPresent()) {
        TreeItem<Path> treeItem = item.get();
        treeItems.remove(treeItem);
        return treeItem;
    }

    return null;
}
项目:incubator-netbeans    文件:Utilities.java   
private static Token<JavaTokenId> createHighlightImpl(CompilationInfo info, Document doc, TreePath tree) {
    Tree leaf = tree.getLeaf();
    SourcePositions positions = info.getTrees().getSourcePositions();
    CompilationUnitTree cu = info.getCompilationUnit();

    //XXX: do not use instanceof:
    if (leaf instanceof MethodTree || leaf instanceof VariableTree || leaf instanceof ClassTree
            || leaf instanceof MemberSelectTree || leaf instanceof AnnotatedTypeTree || leaf instanceof MemberReferenceTree) {
        return findIdentifierSpan(info, doc, tree);
    }

    int start = (int) positions.getStartPosition(cu, leaf);
    int end = (int) positions.getEndPosition(cu, leaf);

    if (start == Diagnostic.NOPOS || end == Diagnostic.NOPOS) {
        return null;
    }

    TokenHierarchy<?> th = info.getTokenHierarchy();
    TokenSequence<JavaTokenId> ts = th.tokenSequence(JavaTokenId.language());

    if (ts.move(start) == Integer.MAX_VALUE) {
        return null;
    }

    if (ts.moveNext()) {
        Token<JavaTokenId> token = ts.token();
        if (ts.offset() == start && token != null) {
            final JavaTokenId id = token.id();
            if (id == JavaTokenId.IDENTIFIER) {
                return token;
            }
            if (id == JavaTokenId.THIS || id == JavaTokenId.SUPER) {
                return ts.offsetToken();
            }
        }
    }

    return null;
}
项目:incubator-netbeans    文件:JavaCompletionTask.java   
private void insideAssignment(Env env) throws IOException {
    int offset = env.getOffset();
    TreePath path = env.getPath();
    AssignmentTree as = (AssignmentTree) path.getLeaf();
    SourcePositions sourcePositions = env.getSourcePositions();
    CompilationUnitTree root = env.getRoot();
    int asTextStart = (int) sourcePositions.getEndPosition(root, as.getVariable());
    if (asTextStart != Diagnostic.NOPOS) {
        Tree expr = unwrapErrTree(as.getExpression());
        if (expr == null || offset <= (int) sourcePositions.getStartPosition(root, expr)) {
            CompilationController controller = env.getController();
            String asText = controller.getText().substring(asTextStart, offset);
            int eqPos = asText.indexOf('='); //NOI18N
            if (eqPos > -1) {
                TreePath parentPath = path.getParentPath();
                if (parentPath.getLeaf().getKind() != Tree.Kind.ANNOTATION) {
                    localResult(env);
                    addValueKeywords(env);
                } else if (as.getVariable().getKind() == Tree.Kind.IDENTIFIER) {
                    insideAnnotationAttribute(env, parentPath, ((IdentifierTree) as.getVariable()).getName());
                    addLocalConstantsAndTypes(env);
                }
            }
        } else {
            insideExpression(env, new TreePath(path, expr));
        }
    }
}
项目:openjdk-jdk10    文件:ClassesTest.java   
public void classesIgnoredModifiersAnnotation() {
    assertEval("public @interface X { }");
    assertEval("@X public interface A { }");
    assertDeclareWarn1("@X static class B implements A { }",
            new ExpectedDiagnostic("jdk.eval.warn.illegal.modifiers", 0, 9, 0, -1, -1, Diagnostic.Kind.WARNING));
    assertDeclareWarn1("@X final interface C extends A { }",
            new ExpectedDiagnostic("jdk.eval.warn.illegal.modifiers", 0, 8, 0, -1, -1, Diagnostic.Kind.WARNING));
    assertActiveKeys();
}
项目:mcc    文件:CompilerErrorTest.java   
@Test
public void testTaskListError() {

    SourceTask sourceTask = new SourceTask();
    sourceTask.createSourceClass("teste", "Teste0", "package teste; public class Teste0 {}");
    sourceTask.createSourceClass("teste", "Teste1", "public class Teste0 {}");
    sourceTask.createSourceClass("teste", "Teste2", "package teste; public class Teste2 {}");

    MemoryClassCompiler compiler = new MemoryClassCompiler();

    boolean throwError = false;

    try {
        compiler.compile(sourceTask);
    } catch (MemoryCompilerException ex) {
        Assert.assertEquals(sourceTask.getSourcesClass().size(), 3);
        SourceClass sourceClass1 = sourceTask.findSourceClass("teste.Teste0");
        Assert.assertNull(sourceClass1.getBytecode());
        SourceClass sourceClass2 = sourceTask.findSourceClass("teste.Teste1");
        Assert.assertNull(sourceClass2.getBytecode());
        SourceClass sourceClass3 = sourceTask.findSourceClass("teste.Teste2");
        Assert.assertNull(sourceClass3.getBytecode());

        Assert.assertEquals(ex.getMessageCompiler().getMessage(), "Error in compilation of class");
        Assert.assertEquals(ex.getMessageCompiler().getStatus(), MessageStatus.FAILED);
        Assert.assertEquals(ex.getMessageCompiler().getDiagnostics().get(0).getCode(), "compiler.err.class.public.should.be.in.file");
        Assert.assertEquals(ex.getMessageCompiler().getDiagnostics().get(0).getColumnNumber(), 8);
        Assert.assertEquals(ex.getMessageCompiler().getDiagnostics().get(0).getEndPosition(), 22);
        Assert.assertEquals(ex.getMessageCompiler().getDiagnostics().get(0).getLineNumber(), 1);
        Assert.assertEquals(ex.getMessageCompiler().getDiagnostics().get(0).getMessage(null), "class Teste0 is public, should be declared in a file named Teste0.java");
        Assert.assertEquals(ex.getMessageCompiler().getDiagnostics().get(0).getPosition(), 7);
        Assert.assertEquals(ex.getMessageCompiler().getDiagnostics().get(0).getStartPosition(), 0);
        Assert.assertEquals(ex.getMessageCompiler().getDiagnostics().get(0).getKind(), Diagnostic.Kind.ERROR);
        throwError = true;
    }
    Assert.assertTrue(throwError);
}
项目:OpenJSharp    文件:WebServiceAp.java   
@Override
public void processWarning(String message) {
    if (isCommandLineInvocation) {
        processingEnv.getMessager().printMessage(Diagnostic.Kind.WARNING, message);
    } else {
        report(message);
    }
}
项目:jtsgen    文件:TsGenProcessor.java   
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    try {
        LOG.log(INFO, () -> String.format("P: Processing Annotations %s (isOver=%b)", annotations, roundEnv.processingOver()));
        if (roundEnv.processingOver() && !roundEnv.errorRaised()) {
            LOG.info(() -> "P: processing over. Start rendering.");
            new TSRenderer(processingEnv, typeScriptModel).writeFiles();
        } else if (roundEnv.processingOver() && roundEnv.errorRaised()) {
            LOG.info(() -> "P: processing over. error raised. nothing to do");
        } else {
            PROCESSING_ORDER.forEach(
                    (x) -> {
                        final Optional<? extends TypeElement> annotation = annotations
                                .stream()
                                .filter((y) -> y.getSimpleName().contentEquals(x.getSimpleName()))
                                .findFirst();
                        LOG.finest(() -> String.format("P: Annotation %s member %s", x, annotation.isPresent()));
                        annotation.ifPresent(typeElement -> processElements(typeElement, roundEnv));
                    }
            );
        }
    } catch (Exception e) {
        this.processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "internal error in jtsgen " + e);
        System.err.println("FATAL error in jtsgen. Please file an issue with the following stack trace @ https://github.com/dzuvic/jtsgen/issues");
        e.printStackTrace();
    }

    return true;
}
项目:incubator-netbeans    文件:UtilitiesTest.java   
public void testErrorsForPatterns1() throws Exception {
    prepareTest("test/Test.java", "package test; public class Test{}");

    SourcePositions[] positions = new SourcePositions[1];
    Collection<Diagnostic<? extends JavaFileObject>> errors = new LinkedList<Diagnostic<? extends JavaFileObject>>();
    String code = "foo bar";
    Tree result = Utilities.parseAndAttribute(info, code, null, positions, errors);

    assertDiagnostics(errors, "7-7:compiler.err.expected");
    assertPositions(result, positions[0], code, "foo", "foo bar");
}
项目:openjdk-jdk10    文件:UnusedResourcesTest.java   
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();
}
项目:shortbread    文件:ShortcutProcessor.java   
private void error(Element element, String message, Object... args) {
    if (args.length > 0) {
        message = String.format(message, args);
    }

    processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, message, element);
}
项目:incubator-netbeans    文件:BaseTask.java   
List<Tree> getArgumentsUpToPos(Env env, Iterable<? extends ExpressionTree> args, int startPos, int position, boolean strict) {
    List<Tree> ret = new ArrayList<>();
    CompilationUnitTree root = env.getRoot();
    SourcePositions sourcePositions = env.getSourcePositions();
    if (args == null) {
        return null; //TODO: member reference???
    }
    for (ExpressionTree e : args) {
        int pos = (int) sourcePositions.getEndPosition(root, e);
        if (pos != Diagnostic.NOPOS && (position > pos || !strict && position == pos)) {
            startPos = pos;
            ret.add(e);
        } else {
            break;
        }
    }
    if (startPos < 0) {
        return ret;
    }
    if (position >= startPos) {
        TokenSequence<JavaTokenId> last = findLastNonWhitespaceToken(env, startPos, position);
        if (last == null) {
            if (!strict && !ret.isEmpty()) {
                ret.remove(ret.size() - 1);
                return ret;
            }
        } else if (last.token().id() == JavaTokenId.LPAREN || last.token().id() == JavaTokenId.COMMA) {
            return ret;
        }
    }
    return null;
}
项目:javaide    文件:CompileJavaTask.java   
@Override
protected Integer doInBackground(JavaProjectFolder... params) {
    if (params[0] == null) return null;
    this.projectFile = params[0];
    DiagnosticListener listener = new DiagnosticListener() {
        @Override
        public void report(Diagnostic diagnostic) {
            mDiagnostics.add(diagnostic);
        }
    };
    //clean task
    projectFile.clean();
    projectFile.createBuildDir();

    int status = CompileHelper.compileJava(context, projectFile, listener);
    if (status == Main.EXIT_OK) {
        try {
            CompileHelper.convertToDexFormat(context, projectFile);
        } catch (Throwable e) {
            this.error = e;
            Log.e(TAG, "doInBackground: ", e);
            publishProgress(e.getMessage().toCharArray(), 0, e.getMessage().length());
            status = Main.EXIT_ERROR;
        }
    }
    return status;
}
项目:GitHub    文件:CompilerWarningIT.java   
@Test
public void checkWarnings() {
  schemaRule.generate(schema, "com.example", config);
  schemaRule.compile(compiler, new NullWriter(), new ArrayList<File>(), config);

  List<Diagnostic<? extends JavaFileObject>> warnings = warnings(schemaRule.getDiagnostics());

  assertThat(warnings, matcher);
}