View Javadoc

    1   package net.sourceforge.pmd.rules;
    2
    3   import java.util.Stack;
    4
    5   import net.sourceforge.pmd.AbstractRule;
    6   import net.sourceforge.pmd.ast.ASTClassOrInterfaceDeclaration;
    7   import net.sourceforge.pmd.ast.ASTClassOrInterfaceType;
    8   import net.sourceforge.pmd.ast.ASTEnumDeclaration;
    9   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
    15  public class MoreThanOneLogger extends AbstractRule {
    16
    17  	private Stack stack = new Stack();
    18
    19  	private Integer count;
    20
    21  	public Object visit(ASTClassOrInterfaceDeclaration node, Object data) {
    22  		return init (node, data);
    23  	}
    24
    25  	public Object visit(ASTEnumDeclaration node, Object data) {
    26  		return init (node, data);
    27  	}
    28
    29  	private Object init(SimpleJavaNode node, Object data) {
    30  		stack.push(count);
    31  		count = new Integer(0);
    32
    33  		node.childrenAccept(this, data);
    34
    35  		if (count.intValue() > 1) {
    36  			addViolation(data, node);
    37  		}
    38  		count = (Integer) stack.pop();
    39
    40  		return data;
    41  	}
    42
    43  	public Object visit(ASTVariableDeclarator node, Object data) {
    44  		if (count.intValue() > 1) {
    45  			return super.visit(node, data);
    46  		}
    47  		SimpleNode type = (SimpleNode) ((SimpleNode) node.jjtGetParent()).getFirstChildOfType(ASTType.class);
    48  		if (type != null) {
    49  			SimpleNode reftypeNode = (SimpleNode) type.jjtGetChild(0);
    50  			if (reftypeNode instanceof ASTReferenceType) {
    51                  SimpleNode classOrIntType = (SimpleNode) reftypeNode.jjtGetChild(0);
    52                  if (classOrIntType instanceof ASTClassOrInterfaceType && "Logger".equals(classOrIntType.getImage())) {
    53                  	count = new Integer(count.intValue()+1);
    54                  }
    55  			}
    56  		}
    57
    58  		return super.visit(node, data);
    59  	}
    60
    61  }