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

The following examples show how to use javax.tools.Diagnostic#getPosition() . 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: 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 2
Source File: T6458823.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    if (compiler == null) {
        throw new RuntimeException("can't get javax.tools.JavaCompiler!");
    }
    DiagnosticCollector<JavaFileObject> diagColl =
        new DiagnosticCollector<JavaFileObject>();
    StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, null);
    List<String> options = new ArrayList<String>();
    options.add("-processor");
    options.add("MyProcessor");
    options.add("-proc:only");
    List<File> files = new ArrayList<File>();
    files.add(new File(T6458823.class.getResource("TestClass.java").toURI()));
    final CompilationTask task = compiler.getTask(null, fm, diagColl,
        options, null, fm.getJavaFileObjectsFromFiles(files));
    task.call();
    int diagCount = 0;
    for (Diagnostic<? extends JavaFileObject> diag : diagColl.getDiagnostics()) {
        if (diag.getKind() != Diagnostic.Kind.WARNING) {
            throw new AssertionError("Only warnings expected");
        }
        System.out.println(diag);
        if (diag.getPosition() == Diagnostic.NOPOS) {
            throw new AssertionError("No position info in message");
        }
        if (diag.getSource() == null) {
            throw new AssertionError("No source info in message");
        }
        diagCount++;
    }
    if (diagCount != 2) {
        throw new AssertionError("unexpected number of warnings: " +
            diagCount + ", expected: 2");
    }
}
 
Example 3
Source File: ErrorSuppressingDiagnosticListener.java    From buck with Apache License 2.0 5 votes vote down vote up
private void removeFromRecordedSet(Diagnostic<? extends JavaFileObject> diagnostic) {
  JavaFileObject file = diagnostic.getSource();
  if (file == null) {
    return;
  }

  try {
    Set<?> recorded = (Set<?>) Objects.requireNonNull(recordedField).get(getLog());
    if (recorded != null) {
      boolean removed = false;
      for (Object recordedPair : recorded) {
        JavaFileObject fst =
            (JavaFileObject) Objects.requireNonNull(pairFirstField).get(recordedPair);
        Integer snd = (Integer) Objects.requireNonNull(pairSecondField).get(recordedPair);

        if (snd == diagnostic.getPosition() && fst.getName().equals(file.getName())) {
          removed = recorded.remove(recordedPair);
          break;
        }
      }
      if (!removed) {
        throw new AssertionError(
            String.format(
                "BUG! Failed to remove %s: %d", file.getName(), diagnostic.getPosition()));
      }
    }
  } catch (IllegalAccessException e) {
    throw new RuntimeException(e);
  }
}
 
Example 4
Source File: T6458823.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    if (compiler == null) {
        throw new RuntimeException("can't get javax.tools.JavaCompiler!");
    }
    DiagnosticCollector<JavaFileObject> diagColl =
        new DiagnosticCollector<JavaFileObject>();
    StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, null);
    List<String> options = new ArrayList<String>();
    options.add("-processor");
    options.add("MyProcessor");
    options.add("-proc:only");
    List<File> files = new ArrayList<File>();
    files.add(new File(T6458823.class.getResource("TestClass.java").toURI()));
    final CompilationTask task = compiler.getTask(null, fm, diagColl,
        options, null, fm.getJavaFileObjectsFromFiles(files));
    task.call();
    int diagCount = 0;
    for (Diagnostic<? extends JavaFileObject> diag : diagColl.getDiagnostics()) {
        if (diag.getKind() != Diagnostic.Kind.WARNING) {
            throw new AssertionError("Only warnings expected");
        }
        System.out.println(diag);
        if (diag.getPosition() == Diagnostic.NOPOS) {
            throw new AssertionError("No position info in message");
        }
        if (diag.getSource() == null) {
            throw new AssertionError("No source info in message");
        }
        diagCount++;
    }
    if (diagCount != 2) {
        throw new AssertionError("unexpected number of warnings: " +
            diagCount + ", expected: 2");
    }
}
 
