View Javadoc

1   /**
2    * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
3    */
4   package net.sourceforge.pmd.typeresolution.rules.imports;
5   
6   import net.sourceforge.pmd.ast.ASTImportDeclaration;
7   import net.sourceforge.pmd.ast.ASTName;
8   import net.sourceforge.pmd.ast.SimpleJavaNode;
9   import net.sourceforge.pmd.ast.SimpleNode;
10  import net.sourceforge.pmd.ast.TypeNode;
11  import net.sourceforge.pmd.rules.ImportWrapper;
12  import net.sourceforge.pmd.rules.imports.UnusedImportsRule;
13  
14  public class UnusedImports extends UnusedImportsRule {
15  
16      public Object visit(ASTImportDeclaration node, Object data) {
17          if (node.isImportOnDemand()) {
18              ASTName importedType = (ASTName) node.jjtGetChild(0);
19              imports.add(new ImportWrapper(importedType.getImage(), null, node));
20          } else {
21              super.visit(node, data);
22          }
23          return data;
24      }
25  
26      protected void check(SimpleNode node) {
27          if (imports.isEmpty()) {
28              return;
29          }
30          ImportWrapper candidate = getImportWrapper(node);
31          if (imports.contains(candidate)) {
32              imports.remove(candidate);
33              return;
34          }
35          if (TypeNode.class.isAssignableFrom(node.getClass()) && ((TypeNode) node).getType() != null) {
36              Class c = ((TypeNode) node).getType();
37              if (c.getPackage() != null) {
38  	            candidate = new ImportWrapper(c.getPackage().getName(), null, new SimpleJavaNode(-1));
39  	            if (imports.contains(candidate)) {
40  	                imports.remove(candidate);
41  	            }
42              }
43          }
44      }
45  }