View Javadoc

1   /**
2    * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
3    */
4   package net.sourceforge.pmd.lang.jsp.rule.basic;
5   
6   import java.util.HashSet;
7   import java.util.List;
8   import java.util.Set;
9   import java.util.StringTokenizer;
10  
11  import net.sourceforge.pmd.RuleContext;
12  import net.sourceforge.pmd.lang.ast.Node;
13  import net.sourceforge.pmd.lang.java.rule.ImportWrapper;
14  import net.sourceforge.pmd.lang.jsp.ast.ASTJspDirectiveAttribute;
15  import net.sourceforge.pmd.lang.jsp.rule.AbstractJspRule;
16  
17  public class DuplicateJspImportsRule extends AbstractJspRule {
18  
19      private Set<ImportWrapper> imports = new HashSet<ImportWrapper>();
20  
21      @Override
22      public void apply(List<? extends Node> nodes, RuleContext ctx) {
23  	/*
24  	 * TODO: This method is a hack! It's overriding the parent's method
25  	 * because the JSP parsing doesn't seem to hit ASTCompilationUnit
26  	 * properly
27  	 */
28  	imports.clear();
29  	super.apply(nodes, ctx);
30      }
31  
32      @Override
33      public Object visit(ASTJspDirectiveAttribute node, Object data) {
34  
35  	if (!"import".equals(node.getName())) {
36  	    return super.visit(node, data);
37  	}
38  	String values = node.getValue();
39  	StringTokenizer st = new StringTokenizer(values, ",");
40  	int count = st.countTokens();
41  	for (int ix = 0; ix < count; ix++) {
42  	    String token = st.nextToken();
43  	    ImportWrapper wrapper = new ImportWrapper(token, token, node);
44  	    if (imports.contains(wrapper)) {
45  		addViolation(data, node, node.getImage());
46  	    } else {
47  		imports.add(wrapper);
48  	    }
49  	}
50  	return super.visit(node, data);
51      }
52  
53  }