Example 5
Source File: T6458823.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    if (compiler == null) {
        throw new RuntimeException("can't get javax.tools.JavaCompiler!");
    }
    DiagnosticCollector<JavaFileObject> diagColl =
        new DiagnosticCollector<JavaFileObject>();
    StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, null);
    List<String> options = new ArrayList<String>();
    options.add("-processor");
    options.add("MyProcessor");
    options.add("-proc:only");
    List<File> files = new ArrayList<File>();
    files.add(new File(T6458823.class.getResource("TestClass.java").toURI()));
    final CompilationTask task = compiler.getTask(null, fm, diagColl,
        options, null, fm.getJavaFileObjectsFromFiles(files));
    task.call();
    int diagCount = 0;
    for (Diagnostic<? extends JavaFileObject> diag : diagColl.getDiagnostics()) {
        if (diag.getKind() != Diagnostic.Kind.WARNING) {
            throw new AssertionError("Only warnings expected");
        }
        System.out.println(diag);
        if (diag.getPosition() == Diagnostic.NOPOS) {
            throw new AssertionError("No position info in message");
        }
        if (diag.getSource() == null) {
            throw new AssertionError("No source info in message");
        }
        diagCount++;
    }
    if (diagCount != 2) {
        throw new AssertionError("unexpected number of warnings: " +
            diagCount + ", expected: 2");
    }
}
 
Example 6
Source File: T6458823.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    if (compiler == null) {
        throw new RuntimeException("can't get javax.tools.JavaCompiler!");
    }
    DiagnosticCollector<JavaFileObject> diagColl =
        new DiagnosticCollector<JavaFileObject>();
    StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, null);
    List<String> options = new ArrayList<String>();
    options.add("-processor");
    options.add("MyProcessor");
    options.add("-proc:only");
    List<File> files = new ArrayList<File>();
    files.add(new File(T6458823.class.getResource("TestClass.java").toURI()));
    final CompilationTask task = compiler.getTask(null, fm, diagColl,
        options, null, fm.getJavaFileObjectsFromFiles(files));
    task.call();
    int diagCount = 0;
    for (Diagnostic<? extends JavaFileObject> diag : diagColl.getDiagnostics()) {
        if (diag.getKind() != Diagnostic.Kind.WARNING) {
            throw new AssertionError("Only warnings expected");
        }
        System.out.println(diag);
        if (diag.getPosition() == Diagnostic.NOPOS) {
            throw new AssertionError("No position info in message");
        }
        if (diag.getSource() == null) {
            throw new AssertionError("No source info in message");
        }
        diagCount++;
    }
    if (diagCount != 2) {
        throw new AssertionError("unexpected number of warnings: " +
            diagCount + ", expected: 2");
    }
}
 
Example 7
Source File: T6458823.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    if (compiler == null) {
        throw new RuntimeException("can't get javax.tools.JavaCompiler!");
    }
    DiagnosticCollector<JavaFileObject> diagColl =
        new DiagnosticCollector<JavaFileObject>();
    try (StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, null)) {
        List<String> options = new ArrayList<String>();
        options.add("-processor");
        options.add("MyProcessor");
        options.add("-proc:only");
        List<File> files = new ArrayList<File>();
        files.add(new File(T6458823.class.getResource("TestClass.java").toURI()));
        final CompilationTask task = compiler.getTask(null, fm, diagColl,
            options, null, fm.getJavaFileObjectsFromFiles(files));
        task.call();
        int diagCount = 0;
        for (Diagnostic<? extends JavaFileObject> diag : diagColl.getDiagnostics()) {
            if (diag.getKind() != Diagnostic.Kind.WARNING) {
                throw new AssertionError("Only warnings expected");
            }
            System.out.println(diag);
            if (diag.getPosition() == Diagnostic.NOPOS) {
                throw new AssertionError("No position info in message");
            }
            if (diag.getSource() == null) {
                throw new AssertionError("No source info in message");
            }
            diagCount++;
        }
        if (diagCount != 2) {
            throw new AssertionError("unexpected number of warnings: " +
                diagCount + ", expected: 2");
        }
    }
}
 
Example 8
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 9
Source File: T6458823.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 Exception {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    if (compiler == null) {
        throw new RuntimeException("can't get javax.tools.JavaCompiler!");
    }
    DiagnosticCollector<JavaFileObject> diagColl =
        new DiagnosticCollector<JavaFileObject>();
    StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, null);
    List<String> options = new ArrayList<String>();
    options.add("-processor");
    options.add("MyProcessor");
    options.add("-proc:only");
    List<File> files = new ArrayList<File>();
    files.add(new File(T6458823.class.getResource("TestClass.java").toURI()));
    final CompilationTask task = compiler.getTask(null, fm, diagColl,
        options, null, fm.getJavaFileObjectsFromFiles(files));
    task.call();
    int diagCount = 0;
    for (Diagnostic<? extends JavaFileObject> diag : diagColl.getDiagnostics()) {
        if (diag.getKind() != Diagnostic.Kind.WARNING) {
            throw new AssertionError("Only warnings expected");
        }
        System.out.println(diag);
        if (diag.getPosition() == Diagnostic.NOPOS) {
            throw new AssertionError("No position info in message");
        }
        if (diag.getSource() == null) {
            throw new AssertionError("No source info in message");
        }
        diagCount++;
    }
    if (diagCount != 2) {
        throw new AssertionError("unexpected number of warnings: " +
            diagCount + ", expected: 2");
    }
}
 
