View Javadoc
1   /**
2    * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
3    */
4   package net.sourceforge.pmd.lang.java.typeresolution.rules.imports;
5   
6   import java.util.Iterator;
7   
8   import net.sourceforge.pmd.lang.ast.Node;
9   import net.sourceforge.pmd.lang.java.ast.ASTImportDeclaration;
10  import net.sourceforge.pmd.lang.java.ast.ASTName;
11  import net.sourceforge.pmd.lang.java.ast.TypeNode;
12  import net.sourceforge.pmd.lang.java.rule.imports.UnusedImportsRule;
13  import net.sourceforge.pmd.lang.rule.ImportWrapper;
14  
15  public class UnusedImports extends UnusedImportsRule {
16  
17      @Override
18      public Object visit(ASTImportDeclaration node, Object data) {
19  	if (node.isImportOnDemand()) {
20  	    ASTName importedType = (ASTName) node.jjtGetChild(0);
21  	    imports.add(new ImportWrapper(importedType.getImage(), null, node, node.getType(), node.isStatic()));
22  	} else {
23  	    super.visit(node, data);
24  	}
25  	return data;
26      }
27  
28      @Override
29      protected void check(Node node) {
30  	if (imports.isEmpty()) {
31  	    return;
32  	}
33  	ImportWrapper candidate = getImportWrapper(node);
34  	Iterator<ImportWrapper> it = imports.iterator();
35  	while (it.hasNext()) {
36  	    ImportWrapper i = it.next();
37  	    if (i.matches(candidate)) {
38  	        it.remove();
39  	        return;
40  	    }
41  	}
42  	if (TypeNode.class.isAssignableFrom(node.getClass()) && ((TypeNode) node).getType() != null) {
43  	    Class<?> c = ((TypeNode) node).getType();
44  	    if (c.getPackage() != null) {
45  		candidate = new ImportWrapper(c.getPackage().getName(), null);
46  		if (imports.contains(candidate)) {
47  		    imports.remove(candidate);
48  		}
49  	    }
50  	}
51      }
52  }