01 package net.sourceforge.pmd.util;
02
03 import java.io.FileReader;
04 import java.util.Iterator;
05
06 import net.sourceforge.pmd.RuleViolation;
07 import net.sourceforge.pmd.PMD;
08 import net.sourceforge.pmd.Report;
09 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.lang.Language;
14 import net.sourceforge.pmd.lang.rule.XPathRule;
15
16 /**
17 * To use this, do this:
18 *
19 * $ cat ~/tmp/Test.java
20 * package foo;
21 * public class Test {
22 * private int x;
23 * }
24 * $ java net.sourceforge.pmd.util.XPathTest -xpath "//FieldDeclaration" -filename "/home/tom/tmp/Test.java"
25 * Match at line 3 column 11; package name 'foo'; variable name 'x'
26 */
27 public class XPathTest {
28 public static void main(String[] args) throws Exception {
29 String xpath;
30 if (args[0].equals("-xpath")) {
31 xpath = args[1];
32 } else {
33 xpath = args[3];
34 }
35 String filename;
36 if (args[0].equals("-file")) {
37 filename = args[1];
38 } else {
39 filename = args[3];
40 }
41 PMD pmd = new PMD();
42 Rule rule = new XPathRule();
43 // rule.addProperty("xpath", xpath);
44 rule.setProperty(XPathRule.XPATH_DESCRIPTOR, xpath);
45 rule.setMessage("Got one!");
46 RuleSet ruleSet = new RuleSet();
47 ruleSet.addRule(rule);
48
49 Report report = new Report();
50 RuleContext ctx = new RuleContext();
51 ctx.setReport(report);
52 ctx.setSourceCodeFilename(filename);
53 ctx.setLanguageVersion(Language.JAVA.getDefaultVersion());
54
55 pmd.processFile(new FileReader(filename), new RuleSets(ruleSet), ctx);
56
57 for (Iterator<RuleViolation> i = report.iterator(); i.hasNext();) {
58 RuleViolation rv = i.next();
59 String res = "Match at line " + rv.getBeginLine() + " column " + rv.getBeginColumn();
60 if (rv.getPackageName() != null && !rv.getPackageName().equals("")) {
61 res += "; package name '" + rv.getPackageName() + "'";
62 }
63 if (rv.getMethodName() != null && !rv.getMethodName().equals("")) {
64 res += "; method name '" + rv.getMethodName() + "'";
65 }
66 if (rv.getVariableName() != null && !rv.getVariableName().equals("")) {
67 res += "; variable name '" + rv.getVariableName() + "'";
68 }
69 System.out.println(res);
70 }
71 }
72 }
|