Example 10
Source File: ErrorHintsProvider.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static long getPrefferedPosition(CompilationInfo info, Diagnostic d) throws IOException {
    if ("compiler.err.doesnt.exist".equals(d.getCode()) || "compiler.err.try.with.resources.expr.needs.var".equals(d.getCode())) {
        return d.getStartPosition();
    }
    if ("compiler.err.cant.resolve.location".equals(d.getCode()) || "compiler.err.cant.resolve.location.args".equals(d.getCode())) {
        int[] span = findUnresolvedElementSpan(info, (int) d.getPosition());
        
        if (span != null) {
            return span[0];
        } else {
            return d.getPosition();
        }
    }
    if ("compiler.err.not.stmt".equals(d.getCode())) {
        //check for "Collections.":
        TreePath path = findUnresolvedElement(info, (int) d.getStartPosition() - 1);
        Element el = path != null ? info.getTrees().getElement(path) : null;
        
        if (el == null || el.asType().getKind() == TypeKind.ERROR) {
            return d.getStartPosition() - 1;
        }
        /*
        if (el.asType().getKind() == TypeKind.PACKAGE) {
            //check if the package does actually exist:
            String s = ((PackageElement) el).getQualifiedName().toString();
            if (info.getElements().getPackageElement(s) == null) {
                //it does not:
                return d.getStartPosition() - 1;
            }
        }
                */
        
        return d.getStartPosition();
    }
    
    return d.getPosition();
}
 
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: 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 13
Source File: T6458823.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    if (compiler == null) {
        throw new RuntimeException("can't get javax.tools.JavaCompiler!");
    }
    DiagnosticCollector<JavaFileObject> diagColl =
        new DiagnosticCollector<JavaFileObject>();
    StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, null);
    List<String> options = new ArrayList<String>();
    options.add("-processor");
    options.add("MyProcessor");
    options.add("-proc:only");
    List<File> files = new ArrayList<File>();
    files.add(new File(T6458823.class.getResource("TestClass.java").toURI()));
    final CompilationTask task = compiler.getTask(null, fm, diagColl,
        options, null, fm.getJavaFileObjectsFromFiles(files));
    task.call();
    int diagCount = 0;
    for (Diagnostic<? extends JavaFileObject> diag : diagColl.getDiagnostics()) {
        if (diag.getKind() != Diagnostic.Kind.WARNING) {
            throw new AssertionError("Only warnings expected");
        }
        System.out.println(diag);
        if (diag.getPosition() == Diagnostic.NOPOS) {
            throw new AssertionError("No position info in message");
        }
        if (diag.getSource() == null) {
            throw new AssertionError("No source info in message");
        }
        diagCount++;
    }
    if (diagCount != 2) {
        throw new AssertionError("unexpected number of warnings: " +
            diagCount + ", expected: 2");
    }
}
 
Example 14
Source File: T6458823.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    if (compiler == null) {
        throw new RuntimeException("can't get javax.tools.JavaCompiler!");
    }
    DiagnosticCollector<JavaFileObject> diagColl =
        new DiagnosticCollector<JavaFileObject>();
    StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, null);
    List<String> options = new ArrayList<String>();
    options.add("-processor");
    options.add("MyProcessor");
    options.add("-proc:only");
    List<File> files = new ArrayList<File>();
    files.add(new File(T6458823.class.getResource("TestClass.java").toURI()));
    final CompilationTask task = compiler.getTask(null, fm, diagColl,
        options, null, fm.getJavaFileObjectsFromFiles(files));
    task.call();
    int diagCount = 0;
    for (Diagnostic<? extends JavaFileObject> diag : diagColl.getDiagnostics()) {
        if (diag.getKind() != Diagnostic.Kind.WARNING) {
            throw new AssertionError("Only warnings expected");
        }
        System.out.println(diag);
        if (diag.getPosition() == Diagnostic.NOPOS) {
            throw new AssertionError("No position info in message");
        }
        if (diag.getSource() == null) {
            throw new AssertionError("No source info in message");
        }
        diagCount++;
    }
    if (diagCount != 2) {
        throw new AssertionError("unexpected number of warnings: " +
            diagCount + ", expected: 2");
    }
}
 
