1 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 ; 12 import java.util.Iterator ; 13 import java.util.Set ; 14 15 public class DuplicateImportsRule extends AbstractRule { 16 17 private Set singleTypeImports; 18 private Set importOnDemandImports; 19 20 public Object visit(ASTCompilationUnit node, Object data) { 21 singleTypeImports = new HashSet (); 22 importOnDemandImports = new HashSet (); 23 super.visit(node, data); 24 25 for (Iterator i = importOnDemandImports.iterator(); i.hasNext();) { 29 ImportWrapper thisImportOnDemand = (ImportWrapper) i.next(); 30 for (Iterator j = singleTypeImports.iterator(); j.hasNext();) { 31 ImportWrapper thisSingleTypeImport = (ImportWrapper) j.next(); 32 String 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 visit(ASTImportDeclaration node, Object data) { 44 ImportWrapper wrapper = new ImportWrapper(node.getImportedName(), node.getImportedName(), node.getImportedNameNode()); 45 46 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 |