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