01: package net.sourceforge.pmd.rules.imports;
02:
03: import net.sourceforge.pmd.AbstractRule;
04: import net.sourceforge.pmd.ast.ASTImportDeclaration;
05: import net.sourceforge.pmd.ast.SimpleNode;
06:
07: import java.util.Arrays;
08: import java.util.HashSet;
09: import java.util.Set;
10:
11: public class DontImportJavaLang extends AbstractRule {
12:
13: private Set<Package> skipPackages = new HashSet<Package>(Arrays
14: .asList(new Package[] {
15: Package.getPackage("java.lang.ref"),
16: Package.getPackage("java.lang.reflect"),
17: Package.getPackage("java.lang.annotation"),
18: Package.getPackage("java.lang.instrument"),
19: Package.getPackage("java.lang.management"),
20: Package.getPackage("java.lang.Thread") }));
21:
22: private Package javaLangPackage = Package.getPackage("java.lang");
23:
24: public Object visit(ASTImportDeclaration node, Object data) {
25:
26: if (node.isStatic()) {
27: return data;
28: }
29:
30: if (node.getPackage() != null) {
31: if (node.getPackage().equals(javaLangPackage)
32: && !skipPackages.contains(node.getPackage())) {
33: addViolation(data, node);
34: }
35: } else {
36: String img = ((SimpleNode) node.jjtGetChild(0)).getImage();
37: if (img.startsWith("java.lang")) {
38: if (img.startsWith("java.lang.ref")
39: || img.startsWith("java.lang.reflect")
40: || img.startsWith("java.lang.annotation")
41: || img.startsWith("java.lang.instrument")
42: || img.startsWith("java.lang.management")
43: || img.startsWith("java.lang.Thread.")) {
44: return data;
45: }
46: addViolation(data, node);
47: }
48: }
49: return data;
50: }
51: }
|