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 net.sourceforge.pmd.lang.ast.Node;
7   import net.sourceforge.pmd.lang.java.ast.ASTImportDeclaration;
8   import net.sourceforge.pmd.lang.java.ast.ASTName;
9   import net.sourceforge.pmd.lang.java.ast.DummyJavaNode;
10  import net.sourceforge.pmd.lang.java.ast.TypeNode;
11  import net.sourceforge.pmd.lang.java.rule.ImportWrapper;
12  import net.sourceforge.pmd.lang.java.rule.imports.UnusedImportsRule;
13  
14  public class UnusedImports extends UnusedImportsRule {
15  
16      @Override
17      public Object visit(ASTImportDeclaration node, Object data) {
18  	if (node.isImportOnDemand()) {
19  	    ASTName importedType = (ASTName) node.jjtGetChild(0);
20  	    imports.add(new ImportWrapper(importedType.getImage(), null, node));
21  	} else {
22  	    super.visit(node, data);
23  	}
24  	return data;
25      }
26  
27      @Override
28      protected void check(Node node) {
29  	if (imports.isEmpty()) {
30  	    return;
31  	}
32  	ImportWrapper candidate = getImportWrapper(node);
33  	if (imports.contains(candidate)) {
34  	    imports.remove(candidate);
35  	    return;
36  	}
37  	if (TypeNode.class.isAssignableFrom(node.getClass()) && ((TypeNode) node).getType() != null) {
38  	    Class<?> c = ((TypeNode) node).getType();
39  	    if (c.getPackage() != null) {
40  		candidate = new ImportWrapper(c.getPackage().getName(), null, new DummyJavaNode(-1));
41  		if (imports.contains(candidate)) {
42  		    imports.remove(candidate);
43  		}
44  	    }
45  	}
46      }
47  }