01: package net.sourceforge.pmd.rules;
02:
03: import java.util.Stack;
04:
05: import net.sourceforge.pmd.AbstractRule;
06: import net.sourceforge.pmd.ast.ASTClassOrInterfaceDeclaration;
07: import net.sourceforge.pmd.ast.ASTClassOrInterfaceType;
08: import net.sourceforge.pmd.ast.ASTEnumDeclaration;
09: import net.sourceforge.pmd.ast.ASTReferenceType;
10: import net.sourceforge.pmd.ast.ASTType;
11: import net.sourceforge.pmd.ast.ASTVariableDeclarator;
12: import net.sourceforge.pmd.ast.SimpleJavaNode;
13: import net.sourceforge.pmd.ast.SimpleNode;
14: import net.sourceforge.pmd.util.NumericConstants;
15:
16: public class MoreThanOneLogger extends AbstractRule {
17:
18: private static Class log4jLogger = null;
19:
20: private static Class javaLogger = null;
21:
22: static {
23: try {
24: log4jLogger = Class.forName("org.apache.log4j.Logger");
25: } catch (Throwable t) {
26: log4jLogger = null;
27: }
28: try {
29: javaLogger = Class.forName("java.util.logging.Logger");
30: } catch (Throwable t) {
31: log4jLogger = null;
32: }
33: }
34:
35: private Stack<Integer> stack = new Stack<Integer>();
36:
37: private Integer count;
38:
39: public Object visit(ASTClassOrInterfaceDeclaration node, Object data) {
40: return init(node, data);
41: }
42:
43: public Object visit(ASTEnumDeclaration node, Object data) {
44: return init(node, data);
45: }
46:
47: private Object init(SimpleJavaNode node, Object data) {
48: stack.push(count);
49: count = NumericConstants.ZERO;
50:
51: node.childrenAccept(this , data);
52:
53: if (count > 1) {
54: addViolation(data, node);
55: }
56: count = stack.pop();
57:
58: return data;
59: }
60:
61: public Object visit(ASTVariableDeclarator node, Object data) {
62: if (count > 1) {
63: return super .visit(node, data);
64: }
65: SimpleNode type = ((SimpleNode) node.jjtGetParent())
66: .getFirstChildOfType(ASTType.class);
67: if (type != null) {
68: SimpleNode reftypeNode = (SimpleNode) type.jjtGetChild(0);
69: if (reftypeNode instanceof ASTReferenceType) {
70: SimpleNode classOrIntType = (SimpleNode) reftypeNode
71: .jjtGetChild(0);
72: if (classOrIntType instanceof ASTClassOrInterfaceType) {
73: Class clazzType = ((ASTClassOrInterfaceType) classOrIntType)
74: .getType();
75: if ((clazzType != null
76: && (clazzType.equals(log4jLogger) || clazzType
77: .equals(javaLogger)) || (clazzType == null && "Logger"
78: .equals(classOrIntType.getImage())))) {
79: ++count;
80: }
81: }
82: }
83: }
84:
85: return super.visit(node, data);
86: }
87:
88: }
|