01: package org.acm.seguin.pmd.rules;
02:
03: import org.acm.seguin.pmd.AbstractRule;
04: import org.acm.seguin.pmd.RuleContext;
05: import net.sourceforge.jrefactory.ast.ASTCompilationUnit;
06: import net.sourceforge.jrefactory.ast.ASTImportDeclaration;
07: import net.sourceforge.jrefactory.ast.SimpleNode;
08:
09: import java.text.MessageFormat;
10: import java.util.HashSet;
11: import java.util.Iterator;
12: import java.util.Set;
13:
14: public class DuplicateImportsRule extends AbstractRule {
15:
16: private Set singleTypeImports;
17: private Set importOnDemandImports;
18:
19: public Object visit(ASTCompilationUnit node, Object data) {
20: RuleContext ctx = (RuleContext) data;
21: singleTypeImports = new HashSet();
22: importOnDemandImports = new HashSet();
23: super .visit(node, data);
24:
25: // this checks for things like:
26: // import java.io.*;
27: // import java.io.File;
28: for (Iterator i = importOnDemandImports.iterator(); i.hasNext();) {
29: ImportWrapper this ImportOnDemand = (ImportWrapper) i.next();
30: for (Iterator j = singleTypeImports.iterator(); j.hasNext();) {
31: ImportWrapper this SingleTypeImport = (ImportWrapper) j
32: .next();
33: String singleTypePkg = this SingleTypeImport.getName()
34: .substring(
35: 0,
36: this SingleTypeImport.getName()
37: .lastIndexOf("."));
38: if (this ImportOnDemand.getName().equals(singleTypePkg)) {
39: String msg = MessageFormat.format(getMessage(),
40: new Object[] { this SingleTypeImport
41: .getName() });
42: ctx.getReport()
43: .addRuleViolation(
44: createRuleViolation(ctx,
45: this SingleTypeImport
46: .getLine(), msg));
47: }
48: }
49: }
50: singleTypeImports.clear();
51: importOnDemandImports.clear();
52: return data;
53: }
54:
55: public Object visit(ASTImportDeclaration node, Object data) {
56: ImportWrapper wrapper = new ImportWrapper(node
57: .getImportedNameNode().getImage(), node
58: .getImportedNameNode().getBeginLine());
59:
60: // blahhhh... this really wants to be ASTImportDeclaration to be polymorphic...
61: if (node.isImportOnDemand()) {
62: if (importOnDemandImports.contains(wrapper)) {
63: createRV((RuleContext) data, node.getImportedNameNode());
64: } else {
65: importOnDemandImports.add(wrapper);
66: }
67: } else {
68: if (singleTypeImports.contains(wrapper)) {
69: createRV((RuleContext) data, node.getImportedNameNode());
70: } else {
71: singleTypeImports.add(wrapper);
72: }
73: }
74: return data;
75: }
76:
77: private void createRV(RuleContext ctx, SimpleNode importNameNode) {
78: String msg = MessageFormat.format(getMessage(),
79: new Object[] { importNameNode.getImage() });
80: ctx.getReport().addRuleViolation(
81: createRuleViolation(ctx, importNameNode.getBeginLine(),
82: msg));
83: }
84: }
|