View Javadoc

1   /***
2    * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
3   */
4   package net.sourceforge.pmd.rules;
5   
6   import net.sourceforge.pmd.AbstractRule;
7   import net.sourceforge.pmd.RuleContext;
8   import net.sourceforge.pmd.ast.ASTCompilationUnit;
9   import net.sourceforge.pmd.ast.ASTVariableDeclaratorId;
10  import net.sourceforge.pmd.ast.SimpleNode;
11  import net.sourceforge.pmd.jaxen.DocumentNavigator;
12  import org.jaxen.BaseXPath;
13  import org.jaxen.JaxenException;
14  import org.jaxen.XPath;
15  
16  import java.io.PrintStream;
17  import java.io.PrintWriter;
18  import java.text.MessageFormat;
19  import java.util.Iterator;
20  
21  public class XPathRule extends AbstractRule {
22  
23      private XPath xpath;
24  
25      public Object visit(ASTCompilationUnit node, Object data) {
26          try {
27              init();
28              for (Iterator iter = xpath.selectNodes(node).iterator(); iter.hasNext();) {
29                  SimpleNode actualNode = (SimpleNode) iter.next();
30                  RuleContext ctx = (RuleContext) data;
31                  String msg = getMessage();
32                  if (actualNode instanceof ASTVariableDeclaratorId && getBooleanProperty("pluginname")) {
33                      msg = MessageFormat.format(msg, new Object[]{actualNode.getImage()});
34                  }
35                  ctx.getReport().addRuleViolation(createRuleViolation(ctx, actualNode.getBeginLine(), msg));
36              }
37          } catch (JaxenException ex) {
38              throwJaxenAsRuntime(ex);
39          }
40          return data;
41      }
42  
43      private void init() throws JaxenException {
44          if(xpath == null) {
45              String path = getStringProperty("xpath");
46              String subst = getStringProperty("subst");
47              if(subst != null && subst.length() > 0) {
48  				path = MessageFormat.format(path, new String[] {subst});
49              }
50              xpath = new BaseXPath(path, new DocumentNavigator());
51          }
52      }
53  
54      private static void throwJaxenAsRuntime(final JaxenException ex) {
55          throw new RuntimeException() {
56              public void printStackTrace() {
57                  super.printStackTrace();
58                  ex.printStackTrace();
59              }
60              public void printStackTrace(PrintWriter writer) {
61                  super.printStackTrace(writer);
62                  ex.printStackTrace(writer);
63              }
64              public void printStackTrace(PrintStream stream) {
65                  super.printStackTrace(stream);
66                  ex.printStackTrace(stream);
67              }
68              public String getMessage() {
69                  return super.getMessage() + ex.getMessage();
70              }
71          };
72      }
73  }