1 20 package com.puppycrawl.tools.checkstyle.checks.imports; 21 22 import com.puppycrawl.tools.checkstyle.api.Check; 23 import com.puppycrawl.tools.checkstyle.api.DetailAST; 24 import com.puppycrawl.tools.checkstyle.api.FullIdent; 25 import com.puppycrawl.tools.checkstyle.api.TokenTypes; 26 27 import java.util.HashSet ; 28 import java.util.Iterator ; 29 import java.util.Set ; 30 31 56 public class RedundantImportCheck 57 extends Check 58 { 59 60 private String mPkgName; 61 62 private final Set mImports = new HashSet (); 63 64 private final Set mStaticImports = new HashSet (); 65 66 67 public void beginTree(DetailAST aRootAST) 68 { 69 mPkgName = null; 70 mImports.clear(); 71 mStaticImports.clear(); 72 } 73 74 75 public int[] getDefaultTokens() 76 { 77 return new int[] 78 {TokenTypes.IMPORT, 79 TokenTypes.STATIC_IMPORT, 80 TokenTypes.PACKAGE_DEF, }; 81 } 82 83 84 public void visitToken(DetailAST aAST) 85 { 86 if (aAST.getType() == TokenTypes.PACKAGE_DEF) { 87 mPkgName = FullIdent.createFullIdent( 88 aAST.getLastChild().getPreviousSibling()).getText(); 89 } 90 else if (aAST.getType() == TokenTypes.IMPORT) { 91 final FullIdent imp = FullIdent.createFullIdentBelow(aAST); 92 if (fromPackage(imp.getText(), "java.lang")) { 93 log(aAST.getLineNo(), aAST.getColumnNo(), "import.lang", 94 imp.getText()); 95 } 96 else if (fromPackage(imp.getText(), mPkgName)) { 97 log(aAST.getLineNo(), aAST.getColumnNo(), "import.same", 98 imp.getText()); 99 } 100 final Iterator it = mImports.iterator(); 102 while (it.hasNext()) { 103 final FullIdent full = (FullIdent) it.next(); 104 if (imp.getText().equals(full.getText())) { 105 log(aAST.getLineNo(), 106 aAST.getColumnNo(), 107 "import.duplicate", 108 new Integer (full.getLineNo()), 109 imp.getText()); 110 } 111 } 112 113 mImports.add(imp); 114 } 115 else { 116 final FullIdent imp = 118 FullIdent.createFullIdent( 119 aAST.getLastChild().getPreviousSibling()); 120 final Iterator it = mStaticImports.iterator(); 121 while (it.hasNext()) { 122 final FullIdent full = (FullIdent) it.next(); 123 if (imp.getText().equals(full.getText())) { 124 log(aAST.getLineNo(), 125 aAST.getColumnNo(), 126 "import.duplicate", 127 new Integer (full.getLineNo()), 128 imp.getText()); 129 } 130 } 131 132 mStaticImports.add(imp); 133 } 134 } 135 136 142 private static boolean fromPackage(String aImport, String aPkg) 143 { 144 boolean retVal = false; 145 if (aPkg == null) { 146 retVal = (aImport.indexOf('.') == -1); 148 } 149 else { 150 final int index = aImport.lastIndexOf('.'); 151 if (index != -1) { 152 final String front = aImport.substring(0, index); 153 retVal = front.equals(aPkg); 154 } 155 } 156 return retVal; 157 } 158 } 159 | Popular Tags |