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
54
55
56
57
58
59
60
61
62
63
64 @FileStatefulCheck
65 public class RedundantImportCheck
66 extends AbstractCheck {
67
68
69
70
71
72 public static final String MSG_LANG = "import.lang";
73
74
75
76
77
78 public static final String MSG_SAME = "import.same";
79
80
81
82
83
84 public static final String MSG_DUPLICATE = "import.duplicate";
85
86
87 private final Set<FullIdent> imports = new HashSet<>();
88
89 private final Set<FullIdent> staticImports = new HashSet<>();
90
91
92 private String pkgName;
93
94 @Override
95 public void beginTree(DetailAST aRootAST) {
96 pkgName = null;
97 imports.clear();
98 staticImports.clear();
99 }
100
101 @Override
102 public int[] getDefaultTokens() {
103 return getRequiredTokens();
104 }
105
106 @Override
107 public int[] getAcceptableTokens() {
108 return getRequiredTokens();
109 }
110
111 @Override
112 public int[] getRequiredTokens() {
113 return new int[] {
114 TokenTypes.IMPORT, TokenTypes.STATIC_IMPORT, TokenTypes.PACKAGE_DEF,
115 };
116 }
117
118 @Override
119 public void visitToken(DetailAST ast) {
120 if (ast.getType() == TokenTypes.PACKAGE_DEF) {
121 pkgName = FullIdent.createFullIdent(
122 ast.getLastChild().getPreviousSibling()).getText();
123 }
124 else if (ast.getType() == TokenTypes.IMPORT) {
125 final FullIdent imp = FullIdent.createFullIdentBelow(ast);
126 final String importText = imp.getText();
127 if (isFromPackage(importText, "java.lang")) {
128 log(ast, MSG_LANG, importText);
129 }
130
131
132 else if (pkgName != null && isFromPackage(importText, pkgName)) {
133 log(ast, MSG_SAME, importText);
134 }
135
136 imports.stream().filter(full -> importText.equals(full.getText()))
137 .forEach(full -> log(ast, MSG_DUPLICATE, full.getLineNo(), importText));
138
139 imports.add(imp);
140 }
141 else {
142
143 final FullIdent imp =
144 FullIdent.createFullIdent(
145 ast.getLastChild().getPreviousSibling());
146 staticImports.stream().filter(full -> imp.getText().equals(full.getText()))
147 .forEach(full -> log(ast, MSG_DUPLICATE, full.getLineNo(), imp.getText()));
148
149 staticImports.add(imp);
150 }
151 }
152
153
154
155
156
157
158
159
160 private static boolean isFromPackage(String importName, String pkg) {
161
162
163
164 final int index = importName.lastIndexOf('.');
165 final String front = importName.substring(0, index);
166 return pkg.equals(front);
167 }
168
169 }