Example 15
Source File: ImplementAllAbstractMethods.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public List<Fix> run(final CompilationInfo info, String diagnosticKey, final int offset, TreePath treePath, Data<Object> data) {
    TreePath path = deepTreePath(info, offset);
    if (path == null) {
        return null;
    }

    Map<Tree, Object> holder = data == null ? null : (Map)data.getData();
    Object saved = null;
    if (holder != null) {
        saved = holder.get(path.getLeaf());
    }
    if (Boolean.TRUE == saved) {
        return null;
    }
    Element e = info.getTrees().getElement(path);
    final Tree leaf = path.getLeaf();
    boolean isUsableElement = e != null && (e.getKind().isClass() || e.getKind().isInterface());
    boolean containsDefaultMethod = saved == Boolean.FALSE;

    boolean completingAnonymous = e != null && e.getKind() == ElementKind.CONSTRUCTOR && 
            leaf.getKind() == Tree.Kind.NEW_CLASS;
    TypeElement tel = findTypeElement(info, path);
    
    if (!Utilities.isValidElement(tel)) {
        return null;
    }
    List<Fix> fixes = new ArrayList<>();
    if (TreeUtilities.CLASS_TREE_KINDS.contains(leaf.getKind()) || leaf.getKind().toString().equals(RECORD)) {
        CompilationUnitTree cut = info.getCompilationUnit();
        // do not offer for class declarations without body
        long start = info.getTrees().getSourcePositions().getStartPosition(cut, leaf);
        long end = info.getTrees().getSourcePositions().getEndPosition(cut, leaf);
        for (Diagnostic d : info.getDiagnostics()) {
            long position = d.getPosition();
            if (d.getCode().equals(PREMATURE_EOF_CODE) && position > start && position < end) {
                return null;
            }
        }
    }
    
    if (completingAnonymous) {
        //if the parent of path.getLeaf is an error, the situation probably is like:
        //new Runnable {}
        //(missing '()' for constructor)
        //do not propose the hint in this case:
        final boolean[] parentError = new boolean[] {false};
        new ErrorAwareTreePathScanner() {
            @Override
            public Object visitNewClass(NewClassTree nct, Object o) {
                if (leaf == nct) {
                    parentError[0] = getCurrentPath().getParentPath().getLeaf().getKind() == Kind.ERRONEOUS;
                }
                return super.visitNewClass(nct, o);
            }
        }.scan(path.getParentPath(), null);
        if (parentError[0]) {
            // ignore
            return null;
        }
        fixes.add(new ImplementAbstractMethodsFix(info, path, tel, containsDefaultMethod));
    }
    boolean someAbstract = false;
    X: if (isUsableElement) {
        for (ExecutableElement ee : ElementFilter.methodsIn(e.getEnclosedElements())) {
            if (ee.getModifiers().contains(Modifier.ABSTRACT)) {
                // make class abstract. In case of enums, suggest to implement the
                // abstract methods on all enum values.
                if (e.getKind() == ElementKind.ENUM) {
                    // cannot make enum abstract, but can generate abstract methods skeleton
                    // to all enum members
                    fixes.add(new ImplementOnEnumValues2(info,  tel, containsDefaultMethod));
                    // avoid other possible fixes:
                    break X;
                } else if (e.getKind().isClass()) {
                    someAbstract = true;
                    break;
                }
            }
        }
        // offer to fix all abstract methods
        if (!someAbstract) {
            fixes.add(new ImplementAbstractMethodsFix(info, path, tel, containsDefaultMethod));
        }
        if (e.getKind() == ElementKind.CLASS && e.getSimpleName() != null && !e.getSimpleName().contentEquals("")) {
            fixes.add(new MakeAbstractFix(info, path, e.getSimpleName().toString()).toEditorFix());
        }
    } 
    if (e != null && e.getKind() == ElementKind.ENUM_CONSTANT) {
        fixes.add(new ImplementAbstractMethodsFix(info, path, tel, containsDefaultMethod));
    }
    return fixes;
}
 
