01: /*
02: * Created on 15/03/2003
03: *
04: * To change this generated comment go to
05: * Window>Preferences>Java>Code Generation>Code Template
06: */
07: package org.acm.seguin.pmd.rules;
08:
09: import org.acm.seguin.pmd.AbstractRule;
10: import org.acm.seguin.pmd.RuleContext;
11: import net.sourceforge.jrefactory.ast.ASTCompilationUnit;
12: import net.sourceforge.jrefactory.ast.SimpleNode;
13: import net.sourceforge.jrefactory.ast.ASTVariableDeclaratorId;
14: import org.acm.seguin.pmd.jaxen.DocumentNavigator;
15: import org.jaxen.BaseXPath;
16: import org.jaxen.JaxenException;
17: import org.jaxen.XPath;
18:
19: import java.io.PrintStream;
20: import java.io.PrintWriter;
21: import java.text.MessageFormat;
22: import java.util.Iterator;
23:
24: /**
25: * @author daniels
26: *
27: * To change this generated comment go to
28: * Window>Preferences>Java>Code Generation>Code Template
29: */
30: public class XPathRule extends AbstractRule {
31:
32: private XPath xpath;
33:
34: public Object visit(ASTCompilationUnit node, Object data) {
35: try {
36: init();
37: for (Iterator iter = xpath.selectNodes(node).iterator(); iter
38: .hasNext();) {
39: SimpleNode actualNode = (SimpleNode) iter.next();
40: //System.out.println("actualNode="+actualNode);
41: RuleContext ctx = (RuleContext) data;
42: String msg = getMessage();
43: if (actualNode instanceof ASTVariableDeclaratorId
44: && getBooleanProperty("pluginname")) {
45: msg = MessageFormat.format(msg,
46: new Object[] { actualNode.getImage() });
47: }
48: ctx.getReport().addRuleViolation(
49: createRuleViolation(ctx, actualNode
50: .getBeginLine(), msg));
51: }
52: } catch (JaxenException ex) {
53: ex.printStackTrace();
54: throwJaxenAsRuntime(ex);
55: } catch (Exception ex) {
56: ex.printStackTrace();
57: }
58: return data;
59: }
60:
61: private void init() throws JaxenException {
62: if (xpath == null) {
63: String path = getStringProperty("xpath");
64: String subst = getStringProperty("subst");
65: if (subst != null && subst.length() > 0) {
66: path = MessageFormat.format(path,
67: new String[] { subst });
68: }
69: xpath = new BaseXPath(path, new DocumentNavigator());
70: }
71: }
72:
73: private static void throwJaxenAsRuntime(final JaxenException ex) {
74: throw new RuntimeException() {
75: public void printStackTrace() {
76: super .printStackTrace();
77: ex.printStackTrace();
78: }
79:
80: public void printStackTrace(PrintWriter writer) {
81: super .printStackTrace(writer);
82: ex.printStackTrace(writer);
83: }
84:
85: public void printStackTrace(PrintStream stream) {
86: super .printStackTrace(stream);
87: ex.printStackTrace(stream);
88: }
89:
90: public String getMessage() {
91: return super.getMessage() + ex.getMessage();
92: }
93: };
94: }
95: }
|