com.android.tools.lint.detector.api.Location Java Examples
The following examples show how to use
com.android.tools.lint.detector.api.Location.
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: TodoDetector.java From Android-Lint-Checks with Apache License 2.0 | 6 votes |
@Override public AstVisitor createJavaVisitor(@NonNull JavaContext context) { String source = context.getContents(); // Check validity of source if (source == null) { return null; } // Check for uses of to-dos int index = source.indexOf(TODO_MATCHER_STRING); for (int i = index; i >= 0; i = source.indexOf(TODO_MATCHER_STRING, i + 1)) { Location location = Location.create(context.file, source, i, i + TODO_MATCHER_STRING.length()); context.report(ISSUE, location, ISSUE.getBriefDescription(TextFormat.TEXT)); } return null; }
Example #2
Source File: ManifestDetector.java From javaide with GNU General Public License v3.0 | 6 votes |
@Override public void afterCheckFile(@NonNull Context context) { XmlContext xmlContext = (XmlContext) context; Element element = xmlContext.document.getDocumentElement(); if (element != null) { checkDocumentElement(xmlContext, element); } if (mSeenUsesSdk == 0 && context.isEnabled(USES_SDK) // Not required in Gradle projects; typically defined in build.gradle instead // and inserted at build time && !context.getMainProject().isGradleProject()) { context.report(USES_SDK, Location.create(context.file), "Manifest should specify a minimum API level with " + "`<uses-sdk android:minSdkVersion=\"?\" />`; if it really supports " + "all versions of Android set it to 1."); } }
Example #3
Source File: HandlerDetector.java From javaide with GNU General Public License v3.0 | 6 votes |
@Override public void checkClass(@NonNull JavaContext context, @Nullable ClassDeclaration declaration, @NonNull Node node, @NonNull ResolvedClass cls) { if (!isInnerClass(declaration)) { return; } if (isStaticClass(declaration)) { return; } // Only flag handlers using the default looper if (hasLooperConstructorParameter(cls)) { return; } Node locationNode = node instanceof ClassDeclaration ? ((ClassDeclaration) node).astName() : node; Location location = context.getLocation(locationNode); context.report(ISSUE, locationNode, location, String.format( "This Handler class should be static or leaks might occur (%1$s)", cls.getName())); }
Example #4
Source File: MergeRootFrameLayoutDetector.java From javaide with GNU General Public License v3.0 | 6 votes |
@Override public void afterCheckProject(@NonNull Context context) { if (mPending != null && mWhitelistedLayouts != null) { // Process all the root FrameLayouts that are eligible, and generate // suggestions for <merge> replacements for any layouts that are included // from other layouts for (Pair<String, Handle> pair : mPending) { String layout = pair.getFirst(); if (mWhitelistedLayouts.contains(layout)) { Handle handle = pair.getSecond(); Object clientData = handle.getClientData(); if (clientData instanceof Node) { if (context.getDriver().isSuppressed(null, ISSUE, (Node) clientData)) { return; } } Location location = handle.resolve(); context.report(ISSUE, location, "This `<FrameLayout>` can be replaced with a `<merge>` tag"); } } } }
Example #5
Source File: PrivateKeyDetector.java From javaide with GNU General Public License v3.0 | 6 votes |
@Override public void run(@NonNull Context context) { if (!context.getProject().getReportIssues()) { // If this is a library project not being analyzed, ignore it return; } File file = context.file; if (isPrivateKeyFile(file)) { String fileName = file.getParentFile().getName() + File.separator + file.getName(); String message = String.format( "The `%1$s` file seems to be a private key file. " + "Please make sure not to embed this in your APK file.", fileName); context.report(ISSUE, Location.create(file), message); } }
Example #6
Source File: TranslationDetector.java From javaide with GNU General Public License v3.0 | 6 votes |
private void reportMap(Context context, Issue issue, Map<String, Location> map) { if (map != null) { for (Map.Entry<String, Location> entry : map.entrySet()) { Location location = entry.getValue(); String name = entry.getKey(); String message = mDescriptions.get(name); if (location == null) { location = Location.create(context.getProject().getDir()); } // We were prepending locations, but we want to prefer the base folders location = Location.reverse(location); context.report(issue, location, message); } } }
Example #7
Source File: WebViewDetector.java From javaide with GNU General Public License v3.0 | 6 votes |
@Override public void visitElement(@NonNull XmlContext context, @NonNull Element element) { Node parentNode = element.getParentNode(); if (parentNode != null && parentNode.getNodeType() == Node.ELEMENT_NODE) { Element parent = (Element)parentNode; Attr width = parent.getAttributeNodeNS(ANDROID_URI, ATTR_LAYOUT_WIDTH); Attr height = parent.getAttributeNodeNS(ANDROID_URI, ATTR_LAYOUT_HEIGHT); Attr attr = null; if (width != null && VALUE_WRAP_CONTENT.equals(width.getValue())) { attr = width; } if (height != null && VALUE_WRAP_CONTENT.equals(height.getValue())) { attr = height; } if (attr != null) { String message = String.format("Placing a `<WebView>` in a parent element that " + "uses a `wrap_content %1$s` can lead to subtle bugs; use `match_parent` " + "instead", attr.getLocalName()); Location location = context.getLocation(element); Location secondary = context.getLocation(attr); secondary.setMessage("`wrap_content` here may not work well with WebView below"); location.setSecondary(secondary); context.report(ISSUE, element, location, message); } } }
Example #8
Source File: ApiDetector.java From javaide with GNU General Public License v3.0 | 6 votes |
private void checkExtendsClass(ClassContext context, ClassNode classNode, int classMinSdk, String signature) { int api = mApiDatabase.getClassVersion(signature); if (api > classMinSdk) { String fqcn = ClassContext.getFqcn(signature); String message = String.format( "Class requires API level %1$d (current min is %2$d): `%3$s`", api, classMinSdk, fqcn); String name = signature.substring(signature.lastIndexOf('/') + 1); name = name.substring(name.lastIndexOf('$') + 1); SearchHints hints = SearchHints.create(BACKWARD).matchJavaSymbol(); int lineNumber = ClassContext.findLineNumber(classNode); Location location = context.getLocationForLine(lineNumber, name, null, hints); context.report(UNSUPPORTED, location, message); } }
Example #9
Source File: MissingClassDetector.java From javaide with GNU General Public License v3.0 | 6 votes |
private static void checkInnerClass(XmlContext context, Element element, String pkg, Node classNameNode, String className) { if (pkg != null && className.indexOf('$') == -1 && className.indexOf('.', 1) > 0) { boolean haveUpperCase = false; for (int i = 0, n = pkg.length(); i < n; i++) { if (Character.isUpperCase(pkg.charAt(i))) { haveUpperCase = true; break; } } if (!haveUpperCase) { String fixed = className.charAt(0) + className.substring(1).replace('.','$'); String message = "Use '$' instead of '.' for inner classes " + "(or use only lowercase letters in package names); replace \"" + className + "\" with \"" + fixed + "\""; Location location = context.getLocation(classNameNode); context.report(INNERCLASS, element, location, message); } } }
Example #10
Source File: LayoutConsistencyDetector.java From javaide with GNU General Public License v3.0 | 6 votes |
@Override public void visitDocument(@NonNull XmlContext context, @NonNull Document document) { Element root = document.getDocumentElement(); if (root != null) { if (context.getPhase() == 1) { // Map from ids to types Map<String,String> fileMap = Maps.newHashMapWithExpectedSize(10); addIds(root, fileMap); getFileMapList(context).add(Pair.of(context.file, fileMap)); } else { String name = LintUtils.getLayoutName(context.file); Map<String, List<Location>> map = mLocations.get(name); if (map != null) { lookupLocations(context, root, map); } } } }
Example #11
Source File: LintCliXmlParser.java From javaide with GNU General Public License v3.0 | 6 votes |
@Override @NonNull public Location getNameLocation(@NonNull XmlContext context, @NonNull Node node) { Location location = getLocation(context, node); Position start = location.getStart(); Position end = location.getEnd(); if (start == null || end == null) { return location; } int delta = node instanceof Element ? 1 : 0; // Elements: skip "<" int length = node.getNodeName().length(); int startOffset = start.getOffset() + delta; int startColumn = start.getColumn() + delta; return Location.create(location.getFile(), new DefaultPosition(start.getLine(), startColumn, startOffset), new DefaultPosition(end.getLine(), startColumn + length, startOffset + length)); }
Example #12
Source File: ResourcePrefixDetector.java From javaide with GNU General Public License v3.0 | 6 votes |
@Override public void beforeCheckFile(@NonNull Context context) { if (mPrefix != null && context instanceof XmlContext) { XmlContext xmlContext = (XmlContext) context; ResourceFolderType folderType = xmlContext.getResourceFolderType(); if (folderType != null && folderType != ResourceFolderType.VALUES) { String name = LintUtils.getBaseName(context.file.getName()); if (!name.startsWith(mPrefix)) { // Attempt to report the error on the root tag of the associated // document to make suppressing the error with a tools:suppress // attribute etc possible if (xmlContext.document != null) { Element root = xmlContext.document.getDocumentElement(); if (root != null) { xmlContext.report(ISSUE, root, xmlContext.getLocation(root), getErrorMessage(name)); return; } } context.report(ISSUE, Location.create(context.file), getErrorMessage(name)); } } } }
Example #13
Source File: OnClickDetector.java From javaide with GNU General Public License v3.0 | 5 votes |
@Override public void afterCheckProject(@NonNull Context context) { if (mNames != null && !mNames.isEmpty() && mHaveBytecode) { List<String> names = new ArrayList<String>(mNames.keySet()); Collections.sort(names); LintDriver driver = context.getDriver(); for (String name : names) { Handle handle = mNames.get(name); Object clientData = handle.getClientData(); if (clientData instanceof Node) { if (driver.isSuppressed(null, ISSUE, (Node) clientData)) { continue; } } Location location = handle.resolve(); String message = String.format( "Corresponding method handler '`public void %1$s(android.view.View)`' not found", name); List<String> similar = mSimilar != null ? mSimilar.get(name) : null; if (similar != null) { Collections.sort(similar); message += String.format(" (did you mean `%1$s` ?)", Joiner.on(", ").join(similar)); } context.report(ISSUE, location, message); } } }
Example #14
Source File: EcjParser.java From javaide with GNU General Public License v3.0 | 5 votes |
@NonNull @Override public Location getLocation(@NonNull JavaContext context, @NonNull Node node) { lombok.ast.Position position = node.getPosition(); return Location.create(context.file, context.getContents(), position.getStart(), position.getEnd()); }
Example #15
Source File: PermissionsInLibraryDetector.java From lewis with Apache License 2.0 | 5 votes |
@Override public void afterCheckProject(@NonNull Context context) { // if it is a library if (context.getProject() == context.getMainProject() && context.getMainProject().isLibrary()) { for (Location location : mPermissionTagsLocations) { context.report(ISSUE_PERMISSION_USAGE_IN_LIBRARY, location, "Expecting " + ANDROID_MANIFEST_XML + " not to have a <" + TAG_USES_PERMISSION + "> tag invocation"); } } }
Example #16
Source File: WrongImportDetector.java From javaide with GNU General Public License v3.0 | 5 votes |
@Override public boolean visitImportDeclaration(ImportDeclaration node) { String fqn = node.asFullyQualifiedName(); if (fqn.equals("android.R")) { //$NON-NLS-1$ Location location = mContext.getLocation(node); mContext.report(ISSUE, node, location, "Don't include `android.R` here; use a fully qualified name for " + "each usage instead"); } return false; }
Example #17
Source File: UnusedResourceDetector.java From javaide with GNU General Public License v3.0 | 5 votes |
private void recordLocation(String resource, Location location) { Location oldLocation = mUnused.get(resource); if (oldLocation != null) { location.setSecondary(oldLocation); } mUnused.put(resource, location); }
Example #18
Source File: GradleDetectorTest.java From javaide with GNU General Public License v3.0 | 5 votes |
@Override protected Location createLocation(@NonNull Context context, @NonNull Object cookie) { ASTNode node = (ASTNode) cookie; Pair<Integer, Integer> offsets = getOffsets(node, context); int fromLine = node.getLineNumber() - 1; int fromColumn = node.getColumnNumber() - 1; int toLine = node.getLastLineNumber() - 1; int toColumn = node.getLastColumnNumber() - 1; return Location.create(context.file, new DefaultPosition(fromLine, fromColumn, offsets.getFirst()), new DefaultPosition(toLine, toColumn, offsets.getSecond())); }
Example #19
Source File: ViewConstructorDetector.java From javaide with GNU General Public License v3.0 | 5 votes |
@Override public void checkClass(@NonNull JavaContext context, @Nullable ClassDeclaration node, @NonNull Node declarationOrAnonymous, @NonNull ResolvedClass resolvedClass) { if (node == null) { return; } // Only applies to concrete classes int flags = node.astModifiers().getEffectiveModifierFlags(); // Ignore abstract classes if ((flags & Modifier.ABSTRACT) != 0) { return; } if (node.getParent() instanceof NormalTypeBody && ((flags & Modifier.STATIC) == 0)) { // Ignore inner classes that aren't static: we can't create these // anyway since we'd need the outer instance return; } boolean found = false; for (ResolvedMethod constructor : resolvedClass.getConstructors()) { if (isXmlConstructor(constructor)) { found = true; break; } } if (!found) { String message = String.format( "Custom view `%1$s` is missing constructor used by tools: " + "`(Context)` or `(Context,AttributeSet)` " + "or `(Context,AttributeSet,int)`", node.astName().astValue()); Location location = context.getLocation(node.astName()); context.report(ISSUE, node, location, message /*data*/); } }
Example #20
Source File: LayoutInflationDetector.java From javaide with GNU General Public License v3.0 | 5 votes |
@Override public void afterCheckProject(@NonNull Context context) { if (mPendingErrors != null) { for (Pair<String,Location> pair : mPendingErrors) { String inflatedLayout = pair.getFirst(); if (mLayoutsWithRootLayoutParams == null || !mLayoutsWithRootLayoutParams.contains(inflatedLayout)) { // No root layout parameters on the inflated layout: no need to complain continue; } Location location = pair.getSecond(); context.report(ISSUE, location, ERROR_MESSAGE); } } }
Example #21
Source File: LintCliClient.java From javaide with GNU General Public License v3.0 | 5 votes |
protected void reportNonExistingIssueId(@Nullable Project project, @NonNull String id) { String message = String.format("Unknown issue id \"%1$s\"", id); if (mDriver != null && project != null) { Location location = Location.create(project.getDir()); if (!isSuppressed(IssueRegistry.LINT_ERROR)) { report(new Context(mDriver, project, project, project.getDir()), IssueRegistry.LINT_ERROR, project.getConfiguration(mDriver).getSeverity(IssueRegistry.LINT_ERROR), location, message, TextFormat.RAW); } } else { log(Severity.ERROR, null, "Lint: %1$s", message); } }
Example #22
Source File: RtlDetector.java From javaide with GNU General Public License v3.0 | 5 votes |
@Override public void afterCheckProject(@NonNull Context context) { if (mUsesRtlAttributes && mEnabledRtlSupport == null && rtlApplies(context)) { List<File> manifestFile = context.getMainProject().getManifestFiles(); if (!manifestFile.isEmpty()) { Location location = Location.create(manifestFile.get(0)); context.report(ENABLED, location, "The project references RTL attributes, but does not explicitly enable " + "or disable RTL support with `android:supportsRtl` in the manifest"); } } }
Example #23
Source File: IconDetector.java From javaide with GNU General Public License v3.0 | 5 votes |
private static Location chainLocations(List<File> files) { // Chain locations together Collections.sort(files); Location location = null; for (File file : files) { Location linkedLocation = location; location = Location.create(file); location.setSecondary(linkedLocation); } return location; }
Example #24
Source File: LayoutConsistencyDetector.java From javaide with GNU General Public License v3.0 | 5 votes |
@NonNull private static Location chainLocations(@NonNull List<Location> locations) { assert !locations.isEmpty(); // Sort locations by the file parent folders if (locations.size() > 1) { Collections.sort(locations, new Comparator<Location>() { @Override public int compare(Location location1, Location location2) { File file1 = location1.getFile(); File file2 = location2.getFile(); String folder1 = file1.getParentFile().getName(); String folder2 = file2.getParentFile().getName(); return folder1.compareTo(folder2); } }); // Chain locations together Iterator<Location> iterator = locations.iterator(); assert iterator.hasNext(); Location prev = iterator.next(); while (iterator.hasNext()) { Location next = iterator.next(); prev.setSecondary(next); prev = next; } } return locations.get(0); }
Example #25
Source File: LayoutConsistencyDetector.java From javaide with GNU General Public License v3.0 | 5 votes |
private static void lookupLocations( @NonNull XmlContext context, @NonNull Element element, @NonNull Map<String, List<Location>> map) { String id = getId(element); if (id != null) { if (map.containsKey(id)) { if (context.getDriver().isSuppressed(context, INCONSISTENT_IDS, element)) { map.remove(id); return; } List<Location> locations = map.get(id); if (locations == null) { locations = Lists.newArrayList(); map.put(id, locations); } Attr attr = element.getAttributeNodeNS(ANDROID_URI, ATTR_ID); assert attr != null; Location location = context.getLocation(attr); String folder = context.file.getParentFile().getName(); location.setMessage(String.format("Occurrence in %1$s", folder)); locations.add(location); } } NodeList childNodes = element.getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { Node child = childNodes.item(i); if (child.getNodeType() == Node.ELEMENT_NODE) { lookupLocations(context, (Element) child, map); } } }
Example #26
Source File: GridLayoutDetectorTest.java From javaide with GNU General Public License v3.0 | 5 votes |
@Override protected void checkReportedError(@NonNull Context context, @NonNull Issue issue, @NonNull Severity severity, @Nullable Location location, @NonNull String message) { if (message.contains("with v7 GridLayout")) { assertNotNull(message, getOldValue(message, TEXT)); assertNotNull(message, getNewValue(message, TEXT)); } }
Example #27
Source File: MissingClassDetectorTest.java From javaide with GNU General Public License v3.0 | 5 votes |
@Override protected void checkReportedError(@NonNull Context context, @NonNull Issue issue, @NonNull Severity severity, @Nullable Location location, @NonNull String message) { if (issue == INNERCLASS) { assertNotNull(message, MissingClassDetector.getOldValue(issue, message, TEXT)); assertNotNull(message, MissingClassDetector.getNewValue(issue, message, TEXT)); } }
Example #28
Source File: ResourcePrefixDetector.java From javaide with GNU General Public License v3.0 | 5 votes |
@Override public void checkBinaryResource(@NonNull ResourceContext context) { if (mPrefix != null) { ResourceFolderType folderType = context.getResourceFolderType(); if (folderType != null && folderType != ResourceFolderType.VALUES) { String name = LintUtils.getBaseName(context.file.getName()); if (!name.startsWith(mPrefix)) { Location location = Location.create(context.file); context.report(ISSUE, location, getErrorMessage(name)); } } } }
Example #29
Source File: GradleDetectorTest.java From javaide with GNU General Public License v3.0 | 5 votes |
@Override protected void checkReportedError(@NonNull Context context, @NonNull Issue issue, @NonNull Severity severity, @Nullable Location location, @NonNull String message) { if (issue == DEPENDENCY && message.startsWith("Using the appcompat library when ")) { // No data embedded in this specific message return; } // Issues we're supporting getOldFrom if (issue == DEPENDENCY || issue == STRING_INTEGER || issue == DEPRECATED || issue == PLUS) { assertNotNull("Could not extract message tokens from " + message, GradleDetector.getOldValue(issue, message, TEXT)); } if (issue == DEPENDENCY || issue == STRING_INTEGER || issue == DEPRECATED) { assertNotNull("Could not extract message tokens from " + message, GradleDetector.getNewValue(issue, message, TEXT)); } if (issue == COMPATIBILITY) { if (message.startsWith("Version ")) { assertNotNull("Could not extract message tokens from " + message, GradleDetector.getNewValue(issue, message, TEXT)); } } }
Example #30
Source File: ManifestDetector.java From javaide with GNU General Public License v3.0 | 5 votes |
@Nullable private Location getMainApplicationTagLocation(@NonNull Context context) { if (mApplicationTagHandle != null) { return mApplicationTagHandle.resolve(); } List<File> manifestFiles = context.getMainProject().getManifestFiles(); if (!manifestFiles.isEmpty()) { return Location.create(manifestFiles.get(0)); } return null; }