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

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

Introduction

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

Prototype

String getMessage();

Source Link

Document

Answer a localized, human-readable message string which describes the problem.

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);//w ww  .j ava 2s. 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;// ww w . ja v a2 s  .  c  o 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  ww  w . j  a va2 s  .c  o  m*/
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.ja v  a  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.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;
            }/*w  w  w .  ja  v  a 2 s .  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. jav a2 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);//  w  w w .j  a  v a2 s . co 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.j2objc.J2ObjC.java

License:Open Source License

private static CompilationUnit parse(String filename, String source) {
    logger.finest("parsing " + filename);
    ASTParser parser = ASTParser.newParser(AST.JLS4);
    Map<String, String> compilerOptions = Options.getCompilerOptions();
    parser.setCompilerOptions(compilerOptions);
    parser.setSource(source.toCharArray());
    parser.setResolveBindings(true);/*from w  ww  . j  a  v  a  2 s.  c  om*/
    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.j2objc.jdt.JdtParser.java

License:Apache License

private boolean checkCompilationErrors(String filename, CompilationUnit unit) {
    boolean hasErrors = false;
    for (IProblem problem : unit.getProblems()) {
        if (problem.isError()) {
            ErrorUtil.error(// www . ja  va 2s.c  o  m
                    String.format("%s:%s: %s", filename, problem.getSourceLineNumber(), problem.getMessage()));
            hasErrors = true;
        }
        if (problem.isWarning()) {
            ErrorUtil.warning(String.format("%s:%s: warning: %s", filename, problem.getSourceLineNumber(),
                    problem.getMessage()));
        }
    }
    return !hasErrors;
}

From source file:com.google.devtools.j2objc.util.JdtParser.java

License:Apache License

private boolean checkCompilationErrors(String filename, CompilationUnit unit) {
    boolean hasErrors = false;
    for (IProblem problem : unit.getProblems()) {
        if (problem.isError()) {
            ErrorUtil.error(/*from ww w. ja  va2 s. c  o  m*/
                    String.format("%s:%s: %s", filename, problem.getSourceLineNumber(), problem.getMessage()));
            hasErrors = true;
        }
    }
    return !hasErrors;
}