Example 16
Source File: OrganizeImports.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * Performs 'organize imports' in two modes. If 'addImports' is null, it optimizes imports according to coding style.
 * However if addImports is not null && not empty, it will add the elements in addImports, and reorder the set
 * of import statements, but will not remove unused imports.
 * Combination of bulk + addImports is not tested.
 * 
 * @param copy working copy to change
 * @param addImports if not null, just adds and reorders imports. If null, performs optimization
 * @param isBulkMode called from batch processing
 * @throws IllegalStateException 
 */
public static void doOrganizeImports(WorkingCopy copy, Set<Element> addImports, boolean isBulkMode) throws IllegalStateException {
    CompilationUnitTree cu = copy.getCompilationUnit();
    List<? extends ImportTree> imports = cu.getImports();
    if (imports.isEmpty()) {
        if (addImports == null) {
            return;
        }
    } else if (addImports == null) {
        // check diag code only if in the 'optimize all' mode.
        List<Diagnostic> diags = copy.getDiagnostics();
        if (!diags.isEmpty()) {
            SourcePositions sp = copy.getTrees().getSourcePositions();
            long startPos = sp.getStartPosition(cu, imports.get(0));
            long endPos = sp.getEndPosition(cu, imports.get(imports.size() - 1));
            for (Diagnostic d : diags) {
                if (startPos <= d.getPosition() && d.getPosition() <= endPos) {
                    if (ERROR_CODE.contentEquals(d.getCode()))
                        return;
                }
            }
        }
    }
    final CodeStyle cs = CodeStyle.getDefault(copy.getFileObject());
    Set<Element> starImports = new HashSet<Element>();
    Set<Element> staticStarImports = new HashSet<Element>();
    Set<Element> toImport = getUsedElements(copy, cu, starImports, staticStarImports);
    List<ImportTree> imps = new LinkedList<ImportTree>();  
    TreeMaker maker = copy.getTreeMaker();
    
    if (addImports != null) {
        // copy over all imports to be added + existing imports.
        toImport.addAll(addImports);
        imps.addAll(cu.getImports());
    } else if (!toImport.isEmpty() || isBulkMode) {
        // track import star import scopes, so only one star import/scope appears in imps - #251977
        Set<Element> starImportScopes = new HashSet<>();
        Trees trees = copy.getTrees();
        for (ImportTree importTree : cu.getImports()) {
            Tree qualIdent = importTree.getQualifiedIdentifier();
            if (qualIdent.getKind() == Tree.Kind.MEMBER_SELECT && "*".contentEquals(((MemberSelectTree)qualIdent).getIdentifier())) {
                ImportTree imp = null;
                Element importedScope = trees.getElement(TreePath.getPath(cu, ((MemberSelectTree)qualIdent).getExpression()));
                
                if (importTree.isStatic()) {
                    if (staticStarImports != null && 
                        staticStarImports.contains(importedScope) &&
                        !starImportScopes.contains(importedScope)) {
                        imp = maker.Import(qualIdent, true);
                    }
                } else {
                    if (starImports != null && 
                        starImports.contains(importedScope) &&
                        !starImportScopes.contains(importedScope)) {
                        imp = maker.Import(qualIdent, false);
                    }
                }
                if (imp != null) {
                    starImportScopes.add(importedScope);
                    imps.add(imp);
                }
            }
        }
    } else {
        return;
    }
    if (!imps.isEmpty()) {
        Collections.sort(imps, new Comparator<ImportTree>() {

            private CodeStyle.ImportGroups groups = cs.getImportGroups();

            @Override
            public int compare(ImportTree o1, ImportTree o2) {
                if (o1 == o2)
                    return 0;
                String s1 = o1.getQualifiedIdentifier().toString();
                String s2 = o2.getQualifiedIdentifier().toString();
                int bal = groups.getGroupId(s1, o1.isStatic()) - groups.getGroupId(s2, o2.isStatic());
                return bal == 0 ? s1.compareTo(s2) : bal;
            }
        });
    }
    CompilationUnitTree cut = maker.CompilationUnit(cu.getPackageAnnotations(), cu.getPackageName(), imps, cu.getTypeDecls(), cu.getSourceFile());
    ((JCCompilationUnit)cut).packge = ((JCCompilationUnit)cu).packge;
    if (starImports != null || staticStarImports != null) {
        ((JCCompilationUnit)cut).starImportScope = ((JCCompilationUnit)cu).starImportScope;
    }
    CompilationUnitTree ncu = toImport.isEmpty() ? cut : GeneratorUtilities.get(copy).addImports(cut, toImport);
    copy.rewrite(cu, ncu);
}
 
Example 17
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 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;
}