com.android.tools.lint.detector.api.JavaContext Java Examples
The following examples show how to use
com.android.tools.lint.detector.api.JavaContext.
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: SupportAnnotationDetector.java From javaide with GNU General Public License v3.0 | 6 votes |
private void checkMethodAnnotation( @NonNull JavaContext context, @NonNull ResolvedMethod method, @NonNull Node node, @NonNull ResolvedAnnotation annotation) { String signature = annotation.getSignature(); if (CHECK_RESULT_ANNOTATION.equals(signature) || signature.endsWith(".CheckReturnValue")) { // support findbugs annotation too checkResult(context, node, annotation); } else if (signature.equals(PERMISSION_ANNOTATION)) { PermissionRequirement requirement = PermissionRequirement.create(context, annotation); checkPermission(context, node, method, null, requirement); } else if (signature.endsWith(THREAD_SUFFIX) && signature.startsWith(SUPPORT_ANNOTATIONS_PREFIX)) { checkThreading(context, node, method, signature); } }
Example #2
Source File: HashMapForJDK7Detector.java From MeituanLintDemo with Apache License 2.0 | 6 votes |
@Override public AstVisitor createJavaVisitor(final @NonNull JavaContext context) { return new ForwardingAstVisitor() { @Override public boolean visitConstructorInvocation(ConstructorInvocation node) { TypeReference reference = node.astTypeReference(); String typeName = reference.astParts().last().astIdentifier().astValue(); // TODO: Should we handle factory method constructions of HashMaps as well, // e.g. via Guava? This is a bit trickier since we need to infer the type // arguments from the calling context. if (typeName.equals(HASH_MAP)) { checkHashMap(context, node, reference); } return super.visitConstructorInvocation(node); } }; }
Example #3
Source File: AppCompatCallDetector.java From javaide with GNU General Public License v3.0 | 6 votes |
private static boolean isAppBarActivityCall(@NonNull JavaContext context, @NonNull MethodInvocation node) { ResolvedNode resolved = context.resolve(node); if (resolved instanceof ResolvedMethod) { ResolvedMethod method = (ResolvedMethod) resolved; ResolvedClass containingClass = method.getContainingClass(); if (containingClass.isSubclassOf(CLASS_ACTIVITY, false)) { // Make sure that the calling context is a subclass of ActionBarActivity; // we don't want to flag these calls if they are in non-appcompat activities // such as PreferenceActivity (see b.android.com/58512) ClassDeclaration surroundingClass = JavaContext.findSurroundingClass(node); if (surroundingClass != null) { ResolvedNode clz = context.resolve(surroundingClass); return clz instanceof ResolvedClass && ((ResolvedClass)clz).isSubclassOf( "android.support.v7.app.ActionBarActivity", false); } } } return false; }
Example #4
Source File: MergeRootFrameLayoutDetector.java From javaide with GNU General Public License v3.0 | 6 votes |
@Override public void visitMethod( @NonNull JavaContext context, @Nullable AstVisitor visitor, @NonNull MethodInvocation node) { StrictListAccessor<Expression, MethodInvocation> argumentList = node.astArguments(); if (argumentList != null && argumentList.size() == 1) { Expression argument = argumentList.first(); if (argument instanceof Select) { String expression = argument.toString(); if (expression.startsWith(R_LAYOUT_RESOURCE_PREFIX)) { whiteListLayout(expression.substring(R_LAYOUT_RESOURCE_PREFIX.length())); } } } }
Example #5
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 #6
Source File: AlarmDetector.java From javaide with GNU General Public License v3.0 | 6 votes |
private static void ensureAtLeast(@NonNull JavaContext context, @NonNull MethodInvocation node, int parameter, long min) { Iterator<Expression> iterator = node.astArguments().iterator(); Expression argument = null; for (int i = 0; i <= parameter; i++) { if (!iterator.hasNext()) { return; } argument = iterator.next(); } if (argument == null) { return; } long value = getLongValue(context, argument); if (value < min) { String message = String.format("Value will be forced up to %d as of Android 5.1; " + "don't rely on this to be exact", min); context.report(ISSUE, argument, context.getLocation(argument), message); } }
Example #7
Source File: LogDetector.java From MeituanLintDemo with Apache License 2.0 | 6 votes |
@Override public AstVisitor createJavaVisitor(final JavaContext context) { return new ForwardingAstVisitor() { @Override public boolean visitMethodInvocation(MethodInvocation node) { JavaParser.ResolvedNode resolve = context.resolve(node); if (resolve instanceof JavaParser.ResolvedMethod) { JavaParser.ResolvedMethod method = (JavaParser.ResolvedMethod) resolve; // 方法所在的类校验 JavaParser.ResolvedClass containingClass = method.getContainingClass(); if (containingClass.matches("android.util.Log")) { context.report(ISSUE, node, context.getLocation(node), "请使用Ln,避免使用Log"); return true; } if (node.toString().startsWith("System.out.println")) { context.report(ISSUE, node, context.getLocation(node), "请使用Ln,避免使用System.out.println"); return true; } } return super.visitMethodInvocation(node); } }; }
Example #8
Source File: SupportAnnotationDetector.java From javaide with GNU General Public License v3.0 | 6 votes |
private static void reportTypeDef(@NonNull JavaContext context, @NonNull Node node, @Nullable Node errorNode, boolean flag, @NonNull Object[] allowedValues, @NonNull Iterable<ResolvedAnnotation> allAnnotations) { String values = listAllowedValues(allowedValues); String message; if (flag) { message = "Must be one or more of: " + values; } else { message = "Must be one of: " + values; } ResolvedAnnotation rangeAnnotation = findIntRange(allAnnotations); if (rangeAnnotation != null) { // Allow @IntRange on this number String rangeError = getIntRangeError(context, rangeAnnotation, node); if (rangeError != null && !rangeError.isEmpty()) { message += " or " + Character.toLowerCase(rangeError.charAt(0)) + rangeError.substring(1); } } if (errorNode == null) { errorNode = node; } context.report(TYPE_DEF, errorNode, context.getLocation(errorNode), message); }
Example #9
Source File: CleanupDetector.java From javaide with GNU General Public License v3.0 | 6 votes |
private static boolean isCommittedInChainedCalls(@NonNull JavaContext context, @NonNull MethodInvocation node) { // Look for chained calls since the FragmentManager methods all return "this" // to allow constructor chaining, e.g. // getFragmentManager().beginTransaction().addToBackStack("test") // .disallowAddToBackStack().hide(mFragment2).setBreadCrumbShortTitle("test") // .show(mFragment2).setCustomAnimations(0, 0).commit(); Node parent = node.getParent(); while (parent instanceof MethodInvocation) { MethodInvocation methodInvocation = (MethodInvocation) parent; if (isTransactionCommitMethodCall(context, methodInvocation) || isShowFragmentMethodCall(context, methodInvocation)) { return true; } parent = parent.getParent(); } return false; }
Example #10
Source File: GetSignaturesDetector.java From javaide with GNU General Public License v3.0 | 6 votes |
@Override public void visitMethod(@NonNull JavaContext context, @Nullable AstVisitor visitor, @NonNull MethodInvocation node) { ResolvedNode resolved = context.resolve(node); if (!(resolved instanceof ResolvedMethod) || !((ResolvedMethod) resolved).getContainingClass() .isSubclassOf(PACKAGE_MANAGER_CLASS, false)) { return; } StrictListAccessor<Expression, MethodInvocation> argumentList = node.astArguments(); // Ignore if the method doesn't fit our description. if (argumentList != null && argumentList.size() == 2) { TypeDescriptor firstParameterType = context.getType(argumentList.first()); if (firstParameterType != null && firstParameterType.matchesSignature(JavaParser.TYPE_STRING)) { maybeReportIssue(calculateValue(context, argumentList.last()), context, node); } } }
Example #11
Source File: PrivateResourceDetector.java From javaide with GNU General Public License v3.0 | 6 votes |
@Override public void visitResourceReference( @NonNull JavaContext context, @Nullable AstVisitor visitor, @NonNull Node node, @NonNull String type, @NonNull String name, boolean isFramework) { if (context.getProject().isGradleProject() && !isFramework) { Project project = context.getProject(); if (project.getGradleProjectModel() != null && project.getCurrentVariant() != null) { ResourceType resourceType = ResourceType.getEnum(type); if (resourceType != null && isPrivate(context, resourceType, name)) { String message = createUsageErrorMessage(context, resourceType, name); context.report(ISSUE, node, context.getLocation(node), message); } } } }
Example #12
Source File: SetJavaScriptEnabledDetector.java From javaide with GNU General Public License v3.0 | 5 votes |
@Override public void visitMethod(@NonNull JavaContext context, @Nullable AstVisitor visitor, @NonNull MethodInvocation node) { if (node.astArguments().size() == 1 && !node.astArguments().first().toString().equals("false")) { //$NON-NLS-1$ context.report(ISSUE, node, context.getLocation(node), "Using `setJavaScriptEnabled` can introduce XSS vulnerabilities " + "into you application, review carefully."); } }
Example #13
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 #14
Source File: ViewTypeDetector.java From javaide with GNU General Public License v3.0 | 5 votes |
/** Check if the view and cast type are compatible */ private static void checkCompatible(JavaContext context, String castType, String layoutType, List<String> layoutTypes, Cast node) { assert layoutType == null || layoutTypes == null; // Should only specify one or the other boolean compatible = true; if (layoutType != null) { if (!layoutType.equals(castType) && !context.getSdkInfo().isSubViewOf(castType, layoutType)) { compatible = false; } } else { compatible = false; assert layoutTypes != null; for (String type : layoutTypes) { if (type.equals(castType) || context.getSdkInfo().isSubViewOf(castType, type)) { compatible = true; break; } } } if (!compatible) { if (layoutType == null) { layoutType = Joiner.on("|").join(layoutTypes); } String message = String.format( "Unexpected cast to `%1$s`: layout tag was `%2$s`", castType, layoutType); context.report(ISSUE, node, context.getLocation(node), message); } }
Example #15
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 #16
Source File: LayoutConsistencyDetector.java From javaide with GNU General Public License v3.0 | 5 votes |
@Override public void visitResourceReference(@NonNull JavaContext context, @Nullable AstVisitor visitor, @NonNull lombok.ast.Node node, @NonNull String type, @NonNull String name, boolean isFramework) { if (!isFramework && type.equals(ResourceType.ID.getName())) { mRelevantIds.add(name); } }
Example #17
Source File: AlarmDetector.java From javaide with GNU General Public License v3.0 | 5 votes |
private static long getLongValue(@NonNull JavaContext context, @NonNull Expression argument) { Object value = ConstantEvaluator.evaluate(context, argument); if (value instanceof Number) { return ((Number)value).longValue(); } return Long.MAX_VALUE; }
Example #18
Source File: RootPackageDetector.java From lewis with Apache License 2.0 | 5 votes |
/** * Check if the node is inside the root package and report an issue in that case. * * @param context is the context of the Java code. * @param node represents the element to evaluate. * @param fileName is the name of the file. */ private void shouldNotBeInRootPackage(JavaContext context, Node node, String fileName) { String packageName = context.getMainProject().getPackage(); String filePackageString = PackageManager.getPackage(context, node); if (filePackageString.equals(packageName + "." + fileName + ".java") && !PackageManager.isGenerated(context, node)) { context.report(ISSUE_CLASS_IN_ROOT_PACKAGE, PackageManager.getNodeLocation(context, node), " Expecting " + fileName + " not to be in root package " + packageName); } }
Example #19
Source File: RtlDetector.java From javaide with GNU General Public License v3.0 | 5 votes |
@Override public AstVisitor createJavaVisitor(@NonNull JavaContext context) { if (rtlApplies(context)) { return new IdentifierChecker(context); } return new ForwardingAstVisitor() { }; }
Example #20
Source File: IssueFixBuilder.java From aircon with MIT License | 5 votes |
public IssueFixBuilder(JavaContext context, T target, String name) { mContext = context; mTarget = target; mGroupBuilder = LintFix.create() .composite() .name(name); }
Example #21
Source File: CleanupDetector.java From javaide with GNU General Public License v3.0 | 5 votes |
private static boolean isTransactionCommitMethodCall(@NonNull JavaContext context, @NonNull MethodInvocation call) { String methodName = call.astName().astValue(); return (COMMIT.equals(methodName) || COMMIT_ALLOWING_LOSS.equals(methodName)) && isMethodOnFragmentClass(context, call, FRAGMENT_TRANSACTION_CLS, FRAGMENT_TRANSACTION_V4_CLS); }
Example #22
Source File: DialogExtendLintDetector.java From SimpleDialogFragments with Apache License 2.0 | 5 votes |
@Override public void visitClass(JavaContext context, UClass declaration) { PsiModifierList classModifiers = declaration.getModifierList(); if (classModifiers == null || !classModifiers.hasModifierProperty("abstract")) { // check for static build method boolean hasBuildMethod = false; for (PsiMethod method : declaration.getMethods()) { if ("build".equals(method.getName()) && method.getModifierList() .hasModifierProperty("static")) { hasBuildMethod = true; break; } } if (!hasBuildMethod){ context.report(BUILD_OVERWRITE, context.getLocation(declaration.getExtendsList()), BUILD_OVERWRITE_MESSAGE); } // check for public static String TAG boolean hasTag = false; for (UField field : declaration.getFields()) { PsiModifierList modifiers = field.getModifierList(); if ("TAG".equals(field.getName()) && LintUtils.isString(field.getType()) && modifiers != null && modifiers.hasModifierProperty("public") && modifiers.hasModifierProperty("static")) { hasTag = true; break; } } if (!hasTag) { context.report(TAG, context.getLocation(declaration.getExtendsList()), TAG_MESSAGE); } } }
Example #23
Source File: JavaVisitor.java From javaide with GNU General Public License v3.0 | 5 votes |
public void setContext(@NonNull JavaContext context) { mContext = context; // The visitors are one-per-context, so clear them out here and construct // lazily only if needed mVisitor = null; }
Example #24
Source File: AssertDetector.java From javaide with GNU General Public License v3.0 | 5 votes |
@Override public AstVisitor createJavaVisitor(@NonNull final JavaContext context) { return new ForwardingAstVisitor() { @Override public boolean visitAssert(Assert node) { if (!context.getMainProject().isAndroidProject()) { return true; } Expression assertion = node.astAssertion(); // Allow "assert true"; it's basically a no-op if (assertion instanceof BooleanLiteral) { Boolean b = ((BooleanLiteral) assertion).astValue(); if (b != null && b) { return false; } } else { // Allow assertions of the form "assert foo != null" because they are often used // to make statements to tools about known nullness properties. For example, // findViewById() may technically return null in some cases, but a developer // may know that it won't be when it's called correctly, so the assertion helps // to clear nullness warnings. if (isNullCheck(assertion)) { return false; } } String message = "Assertions are unreliable. Use `BuildConfig.DEBUG` conditional checks instead."; context.report(ISSUE, node, context.getLocation(node), message); return false; } }; }
Example #25
Source File: CleanupDetector.java From javaide with GNU General Public License v3.0 | 5 votes |
@Override public void visitMethod(@NonNull JavaContext context, @Nullable AstVisitor visitor, @NonNull MethodInvocation node) { String name = node.astName().astValue(); if (BEGIN_TRANSACTION.equals(name)) { checkTransactionCommits(context, node); } else { checkResourceRecycled(context, node, name); } }
Example #26
Source File: SupportAnnotationDetector.java From javaide with GNU General Public License v3.0 | 5 votes |
private static void checkResult(@NonNull JavaContext context, @NonNull Node node, @NonNull ResolvedAnnotation annotation) { if (node.getParent() instanceof ExpressionStatement) { String methodName = JavaContext.getMethodName(node); Object suggested = annotation.getValue(ATTR_SUGGEST); // Failing to check permissions is a potential security issue (and had an existing // dedicated issue id before which people may already have configured with a // custom severity in their LintOptions etc) so continue to use that issue // (which also has category Security rather than Correctness) for these: Issue issue = CHECK_RESULT; if (methodName != null && methodName.startsWith("check") && methodName.contains("Permission")) { issue = CHECK_PERMISSION; } String message = String.format("The result of `%1$s` is not used", methodName); if (suggested != null) { // TODO: Resolve suggest attribute (e.g. prefix annotation class if it starts // with "#" etc? message = String.format( "The result of `%1$s` is not used; did you mean to call `%2$s`?", methodName, suggested.toString()); } context.report(issue, node, context.getLocation(node), message); } }
Example #27
Source File: CleanupDetector.java From javaide with GNU General Public License v3.0 | 5 votes |
private static boolean isShowFragmentMethodCall(@NonNull JavaContext context, @NonNull MethodInvocation call) { String methodName = call.astName().astValue(); return SHOW.equals(methodName) && isMethodOnFragmentClass(context, call, DIALOG_FRAGMENT, DIALOG_V4_FRAGMENT); }
Example #28
Source File: HashMapForJDK7Detector.java From MeituanLintDemo with Apache License 2.0 | 5 votes |
private void checkCore2(JavaContext context, Node node, String fullTypeName) { final Pattern p = Pattern.compile(".*<(.*),(.*)>"); Matcher m = p.matcher(fullTypeName); if (m.find()) { String typeName = m.group(1).trim(); String valueType = m.group(2).trim(); int minSdk = context.getMainProject().getMinSdk(); if (typeName.equals(INTEGER) || typeName.equals(BYTE)) { if (valueType.equals(INTEGER)) { context.report(ISSUE, node, context.getLocation(node), "Use new SparseIntArray(...) instead for better performance"); } else if (valueType.equals(LONG) && minSdk >= 18) { context.report(ISSUE, node, context.getLocation(node), "Use new SparseLongArray(...) instead for better performance"); } else if (valueType.equals(BOOLEAN)) { context.report(ISSUE, node, context.getLocation(node), "Use new SparseBooleanArray(...) instead for better performance"); } else { context.report(ISSUE, node, context.getLocation(node), String.format( "Use new SparseArray<%1$s>(...) instead for better performance", valueType)); } } else if (typeName.equals(LONG) && (minSdk >= 16 || Boolean.TRUE == context.getMainProject().dependsOn( SdkConstants.SUPPORT_LIB_ARTIFACT))) { boolean useBuiltin = minSdk >= 16; String message = useBuiltin ? "Use new LongSparseArray(...) instead for better performance" : "Use new android.support.v4.util.LongSparseArray(...) instead for better performance"; context.report(ISSUE, node, context.getLocation(node), message); } } }
Example #29
Source File: CallSuperDetector.java From javaide with GNU General Public License v3.0 | 5 votes |
public static boolean callsSuper( @NonNull JavaContext context, @NonNull MethodDeclaration methodDeclaration, @NonNull ResolvedMethod method) { SuperCallVisitor visitor = new SuperCallVisitor(context, method); methodDeclaration.accept(visitor); return visitor.mCallsSuper; }
Example #30
Source File: CleanupDetector.java From javaide with GNU General Public License v3.0 | 5 votes |
private static boolean isMethodOnFragmentClass( @NonNull JavaContext context, @NonNull MethodInvocation call, @NonNull String fragmentClass, @NonNull String v4FragmentClass) { ResolvedNode resolved = context.resolve(call); if (resolved instanceof ResolvedMethod) { ResolvedClass containingClass = ((ResolvedMethod) resolved).getContainingClass(); return containingClass.isSubclassOf(fragmentClass, false) || containingClass.isSubclassOf(v4FragmentClass, false); } return false; }