Example usage for org.eclipse.jdt.core.compiler IProblem isError

List of usage examples for org.eclipse.jdt.core.compiler IProblem isError

Introduction

In this page you can find the example usage for org.eclipse.jdt.core.compiler IProblem isError.

Prototype

boolean isError();

Source Link

Document

Returns whether the severity of this problem is 'Error'.

Usage

From source file:at.bestsolution.javafx.ide.jdt.internal.JavaEditor.java

License:Open Source License

@Inject
public JavaEditor(BorderPane pane, IEditorInput input) {
    editor = new SourceEditor();
    pane.setCenter(editor);/*  ww w.  ja v  a 2  s  .  c o m*/

    IResourceFileInput fsInput = (IResourceFileInput) input;
    try {
        unit = ((ICompilationUnit) JavaCore.create(fsInput.getFile()))
                .getWorkingCopy(new FXWorkingCopyOwner(new IProblemRequestor() {
                    private List<ProblemMarker> l = new ArrayList<>();

                    @Override
                    public boolean isActive() {
                        // TODO Auto-generated method stub
                        return true;
                    }

                    @Override
                    public void endReporting() {
                        setMarkers(l);
                    }

                    @Override
                    public void beginReporting() {
                        l.clear();
                    }

                    @Override
                    public void acceptProblem(IProblem problem) {
                        int linenumber = problem.getSourceLineNumber();
                        int startCol = problem.getSourceStart();
                        int endCol = problem.getSourceEnd();

                        if (endCol == startCol) {
                            endCol++;
                        }

                        String description = problem.getMessage();
                        ProblemMarker marker = new ProblemMarker(
                                problem.isError() ? at.bestsolution.javafx.ide.editor.ProblemMarker.Type.ERROR
                                        : at.bestsolution.javafx.ide.editor.ProblemMarker.Type.WARNING,
                                linenumber, startCol, endCol, description);
                        l.add(marker);
                    }
                }), new NullProgressMonitor());
    } catch (JavaModelException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    final Document doc = createDocument(unit);
    editor.setDocument(doc);
    editor.setContentProposalComputer(new ContentProposalComputer() {

        @Override
        public List<Proposal> computeProposals(String line, String prefix, int offset) {
            final List<Proposal> l = new ArrayList<ContentProposalComputer.Proposal>();

            try {
                unit.codeComplete(offset, new CompletionRequestor() {

                    @Override
                    public void accept(CompletionProposal proposal) {
                        String completion = new String(proposal.getCompletion());

                        if (!Flags.isPublic(proposal.getFlags())) {
                            return;
                        }

                        if (proposal.getKind() == CompletionProposal.METHOD_REF) {
                            String sig = Signature.toString(new String(proposal.getSignature()),
                                    new String(proposal.getName()), null, false, false);
                            StyledString s = new StyledString(sig + " : " + Signature.getSimpleName(Signature
                                    .toString(Signature.getReturnType(new String(proposal.getSignature())))));
                            s.appendString(
                                    " - " + Signature.getSignatureSimpleName(
                                            new String(proposal.getDeclarationSignature())),
                                    Style.colored("#AAAAAA"));

                            l.add(new Proposal(Type.METHOD, completion, s));
                        } else if (proposal.getKind() == CompletionProposal.FIELD_REF) {
                            StyledString s = new StyledString(
                                    completion + " : "
                                            + (proposal.getSignature() != null
                                                    ? Signature.getSignatureSimpleName(
                                                            new String(proposal.getSignature()))
                                                    : "<unknown>"));
                            s.appendString(
                                    " - " + (proposal.getDeclarationSignature() != null
                                            ? Signature.getSignatureSimpleName(
                                                    new String(proposal.getDeclarationSignature()))
                                            : "<unknown>"),
                                    Style.colored("#AAAAAA"));
                            l.add(new Proposal(Type.FIELD, completion, s));
                        } else if (proposal.getKind() == CompletionProposal.TYPE_REF) {
                            if (proposal.getAccessibility() == IAccessRule.K_NON_ACCESSIBLE) {
                                return;
                            }

                            StyledString s = new StyledString(
                                    Signature.getSignatureSimpleName(new String(proposal.getSignature())));
                            s.appendString(" - " + new String(proposal.getDeclarationSignature()),
                                    Style.colored("#AAAAAA"));
                            l.add(new Proposal(Type.TYPE, new String(proposal.getCompletion()), s));
                        } else {
                            System.err.println(proposal);
                        }
                    }
                });
            } catch (JavaModelException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return l;
        }

    });
    editor.setSaveCallback(new Runnable() {

        @Override
        public void run() {
            try {
                unit.commitWorkingCopy(true, null);
            } catch (JavaModelException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    });

    try {
        unit.reconcile(ICompilationUnit.NO_AST, true, null, null);
    } catch (JavaModelException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:com.android.build.gradle.tasks.annotations.ExtractAnnotationsDriver.java

License:Apache License

@SuppressWarnings("MethodMayBeStatic")
public void run(@NonNull String[] args) {
    List<String> classpath = Lists.newArrayList();
    List<File> sources = Lists.newArrayList();
    List<File> mergePaths = Lists.newArrayList();
    List<File> apiFilters = null;
    File rmTypeDefs = null;/*  w w  w. j  a va  2 s.  co m*/
    boolean verbose = true;
    boolean allowMissingTypes = false;
    boolean allowErrors = false;
    boolean listFiltered = true;
    boolean skipClassRetention = false;

    String encoding = Charsets.UTF_8.name();
    File output = null;
    File proguard = null;
    long languageLevel = EcjParser.getLanguageLevel(1, 7);
    if (args.length == 1 && "--help".equals(args[0])) {
        usage(System.out);
    }
    if (args.length < 2) {
        usage(System.err);
    }
    for (int i = 0, n = args.length; i < n; i++) {
        String flag = args[i];

        if (flag.equals("--quiet")) {
            verbose = false;
            continue;
        } else if (flag.equals("--allow-missing-types")) {
            allowMissingTypes = true;
            continue;
        } else if (flag.equals("--allow-errors")) {
            allowErrors = true;
            continue;
        } else if (flag.equals("--hide-filtered")) {
            listFiltered = false;
            continue;
        } else if (flag.equals("--skip-class-retention")) {
            skipClassRetention = true;
            continue;
        }
        if (i == n - 1) {
            usage(System.err);
        }
        String value = args[i + 1];
        i++;

        if (flag.equals("--sources")) {
            sources = getFiles(value);
        } else if (flag.equals("--classpath")) {
            classpath = getPaths(value);
        } else if (flag.equals("--merge-zips")) {
            mergePaths = getFiles(value);
        } else if (flag.equals("--output")) {
            output = new File(value);
            if (output.exists()) {
                if (output.isDirectory()) {
                    abort(output + " is a directory");
                }
                boolean deleted = output.delete();
                if (!deleted) {
                    abort("Could not delete previous version of " + output);
                }
            } else if (output.getParentFile() != null && !output.getParentFile().exists()) {
                abort(output.getParentFile() + " does not exist");
            }
        } else if (flag.equals("--proguard")) {
            proguard = new File(value);
            if (proguard.exists()) {
                if (proguard.isDirectory()) {
                    abort(proguard + " is a directory");
                }
                boolean deleted = proguard.delete();
                if (!deleted) {
                    abort("Could not delete previous version of " + proguard);
                }
            } else if (proguard.getParentFile() != null && !proguard.getParentFile().exists()) {
                abort(proguard.getParentFile() + " does not exist");
            }
        } else if (flag.equals("--encoding")) {
            encoding = value;
        } else if (flag.equals("--api-filter")) {
            if (apiFilters == null) {
                apiFilters = Lists.newArrayList();
            }
            for (String path : Splitter.on(",").omitEmptyStrings().split(value)) {
                File apiFilter = new File(path);
                if (!apiFilter.isFile()) {
                    String message = apiFilter + " does not exist or is not a file";
                    abort(message);
                }
                apiFilters.add(apiFilter);
            }
        } else if (flag.equals("--language-level")) {
            if ("1.6".equals(value)) {
                languageLevel = EcjParser.getLanguageLevel(1, 6);
            } else if ("1.7".equals(value)) {
                languageLevel = EcjParser.getLanguageLevel(1, 7);
            } else {
                abort("Unsupported language level " + value);
            }
        } else if (flag.equals("--rmtypedefs")) {
            rmTypeDefs = new File(value);
            if (!rmTypeDefs.isDirectory()) {
                abort(rmTypeDefs + " is not a directory");
            }
        } else {
            System.err.println("Unknown flag " + flag + ": Use --help for usage information");
        }
    }

    if (sources.isEmpty()) {
        abort("Must specify at least one source path");
    }
    if (classpath.isEmpty()) {
        abort("Must specify classpath pointing to at least android.jar or the framework");
    }
    if (output == null && proguard == null) {
        abort("Must specify output path with --output or a proguard path with --proguard");
    }

    // API definition files
    ApiDatabase database = null;
    if (apiFilters != null && !apiFilters.isEmpty()) {
        try {
            List<String> lines = Lists.newArrayList();
            for (File file : apiFilters) {
                lines.addAll(Files.readLines(file, Charsets.UTF_8));
            }
            database = new ApiDatabase(lines);
        } catch (IOException e) {
            abort("Could not open API database " + apiFilters + ": " + e.getLocalizedMessage());
        }
    }

    Extractor extractor = new Extractor(database, rmTypeDefs, verbose, !skipClassRetention, true);
    extractor.setListIgnored(listFiltered);

    try {
        Pair<Collection<CompilationUnitDeclaration>, INameEnvironment> pair = parseSources(sources, classpath,
                encoding, languageLevel);
        Collection<CompilationUnitDeclaration> units = pair.getFirst();

        boolean abort = false;
        int errorCount = 0;
        for (CompilationUnitDeclaration unit : units) {
            // so maybe I don't need my map!!
            IProblem[] problems = unit.compilationResult().getAllProblems();
            if (problems != null) {
                for (IProblem problem : problems) {
                    if (problem.isError()) {
                        errorCount++;
                        String message = problem.getMessage();
                        if (allowMissingTypes) {
                            if (message.contains("cannot be resolved")) {
                                continue;
                            }
                        }

                        System.out.println("Error: " + new String(problem.getOriginatingFileName()) + ":"
                                + problem.getSourceLineNumber() + ": " + message);
                        abort = !allowErrors;
                    }
                }
            }
        }
        if (errorCount > 0) {
            System.err.println("Found " + errorCount + " errors");
        }
        if (abort) {
            abort("Not extracting annotations (compilation problems encountered)");
        }

        INameEnvironment environment = pair.getSecond();
        extractor.extractFromProjectSource(units);

        if (mergePaths != null) {
            for (File jar : mergePaths) {
                extractor.mergeExisting(jar);
            }
        }

        extractor.export(output, proguard);

        // Remove typedefs?
        //noinspection VariableNotUsedInsideIf
        if (rmTypeDefs != null) {
            extractor.removeTypedefClasses();
        }

        environment.cleanup();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.android.build.gradle.tasks.ExtractAnnotations.java

License:Apache License

@Override
@TaskAction//from   w ww . java2s. c  om
protected void compile() {
    if (!hasAndroidAnnotations()) {
        return;
    }

    if (encoding == null) {
        encoding = UTF_8;
    }

    EcjParser.EcjResult result = parseSources();
    Collection<CompilationUnitDeclaration> parsedUnits = result.getCompilationUnits();

    try {
        if (!allowErrors) {
            for (CompilationUnitDeclaration unit : parsedUnits) {
                // so maybe I don't need my map!!
                CategorizedProblem[] problems = unit.compilationResult().getAllProblems();
                for (IProblem problem : problems) {
                    if (problem.isError()) {
                        getLogger().warn("Not extracting annotations (compilation problems " + "encountered)\n"
                                + "Error: " + new String(problem.getOriginatingFileName()) + ":"
                                + problem.getSourceLineNumber() + ": " + problem.getMessage());
                        // TODO: Consider whether we abort the build at this point!
                        return;
                    }
                }
            }
        }

        // API definition file
        ApiDatabase database = null;
        if (apiFilter != null && apiFilter.exists()) {
            try {
                database = new ApiDatabase(apiFilter);
            } catch (IOException e) {
                throw new BuildException("Could not open API database " + apiFilter, e);
            }
        }

        boolean displayInfo = getProject().getLogger().isEnabled(LogLevel.INFO);

        Extractor extractor = new Extractor(database, classDir, displayInfo,
                false /*includeClassRetentionAnnotations*/, false /*sortAnnotations*/);
        extractor.extractFromProjectSource(parsedUnits);
        if (mergeJars != null) {
            for (File jar : mergeJars) {
                extractor.mergeExisting(jar);
            }
        }
        extractor.export(output, proguard);
        if (typedefFile != null) {
            extractor.writeTypedefFile(typedefFile);
        } else {
            extractor.removeTypedefClasses();
        }
    } finally {
        result.dispose();
    }
}

From source file:com.android.tools.lint.EcjParser.java

License:Apache License

@Override
public void prepareJavaParse(@NonNull final List<JavaContext> contexts) {
    if (mProject == null || contexts.isEmpty()) {
        return;/*from   w  w  w. j  a  va  2 s  .  c o m*/
    }

    List<ICompilationUnit> sources = Lists.newArrayListWithExpectedSize(contexts.size());
    mSourceUnits = Maps.newHashMapWithExpectedSize(sources.size());
    for (JavaContext context : contexts) {
        String contents = context.getContents();
        if (contents == null) {
            continue;
        }
        File file = context.file;
        CompilationUnit unit = new CompilationUnit(contents.toCharArray(), file.getPath(), UTF_8);
        sources.add(unit);
        mSourceUnits.put(file, unit);
    }
    List<String> classPath = computeClassPath(contexts);
    mCompiled = Maps.newHashMapWithExpectedSize(mSourceUnits.size());
    try {
        mEnvironment = parse(createCompilerOptions(), sources, classPath, mCompiled, mClient);
    } catch (Throwable t) {
        mClient.log(t, "ECJ compiler crashed");
    }

    if (DEBUG_DUMP_PARSE_ERRORS) {
        for (CompilationUnitDeclaration unit : mCompiled.values()) {
            // so maybe I don't need my map!!
            CategorizedProblem[] problems = unit.compilationResult().getAllProblems();
            if (problems != null) {
                for (IProblem problem : problems) {
                    if (problem == null || !problem.isError()) {
                        continue;
                    }
                    System.out.println(new String(problem.getOriginatingFileName()) + ":"
                            + (problem.isError() ? "Error" : "Warning") + ": " + problem.getSourceLineNumber()
                            + ": " + problem.getMessage());
                }
            }
        }
    }
}

From source file:com.bsiag.eclipse.jdt.java.formatter.DefaultCodeFormatter.java

License:Open Source License

private ASTNode parseSourceCode(ASTParser parser, int parserMode, boolean ignoreErrors) {
    parser.setKind(parserMode);//from  www  .java2  s. c  om
    parser.setSource(this.sourceArray);
    ASTNode astNode = parser.createAST(null);
    if (ignoreErrors)
        return astNode;

    boolean hasErrors = false;
    CompilationUnit root = (CompilationUnit) astNode.getRoot();
    for (IProblem problem : root.getProblems()) {
        if (problem.isError()) {
            hasErrors = true;
            break;
        }
    }
    return hasErrors ? null : astNode;
}

From source file:com.crispico.flower.mp.metamodel.codesyncjava.algorithm.reverse.ReversePackage_JavaTypes.java

License:Open Source License

/**
 * @author Sorin//w  w  w. j a  v a 2  s. c o  m
 * @author Mariana
 */
@Override
protected Object getLookupKeyForAstElement(FileAndAST<CompilationUnit> e) throws ParsingException {
    if (e != null) {
        // if the file name contains white spaces, an error is thrown
        String onlyFileName = SyncUtils.getOnlyNameFromFile(e.getFile());
        if (onlyFileName.contains(" ")) {
            throw new RuntimeException("The name of the file " + onlyFileName + " contains invalid characters");
        }

        if (e.getAstElement() == null) {
            try {
                ASTParser parser = ASTParser.newParser(AST.JLS3);
                parser.setKind(ASTParser.K_COMPILATION_UNIT);
                e.setAstElement(JavaSyncUtils.loadJavaFile(e.getFile(), parser));
            } catch (Exception ex) {
                throw new RuntimeException("Could not load Java file " + e.getFile().getFullPath(), ex);
            }
        }

        if (e.getAstElement().getProblems().length > 0) {
            StringBuilder cause = new StringBuilder();
            IProblem[] problems = e.getAstElement().getProblems();

            for (int i = 0; i < problems.length; i++) {
                IProblem problem = problems[i];
                if (problem.isError()) {
                    cause.append(problems[i].getMessage() + " - at line " + problems[i].getSourceLineNumber()
                            + ((i + 1 < problems.length) ? "\n" : ""));
                }
            }
            if (cause.length() > 0) { // ignore warnings
                throw new ParsingException(e.getFile(), cause.toString());
            }
        }
        // If the path from source file differs from the type's package hierarchy,
        // we will throw a parsing exception because probably the user chose an inner folder of a source directory
        // when creating the model.
        if (e.getAstElement().getPackage() != null) {
            String pckFileName = e.getAstElement().getPackage().getName().getFullyQualifiedName();
            String pckTypeName = SyncUtils.getFullyQualifiedPackageName(this.getParent().getSrcDirPackage(),
                    e.getFile());
            if (pckFileName != null && !pckTypeName.equals(pckFileName)) {
                throw new ParsingException(e.getFile(), "The path of the file " + onlyFileName
                        + " does not match type's package hierarchy " + pckTypeName);
            }
        }

        // Temporary solution to filter out enum and annotation types
        try {
            String instanceType = JavaSyncUtils.getMasterClass(e.getAstElement()).isInterface() ? "interface"
                    : "class";
            return instanceType + " " + JavaSyncUtils.getMasterClass(e.getAstElement()).getName().toString();
        } catch (ClassCastException exception) {
            return null;
        } catch (IllegalStateException exception) {
            // special case: package-info.java => don't create a model element
            if (SyncUtils.getOnlyNameFromFile(e.getFile()).equals("package-info")) {
                return null;
            }

            // throwing a parsing exception will cause a dummy type to be created with the same name as the file; this type will not be synchronized
            throw new ParsingException(e.getFile(), "No type declaration");
        }
    } else
        return null;
}

From source file:com.facebook.nuclide.debugger.EvaluationManager.java

License:Open Source License

private String checkUnitForProblems(CompilationUnit unit) {
    final IProblem[] problems = unit.getProblems();
    final StringBuilder errors = new StringBuilder();
    int realProblemCount = 0;

    if (problems.length > 0) {
        for (IProblem problem : problems) {
            if (!problem.isError()) {
                // Ignore anything that's not error severity.
                continue;
            }//ww  w  .jav a 2s. c o  m

            int problemId = problem.getID();

            // These problems do not need to stop the parse.
            // NOTE: List taken from Eclipse reference impl.
            if (problemId == IProblem.VoidMethodReturnsValue || problemId == IProblem.NotVisibleMethod
                    || problemId == IProblem.NotVisibleConstructor || problemId == IProblem.NotVisibleField
                    || problemId == IProblem.NotVisibleType || problemId == IProblem.ImportNotFound
                    || problemId == IProblem.UndefinedType || problemId == IProblem.BodyForAbstractMethod) {

                continue;
            }

            realProblemCount++;
            if (realProblemCount == 1) {
                errors.append("Unable to evaluate expression: ");
            }

            errors.append(problem.getMessage());
            errors.append("\n");
        }

        // We couldn't parse the specified expression.
        // Throw the error messages back to the debugger frontend.
        if (realProblemCount > 0) {
            return errors.toString().trim();
        }
    }

    return null;
}

From source file:com.google.devtools.j2cpp.GenerationTest.java

License:Open Source License

/**
 * Asserts that a compilation unit is error-free.
 *//*from  w ww  .  j a  va 2 s.  c o  m*/
protected void assertNoCompilationErrors(CompilationUnit unit) {
    for (IProblem problem : unit.getProblems()) {
        assertFalse(problem.getMessage(), problem.isError());
    }
}

From source file:com.google.devtools.j2cpp.J2ObjC.java

License:Open Source License

private static CompilationUnit parse(String filename, String source) {
    logger.finest("parsing " + filename);
    ASTParser parser = ASTParser.newParser(AST.JLS3);
    Map<String, String> compilerOptions = Options.getCompilerOptions();
    parser.setCompilerOptions(compilerOptions);
    parser.setSource(source.toCharArray());
    parser.setResolveBindings(true);/*from  w  w w .  j av a 2s . c o m*/
    setPaths(parser);
    parser.setUnitName(filename);
    CompilationUnit unit = (CompilationUnit) parser.createAST(null);

    for (IProblem problem : getCompilationErrors(unit)) {
        if (problem.isError()) {
            error(String.format("%s:%s: %s", filename, problem.getSourceLineNumber(), problem.getMessage()));
        }
    }
    return unit;
}

From source file:com.google.devtools.j2cpp.J2ObjC.java

License:Open Source License

private static List<IProblem> getCompilationErrors(CompilationUnit unit) {
    List<IProblem> errors = Lists.newArrayList();
    for (IProblem problem : unit.getProblems()) {
        if (problem.isError()) {
            if (((problem.getID() & IProblem.ImportRelated) > 0) && Options.ignoreMissingImports()) {
                continue;
            } else {
                errors.add(problem);//from  w w  w.ja  va  2  s. c  om
            }
        }
    }
    return errors;
}