1 package net.sourceforge.pmd.rules.strictexception;
2
3 import net.sourceforge.pmd.AbstractRule;
4 import net.sourceforge.pmd.RuleContext;
5 import net.sourceforge.pmd.ast.ASTBlock;
6 import net.sourceforge.pmd.ast.ASTCastExpression;
7 import net.sourceforge.pmd.ast.ASTCatchStatement;
8 import net.sourceforge.pmd.ast.ASTInstanceOfExpression;
9 import net.sourceforge.pmd.ast.ASTName;
10 import net.sourceforge.pmd.ast.ASTPrimaryExpression;
11 import net.sourceforge.pmd.ast.ASTType;
12 import net.sourceforge.pmd.ast.ASTVariableDeclaratorId;
13 import net.sourceforge.pmd.ast.SimpleNode;
14
15 import java.util.Iterator;
16 import java.util.List;
17
18 /***
19 * @author <a mailto:trond.andersen@nordea.com>Trond Andersen</a>
20 */
21 public class ExceptionTypeChecking extends AbstractRule {
22
23 public Object visit(ASTCatchStatement node, Object data) {
24 String exceptionParameter = getExceptionParameter(node);
25
26 ASTBlock block = (ASTBlock)(node.jjtGetChild(1));
27 List myList = block.findChildrenOfType(ASTInstanceOfExpression.class);
28 for (Iterator i = myList.iterator(); i.hasNext();) {
29 evaluateInstanceOfExpression((ASTInstanceOfExpression) i.next(), exceptionParameter, (RuleContext)data);
30 }
31 return super.visit(node, data);
32 }
33
34 private void evaluateInstanceOfExpression(ASTInstanceOfExpression instanceOfExpression,
35 String exceptionName, RuleContext ctx) {
36 if (!hasTypeEvaluation(instanceOfExpression)) {
37 return;
38 }
39 if (exceptionName.equals(getInstanceOfObjectReference(instanceOfExpression))) {
40 ctx.getReport().addRuleViolation(createRuleViolation(ctx, instanceOfExpression));
41 }
42 }
43
44 private boolean hasTypeEvaluation(ASTInstanceOfExpression instanceOfExpression) {
45 List typeList = instanceOfExpression.findChildrenOfType(ASTType.class);
46 if (!typeList.isEmpty()) {
47 ASTType theType = (ASTType) typeList.get(0);
48 if (!(theType.jjtGetParent() instanceof ASTCastExpression)) {
49 return true;
50 }
51 }
52 return false;
53 }
54
55 private String getInstanceOfObjectReference(ASTInstanceOfExpression expression) {
56 List primaryList = expression.findChildrenOfType(ASTPrimaryExpression.class);
57 String objectReferenceName = null;
58 if (primaryList.size() == 1) {
59 List someList = ((ASTPrimaryExpression) primaryList.get(0)).findChildrenOfType(ASTName.class);
60 if (someList.size() == 1) {
61 objectReferenceName = ((ASTName) someList.get(0)).getImage();
62 }
63 }
64 return objectReferenceName;
65 }
66
67 private String getExceptionParameter(ASTCatchStatement catchStmt) {
68 ASTVariableDeclaratorId id = (ASTVariableDeclaratorId)((SimpleNode)catchStmt.jjtGetChild(0)).findChildrenOfType(ASTVariableDeclaratorId.class).get(0);
69 return id.getImage();
70 }
71
72 }