1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package com.puppycrawl.tools.checkstyle.checks.imports;
21
22 import java.util.HashSet;
23 import java.util.Set;
24
25 import com.puppycrawl.tools.checkstyle.FileStatefulCheck;
26 import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
27 import com.puppycrawl.tools.checkstyle.api.DetailAST;
28 import com.puppycrawl.tools.checkstyle.api.FullIdent;
29 import com.puppycrawl.tools.checkstyle.api.TokenTypes;
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53 @FileStatefulCheck
54 public class RedundantImportCheck
55 extends AbstractCheck {
56
57
58
59
60
61 public static final String MSG_LANG = "import.lang";
62
63
64
65
66
67 public static final String MSG_SAME = "import.same";
68
69
70
71
72
73 public static final String MSG_DUPLICATE = "import.duplicate";
74
75
76 private final Set<FullIdent> imports = new HashSet<>();
77
78 private final Set<FullIdent> staticImports = new HashSet<>();
79
80
81 private String pkgName;
82
83 @Override
84 public void beginTree(DetailAST aRootAST) {
85 pkgName = null;
86 imports.clear();
87 staticImports.clear();
88 }
89
90 @Override
91 public int[] getDefaultTokens() {
92 return getRequiredTokens();
93 }
94
95 @Override
96 public int[] getAcceptableTokens() {
97 return getRequiredTokens();
98 }
99
100 @Override
101 public int[] getRequiredTokens() {
102 return new int[] {
103 TokenTypes.IMPORT, TokenTypes.STATIC_IMPORT, TokenTypes.PACKAGE_DEF,
104 };
105 }
106
107 @Override
108 public void visitToken(DetailAST ast) {
109 if (ast.getType() == TokenTypes.PACKAGE_DEF) {
110 pkgName = FullIdent.createFullIdent(
111 ast.getLastChild().getPreviousSibling()).getText();
112 }
113 else if (ast.getType() == TokenTypes.IMPORT) {
114 final FullIdent imp = FullIdent.createFullIdentBelow(ast);
115 if (isFromPackage(imp.getText(), "java.lang")) {
116 log(ast, MSG_LANG, imp.getText());
117 }
118
119
120 else if (pkgName != null && isFromPackage(imp.getText(), pkgName)) {
121 log(ast, MSG_SAME, imp.getText());
122 }
123
124 imports.stream().filter(full -> imp.getText().equals(full.getText()))
125 .forEach(full -> log(ast,
126 MSG_DUPLICATE, full.getLineNo(),
127 imp.getText()));
128
129 imports.add(imp);
130 }
131 else {
132
133 final FullIdent imp =
134 FullIdent.createFullIdent(
135 ast.getLastChild().getPreviousSibling());
136 staticImports.stream().filter(full -> imp.getText().equals(full.getText()))
137 .forEach(full -> log(ast,
138 MSG_DUPLICATE, full.getLineNo(), imp.getText()));
139
140 staticImports.add(imp);
141 }
142 }
143
144
145
146
147
148
149
150 private static boolean isFromPackage(String importName, String pkg) {
151
152
153
154 final int index = importName.lastIndexOf('.');
155 final String front = importName.substring(0, index);
156 return front.equals(pkg);
157 }
158
159 }