List of usage examples for org.eclipse.jdt.core.compiler IProblem getOriginatingFileName
char[] getOriginatingFileName();
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;//from ww w . j a v a 2s.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 .ja va2s .com 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;/* w w w . j a 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.microsoft.javapkgsrv.JavaParser.java
License:MIT License
public List<Problem> ProcessFileParseMessagesRequest(Integer fileId) { List<FileParseMessagesResponse.Problem> ret = new ArrayList<FileParseMessagesResponse.Problem>(); if (ActiveUnits.containsKey(fileId)) { CompilationUnit cu = ActiveUnits.get(fileId); IProblem[] problems = cu.getProblems(); for (IProblem problem : problems) { System.out.println(problem.toString()); FileParseMessagesResponse.Problem.Builder retProblem = FileParseMessagesResponse.Problem .newBuilder().setId(problem.getID()).setMessage(problem.getMessage()) .setFileName(new String(problem.getOriginatingFileName())) .setScopeStart(problem.getSourceStart()).setScopeEnd(problem.getSourceEnd() + 1) .setLineNumber(problem.getSourceLineNumber()).setProblemType(GetProblemType(problem)); for (String arg : problem.getArguments()) retProblem.addArguments(arg); ret.add(retProblem.build()); }//from w ww .j a v a 2s . c om } return ret; }
From source file:com.tsc9526.monalisa.plugin.eclipse.jdt.ProblemDetail.java
License:Open Source License
private String getDetail(IProblem problem) { StringBuilder sb = new StringBuilder(); String className = new String(problem.getOriginatingFileName()).replace("/", "."); className = className.substring(0, className.length() - 5); String message = problem.getMessage(); if (problem.getID() == IProblem.CannotImportPackage) { message = problem.getArguments()[0] + " cannot be resolved"; }/*from w ww. jav a 2 s .c om*/ sb.append(className + ":" + message + ", Source: "); sb.append("\r\n==============================================\r\n"); int start = problem.getSourceStart(); int end = problem.getSourceEnd(); char[] contents = result.getCompilationUnit().getContents(); if (end > start && start >= 0 && end < contents.length) { int lineOffset = -1; for (int i = 0; i <= start; i++) { if (contents[i] == '\n') { lineOffset = -1; } else { lineOffset++; } } int lineStart = 0; for (int i = start; i < contents.length; i++) { if (contents[i] == '\n') { lineStart = i + 1; break; } } int minEnd = end; for (int i = start; i <= end; i++) { if (contents[i] == '\n') { minEnd = i; break; } } sb.append(new String(contents, 0, lineStart)); for (int i = 0; i < lineOffset; i++) { sb.append(" "); } for (int i = 0; i <= (minEnd - start); i++) { sb.append("^"); } sb.append(" <--- " + message + "\r\n"); sb.append(new String(contents, lineStart, contents.length - lineStart)); } else { sb.append(new String(contents)); } sb.append("\r\n=====================================================\r\n"); return sb.toString(); }
From source file:de.plugins.eclipse.depclipse.testcommons.Util.java
License:Open Source License
public static void appendProblem(StringBuffer problems, IProblem problem, char[] source, int problemCount) { problems.append(problemCount + (problem.isError() ? ". ERROR" : ". WARNING")); problems.append(" in " + new String(problem.getOriginatingFileName())); if (source != null) { problems.append(((DefaultProblem) problem).errorReportSource(source)); }//from w ww .j av a 2 s .com problems.append("\n"); problems.append(problem.getMessage()); problems.append("\n"); }
From source file:edu.brown.cs.bubbles.bedrock.BedrockUtil.java
License:Open Source License
/********************************************************************************/ static void outputProblem(IProject proj, IProblem ip, IvyXmlWriter xw) { xw.begin("PROBLEM"); if (ip instanceof IMarker) { IMarker xmk = (IMarker) ip;//from ww w . j a v a 2 s. c o m xw.field("ID", xmk.getId()); } xw.field("MSGID", ip.getID()); xw.field("MESSAGE", ip.getMessage()); char[] filc = ip.getOriginatingFileName(); if (filc != null) { File fnm = new File(new String(filc)); fnm = getFileForPath(fnm, proj); xw.field("FILE", fnm.getAbsolutePath()); } xw.field("LINE", ip.getSourceLineNumber()); xw.field("START", ip.getSourceStart()); xw.field("END", ip.getSourceEnd()); if (proj != null) xw.field("PROJECT", proj.getName()); if (ip.isError()) xw.field("ERROR", true); else { switch (ip.getID()) { case IProblem.Task: break; default: xw.field("WARNING", true); break; } } for (String s : ip.getArguments()) { xw.textElement("ARG", s); } BedrockPlugin.getPlugin().addFixes(ip, xw); xw.end("PROBLEM"); }
From source file:org.apache.tuscany.maven.compiler.CompilerRequestor.java
License:Apache License
public void acceptResult(CompilationResult result) { boolean hasErrors = false; if (result.hasProblems()) { // Convert JDT IProblems into plexus CompilerErrors for (IProblem problem : result.getProblems()) { if (problem.isWarning()) { if (showWarnings) { compilerErrors.add(new CompilerError(new String(problem.getOriginatingFileName()), false, problem.getSourceLineNumber(), problem.getSourceStart(), problem.getSourceLineNumber(), problem.getSourceEnd(), problem.getMessage())); }//from www . ja v a2 s. c o m } else if (problem.isError()) { hasErrors = true; compilerErrors.add(new CompilerError(new String(problem.getOriginatingFileName()), true, problem.getSourceLineNumber(), problem.getSourceStart(), problem.getSourceLineNumber(), problem.getSourceEnd(), problem.getMessage())); } } } // Write the class files if (!hasErrors) { ClassFile[] classFiles = result.getClassFiles(); for (ClassFile classFile : classFiles) { // Create file and parent directories StringBuffer className = new StringBuffer(); for (char[] name : classFile.getCompoundName()) { if (className.length() != 0) { className.append('.'); } className.append(name); } File file = new File(outputDirectory, className.toString().replace('.', '/') + ".class"); if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); } // Write class file contents FileOutputStream fos = null; try { fos = new FileOutputStream(file); fos.write(classFile.getBytes()); } catch (FileNotFoundException e) { throw new IllegalArgumentException(e); } catch (IOException e) { throw new IllegalArgumentException(e); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { } } } } } }
From source file:org.codehaus.plexus.compiler.eclipse.EclipseJavaCompiler.java
License:Open Source License
private CompilerError handleWarning(IProblem warning) { return new CompilerError(new String(warning.getOriginatingFileName()), false, warning.getSourceLineNumber(), warning.getSourceStart(), warning.getSourceLineNumber(), warning.getSourceEnd(), warning.getMessage());/*from w w w . j a v a 2 s. c o m*/ }
From source file:org.eclim.plugin.jdt.command.complete.CompletionProposalCollector.java
License:Open Source License
public void completionFailure(IProblem problem) { ICompilationUnit src = getCompilationUnit(); IJavaProject javaProject = src.getJavaProject(); IProject project = javaProject.getProject(); // undefined type or attempting to complete static members of an unimported // type/* w ww . jav a 2s. c om*/ if (problem.getID() == IProblem.UndefinedType || problem.getID() == IProblem.UnresolvedVariable) { try { SearchPattern pattern = SearchPattern.createPattern(problem.getArguments()[0], IJavaSearchConstants.TYPE, IJavaSearchConstants.DECLARATIONS, SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE); IJavaSearchScope scope = SearchEngine.createJavaSearchScope(new IJavaElement[] { javaProject }); SearchRequestor requestor = new SearchRequestor(); SearchEngine engine = new SearchEngine(); SearchParticipant[] participants = new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() }; engine.search(pattern, participants, scope, requestor, null); if (requestor.getMatches().size() > 0) { imports = new ArrayList<String>(); for (SearchMatch match : requestor.getMatches()) { if (match.getAccuracy() != SearchMatch.A_ACCURATE) { continue; } IJavaElement element = (IJavaElement) match.getElement(); String name = null; switch (element.getElementType()) { case IJavaElement.TYPE: IType type = (IType) element; if (Flags.isPublic(type.getFlags())) { name = type.getFullyQualifiedName(); } break; case IJavaElement.METHOD: case IJavaElement.FIELD: name = ((IType) element.getParent()).getFullyQualifiedName() + '.' + element.getElementName(); break; } if (name != null) { name = name.replace('$', '.'); if (!ImportUtils.isImportExcluded(project, name)) { imports.add(name); } } } } } catch (Exception e) { throw new RuntimeException(e); } } IResource resource = src.getResource(); String relativeName = resource.getProjectRelativePath().toString(); if (new String(problem.getOriginatingFileName()).endsWith(relativeName)) { String filename = resource.getLocation().toString(); // ignore the problem if a temp file is being used and the problem is that // the type needs to be defined in its own file. if (problem.getID() == IProblem.PublicClassMustMatchFileName && filename.indexOf("__eclim_temp_") != -1) { return; } FileOffsets offsets = FileOffsets.compile(filename); int[] lineColumn = offsets.offsetToLineColumn(problem.getSourceStart()); error = new Error(problem.getMessage(), filename.replace("__eclim_temp_", ""), lineColumn[0], lineColumn[1], problem.isWarning()); } }