KickJava   Java API By Example, From Geeks To Geeks.

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


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.ASTCompilationUnit;
8 import net.sourceforge.pmd.ast.ASTImportDeclaration;
9 import net.sourceforge.pmd.rules.ImportWrapper;
10
11 import java.util.HashSet JavaDoc;
12 import java.util.Iterator JavaDoc;
13 import java.util.Set JavaDoc;
14
15 public class DuplicateImportsRule extends AbstractRule {
16
17     private Set JavaDoc singleTypeImports;
18     private Set JavaDoc importOnDemandImports;
19
20     public Object JavaDoc visit(ASTCompilationUnit node, Object JavaDoc data) {
21         singleTypeImports = new HashSet JavaDoc();
22         importOnDemandImports = new HashSet JavaDoc();
23         super.visit(node, data);
24
25         // this checks for things like:
26
// import java.io.*;
27
// import java.io.File;
28
for (Iterator JavaDoc i = importOnDemandImports.iterator(); i.hasNext();) {
29             ImportWrapper thisImportOnDemand = (ImportWrapper) i.next();
30             for (Iterator JavaDoc j = singleTypeImports.iterator(); j.hasNext();) {
31                 ImportWrapper thisSingleTypeImport = (ImportWrapper) j.next();
32                 String JavaDoc singleTypePkg = thisSingleTypeImport.getName().substring(0, thisSingleTypeImport.getName().lastIndexOf('.'));
33                 if (thisImportOnDemand.getName().equals(singleTypePkg)) {
34                     addViolation(data, thisSingleTypeImport.getNode(), thisSingleTypeImport.getName());
35                 }
36             }
37         }
38         singleTypeImports.clear();
39         importOnDemandImports.clear();
40         return data;
41     }
42
43     public Object JavaDoc visit(ASTImportDeclaration node, Object JavaDoc data) {
44         ImportWrapper wrapper = new ImportWrapper(node.getImportedName(), node.getImportedName(), node.getImportedNameNode());
45
46         // blahhhh... this really wants to be ASTImportDeclaration to be polymorphic...
47
if (node.isImportOnDemand()) {
48             if (importOnDemandImports.contains(wrapper)) {
49                 addViolation(data, node.getImportedNameNode(), node.getImportedNameNode().getImage());
50             } else {
51                 importOnDemandImports.add(wrapper);
52             }
53         } else {
54             if (singleTypeImports.contains(wrapper)) {
55                 addViolation(data, node.getImportedNameNode(), node.getImportedNameNode().getImage());
56             } else {
57                 singleTypeImports.add(wrapper);
58             }
59         }
60         return data;
61     }
62
63 }
64
Popular Tags