View Javadoc

    1   package net.sourceforge.pmd.util;
    2
    3   import net.sourceforge.pmd.*;
    4   import net.sourceforge.pmd.rules.XPathRule;
    5
    6   import java.io.FileReader;
    7   import java.util.Iterator;
    8
    9   /**
    10   * To use this, do this:
    11   *
    12   * $ cat ~/tmp/Test.java
    13   * package foo;
    14   * public class Test {
    15   *  private int x;
    16   * }
    17   * $ java net.sourceforge.pmd.util.XPathTest -xpath "//FieldDeclaration" -filename "/home/tom/tmp/Test.java"
    18   * Match at line 3 column 11; package name 'foo'; variable name 'x'
    19   */
    20  public class XPathTest {
    21      public static void main(String[] args) throws Exception {
    22          String xpath;
    23          if (args[0].equals("-xpath")) {
    24              xpath = args[1];
    25          } else {
    26              xpath = args[3];
    27          }
    28          String filename;
    29          if (args[0].equals("-file")) {
    30              filename = args[1];
    31          } else {
    32              filename = args[3];
    33          }
    34          PMD pmd = new PMD();
    35          Rule rule = new XPathRule();
    36          rule.addProperty("xpath", xpath);
    37          rule.setMessage("Got one!");
    38          RuleSet ruleSet = new RuleSet();
    39          ruleSet.addRule(rule);
    40
    41          Report report = new Report();
    42          RuleContext ctx = new RuleContext();
    43          ctx.setReport(report);
    44          ctx.setSourceCodeFilename(filename);
    45
    46          pmd.processFile(new FileReader(filename), new RuleSets(ruleSet), ctx, SourceType.JAVA_15);
    47
    48          for (Iterator<IRuleViolation> i = report.iterator(); i.hasNext();) {
    49              IRuleViolation rv = i.next();
    50              String res = "Match at line " + rv.getBeginLine() + " column " + rv.getBeginColumn();
    51              if (rv.getPackageName() != null && !rv.getPackageName().equals("")) {
    52                  res += "; package name '" + rv.getPackageName() + "'";
    53              }
    54              if (rv.getMethodName() != null && !rv.getMethodName().equals("")) {
    55                  res += "; method name '" + rv.getMethodName() + "'";
    56              }
    57              if (rv.getVariableName() != null && !rv.getVariableName().equals("")) {
    58                  res += "; variable name '" + rv.getVariableName() + "'";
    59              }
    60              System.out.println(res);
    61          }
    62      }
    63  }