01: package net.sourceforge.pmd.util;
02:
03: import net.sourceforge.pmd.*;
04: import net.sourceforge.pmd.rules.XPathRule;
05:
06: import java.io.FileReader;
07: import java.util.Iterator;
08:
09: /**
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),
47: new RuleSets(ruleSet), ctx, SourceType.JAVA_15);
48:
49: for (Iterator<IRuleViolation> i = report.iterator(); i
50: .hasNext();) {
51: IRuleViolation rv = i.next();
52: String res = "Match at line " + rv.getBeginLine()
53: + " column " + rv.getBeginColumn();
54: if (rv.getPackageName() != null
55: && !rv.getPackageName().equals("")) {
56: res += "; package name '" + rv.getPackageName() + "'";
57: }
58: if (rv.getMethodName() != null
59: && !rv.getMethodName().equals("")) {
60: res += "; method name '" + rv.getMethodName() + "'";
61: }
62: if (rv.getVariableName() != null
63: && !rv.getVariableName().equals("")) {
64: res += "; variable name '" + rv.getVariableName() + "'";
65: }
66: System.out.println(res);
67: }
68: }
69: }
|