1 package net.sourceforge.pmd.lang.java.rule;
2
3 import java.util.List;
4
5 import net.sourceforge.pmd.lang.ast.Node;
6 import net.sourceforge.pmd.lang.java.ast.ASTAdditiveExpression;
7 import net.sourceforge.pmd.lang.java.ast.ASTLiteral;
8 import net.sourceforge.pmd.lang.java.ast.ASTPrimaryExpression;
9 import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclaratorId;
10 import net.sourceforge.pmd.lang.java.symboltable.NameOccurrence;
11
12
13
14
15
16
17
18
19
20
21
22
23
24 public abstract class AbstractPoorMethodCall extends AbstractJavaRule {
25
26
27
28
29
30
31 protected abstract String targetTypename();
32
33
34
35
36
37
38
39 protected abstract String[] methodNames();
40
41
42
43
44
45
46
47
48 protected abstract boolean isViolationArgument(Node arg);
49
50
51
52
53
54
55
56
57 private boolean isNotedMethod(NameOccurrence occurrence) {
58
59 if (occurrence == null) {
60 return false;
61 }
62
63 String methodCall = occurrence.getImage();
64 String[] methodNames = methodNames();
65
66 for (String element : methodNames) {
67 if (methodCall.indexOf(element) != -1) {
68 return true;
69 }
70 }
71 return false;
72 }
73
74
75
76
77
78
79
80
81 @Override
82 public Object visit(ASTVariableDeclaratorId node, Object data) {
83 if (!node.getNameDeclaration().getTypeImage().equals(targetTypename())) {
84 return data;
85 }
86
87 for (NameOccurrence occ : node.getUsages()) {
88 if (isNotedMethod(occ.getNameForWhichThisIsAQualifier())) {
89 Node parent = occ.getLocation().jjtGetParent().jjtGetParent();
90 if (parent instanceof ASTPrimaryExpression) {
91
92 if (parent.hasDescendantOfType(ASTAdditiveExpression.class)) {
93 return data;
94 }
95 List<ASTLiteral> literals = parent.findDescendantsOfType(ASTLiteral.class);
96 for (int l = 0; l < literals.size(); l++) {
97 ASTLiteral literal = literals.get(l);
98 if (isViolationArgument(literal)) {
99 addViolation(data, occ.getLocation());
100 }
101 }
102 }
103 }
104 }
105 return data;
106 }
107 }