View Javadoc

    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.ASTClassOrInterfaceType;
    8   import net.sourceforge.pmd.ast.ASTCompilationUnit;
    9   import net.sourceforge.pmd.ast.ASTImportDeclaration;
    10  import net.sourceforge.pmd.ast.ASTName;
    11  import net.sourceforge.pmd.ast.SimpleJavaNode;
    12  import net.sourceforge.pmd.ast.SimpleNode;
    13  import net.sourceforge.pmd.rules.ImportWrapper;
    14
    15  import java.util.HashSet;
    16  import java.util.Iterator;
    17  import java.util.Set;
    18
    19  public class UnusedImportsRule extends AbstractRule {
    20
    21      private Set imports = new HashSet();
    22
    23      public Object visit(ASTCompilationUnit node, Object data) {
    24          imports.clear();
    25          super.visit(node, data);
    26          for (Iterator i = imports.iterator(); i.hasNext();) {
    27              ImportWrapper wrapper = (ImportWrapper) i.next();
    28              addViolation(data, wrapper.getNode(), wrapper.getFullName());
    29          }
    30          return data;
    31      }
    32
    33      public Object visit(ASTImportDeclaration node, Object data) {
    34          if (!node.isImportOnDemand()) {
    35              ASTName importedType = (ASTName) node.jjtGetChild(0);
    36              String className;
    37              if (isQualifiedName(importedType)) {
    38                  int lastDot = importedType.getImage().lastIndexOf('.') + 1;
    39                  className = importedType.getImage().substring(lastDot);
    40              } else {
    41                  className = importedType.getImage();
    42              }
    43              imports.add(new ImportWrapper(importedType.getImage(), className, node));
    44          }
    45
    46          return data;
    47      }
    48
    49      public Object visit(ASTClassOrInterfaceType node, Object data) {
    50          check(node);
    51          return super.visit(node, data);
    52      }
    53
    54      public Object visit(ASTName node, Object data) {
    55          check(node);
    56          return data;
    57      }
    58
    59      private void check(SimpleNode node) {
    60          String name;
    61          if (!isQualifiedName(node)) {
    62              name = node.getImage();
    63          } else {
    64              name = node.getImage().substring(0, node.getImage().indexOf('.'));
    65          }
    66          ImportWrapper candidate = new ImportWrapper(node.getImage(), name, new SimpleJavaNode(-1));
    67          if (imports.contains(candidate)) {
    68              imports.remove(candidate);
    69          }
    70      }
    71  }