View Javadoc
1   /**
2    * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
3    */
4   package net.sourceforge.pmd.lang.java.xpath;
5   
6   import java.util.List;
7   
8   import net.sourceforge.pmd.lang.ast.AbstractNode;
9   import net.sourceforge.pmd.lang.ast.Node;
10  import net.sourceforge.pmd.lang.java.ast.ASTCompilationUnit;
11  import net.sourceforge.pmd.lang.java.ast.Comment;
12  
13  import org.jaxen.Context;
14  import org.jaxen.Function;
15  import org.jaxen.FunctionCallException;
16  import org.jaxen.SimpleFunctionContext;
17  import org.jaxen.XPathFunctionContext;
18  
19  /**
20   * The XPath query "//VariableDeclarator[contains(getCommentOn(), '//password')]" 
21   * will find all variables declared that are annotated with the password comment.
22   *  
23   * @author Andy Throgmorton
24   */
25  public class GetCommentOnFunction implements Function {
26  
27      public static void registerSelfInSimpleContext() {
28          // see http://jaxen.org/extensions.html
29          ((SimpleFunctionContext) XPathFunctionContext.getInstance()).registerFunction(null, "getCommentOn", new GetCommentOnFunction());
30      }
31  
32      public Object call(Context context, List args) throws FunctionCallException {
33          if (!args.isEmpty()) {
34              return Boolean.FALSE;
35          }
36          Node n = (Node) context.getNodeSet().get(0);
37          if (n instanceof AbstractNode) {
38              int codeBeginLine = ((AbstractNode) n).getBeginLine();
39              int codeEndLine = ((AbstractNode) n).getEndLine();
40  
41              List<Comment> commentList = ((AbstractNode)n).getFirstParentOfType(ASTCompilationUnit.class).getComments();
42              for (Comment comment : commentList) {
43                  if (comment.getBeginLine() == codeBeginLine || comment.getEndLine() == codeEndLine) {
44                      return comment.getImage();
45                  }
46              }
47          }
48          return Boolean.FALSE;
49      }
50  }