KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > sourceforge > pmd > rules > imports > UnusedImportsRule


1 /**
2  * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
3  */

4 package net.sourceforge.pmd.rules.imports;
5
6 import net.sourceforge.pmd.AbstractRule;
7 import net.sourceforge.pmd.ast.ASTClassOrInterfaceType;
8 import net.sourceforge.pmd.ast.ASTCompilationUnit;
9 import net.sourceforge.pmd.ast.ASTImportDeclaration;
10 import net.sourceforge.pmd.ast.ASTName;
11 import net.sourceforge.pmd.ast.SimpleJavaNode;
12 import net.sourceforge.pmd.ast.SimpleNode;
13 import net.sourceforge.pmd.rules.ImportWrapper;
14
15 import java.util.HashSet JavaDoc;
16 import java.util.Iterator JavaDoc;
17 import java.util.Set JavaDoc;
18
19 public class UnusedImportsRule extends AbstractRule {
20
21     private Set JavaDoc imports = new HashSet JavaDoc();
22
23     public Object JavaDoc visit(ASTCompilationUnit node, Object JavaDoc data) {
24         imports.clear();
25         super.visit(node, data);
26         for (Iterator JavaDoc i = imports.iterator(); i.hasNext();) {
27             ImportWrapper wrapper = (ImportWrapper) i.next();
28             addViolation(data, wrapper.getNode(), wrapper.getFullName());
29         }
30         return data;
31     }
32
33     public Object JavaDoc visit(ASTImportDeclaration node, Object JavaDoc data) {
34         if (!node.isImportOnDemand()) {
35             ASTName importedType = (ASTName) node.jjtGetChild(0);
36             String JavaDoc className;
37             if (isQualifiedName(importedType)) {
38                 int lastDot = importedType.getImage().lastIndexOf('.') + 1;
39                 className = importedType.getImage().substring(lastDot);
40             } else {
41                 className = importedType.getImage();
42             }
43             imports.add(new ImportWrapper(importedType.getImage(), className, node));
44         }
45
46         return data;
47     }
48
49     public Object JavaDoc visit(ASTClassOrInterfaceType node, Object JavaDoc data) {
50         check(node);
51         return super.visit(node, data);
52     }
53
54     public Object JavaDoc visit(ASTName node, Object JavaDoc data) {
55         check(node);
56         return data;
57     }
58
59     private void check(SimpleNode node) {
60         String JavaDoc name;
61         if (!isQualifiedName(node)) {
62             name = node.getImage();
63         } else {
64             name = node.getImage().substring(0, node.getImage().indexOf('.'));
65         }
66         ImportWrapper candidate = new ImportWrapper(node.getImage(), name, new SimpleJavaNode(-1));
67         if (imports.contains(candidate)) {
68             imports.remove(candidate);
69         }
70     }
71 }
72
Popular Tags