View Javadoc

    1   package net.sourceforge.pmd.cli;
    2
    3   import java.io.File;
    4   import java.io.FileReader;
    5   import java.util.Iterator;
    6
    7   import net.sourceforge.pmd.PMD;
    8   import net.sourceforge.pmd.PMDConfiguration;
    9   import net.sourceforge.pmd.Rule;
    10  import net.sourceforge.pmd.RuleContext;
    11  import net.sourceforge.pmd.RuleSet;
    12  import net.sourceforge.pmd.RuleSets;
    13  import net.sourceforge.pmd.RuleViolation;
    14  import net.sourceforge.pmd.SourceCodeProcessor;
    15  import net.sourceforge.pmd.lang.Language;
    16  import net.sourceforge.pmd.lang.rule.XPathRule;
    17  import net.sourceforge.pmd.util.StringUtil;
    18
    19  /**
    20   * To use this, do this:
    21   *
    22   * $ cat ~/tmp/Test.java
    23   * package foo;
    24   * public class Test {
    25   *  private int x;
    26   * }
    27   * $ java net.sourceforge.pmd.util.XPathTest -xpath "//FieldDeclaration" -filename "/home/tom/tmp/Test.java"
    28   * Match at line 3 column 11; package name 'foo'; variable name 'x'
    29   */
    30  public class XPathCLI {
    31
    32      public static void main(String[] args) throws Exception {
    33
    34          String xpath = args[0].equals("-xpath") ? args[1] : args[3];
    35          String filename = args[0].equals("-file") ? args[1] : args[3];
    36
    37          Rule rule = new XPathRule(xpath);
    38          rule.setMessage("Got one!");
    39          RuleSet ruleSet = RuleSet.createFor("", rule);
    40
    41          RuleContext ctx = PMD.newRuleContext(filename, new File(filename));
    42          ctx.setLanguageVersion(Language.JAVA.getDefaultVersion());
    43
    44          PMDConfiguration config = new PMDConfiguration();
    45          config.setDefaultLanguageVersion(Language.JAVA.getDefaultVersion());
    46
    47          new SourceCodeProcessor(config).processSourceCode(new FileReader(filename), new RuleSets(ruleSet), ctx);
    48
    49          for (Iterator<RuleViolation> i = ctx.getReport().iterator(); i.hasNext();) {
    50              RuleViolation rv = i.next();
    51              StringBuilder sb = new StringBuilder("Match at line " + rv.getBeginLine() + " column " + rv.getBeginColumn());
    52              if (StringUtil.isNotEmpty(rv.getPackageName())) {
    53                  sb.append("; package name '" + rv.getPackageName() + "'");
    54              }
    55              if (StringUtil.isNotEmpty(rv.getMethodName())) {
    56                  sb.append("; method name '" + rv.getMethodName() + "'");
    57              }
    58              if (StringUtil.isNotEmpty(rv.getVariableName())) {
    59                  sb.append("; variable name '" + rv.getVariableName() + "'");
    60              }
    61              System.out.println(sb.toString());
    62          }
    63      }
    64  }