01: package org.acm.seguin.pmd.rules;
02:
03: import org.acm.seguin.pmd.AbstractRule;
04: import org.acm.seguin.pmd.RuleContext;
05: import net.sourceforge.jrefactory.ast.ASTCompilationUnit;
06: import net.sourceforge.jrefactory.ast.ASTImportDeclaration;
07: import net.sourceforge.jrefactory.ast.ASTName;
08: import net.sourceforge.jrefactory.ast.ASTPackageDeclaration;
09:
10: public class ImportFromSamePackageRule extends AbstractRule {
11:
12: private String packageName;
13:
14: public Object visit(ASTCompilationUnit node, Object data) {
15: packageName = null;
16: return super .visit(node, data);
17: }
18:
19: public Object visit(ASTPackageDeclaration node, Object data) {
20: packageName = ((ASTName) node.jjtGetFirstChild()).getImage();
21: return data;
22: }
23:
24: public Object visit(ASTImportDeclaration node, Object data) {
25: ASTName nameNode = node.getImportedNameNode();
26: RuleContext ctx = (RuleContext) data;
27: if (packageName != null
28: && !node.isImportOnDemand()
29: && packageName.equals(getPackageName(nameNode
30: .getImage()))) {
31: addViolation(ctx, node);
32: }
33:
34: // special case
35: if (packageName == null
36: && getPackageName(nameNode.getImage()).equals("")) {
37: addViolation(ctx, node);
38: }
39: return data;
40: }
41:
42: private void addViolation(RuleContext ctx, ASTImportDeclaration node) {
43: ctx.getReport().addRuleViolation(
44: createRuleViolation(ctx, node.getBeginLine()));
45: }
46:
47: private String getPackageName(String importName) {
48: if (importName.indexOf('.') == -1) {
49: return "";
50: }
51: int lastDot = importName.lastIndexOf('.');
52: return importName.substring(0, lastDot);
53: }
54:
55: }
|