View Javadoc

1   /**
2    * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
3    */
4   package net.sourceforge.pmd.lang.xpath;
5   
6   import java.util.List;
7   import java.util.regex.Matcher;
8   import java.util.regex.Pattern;
9   
10  import net.sourceforge.pmd.lang.ast.xpath.Attribute;
11  
12  import org.jaxen.Context;
13  import org.jaxen.Function;
14  import org.jaxen.FunctionCallException;
15  import org.jaxen.SimpleFunctionContext;
16  import org.jaxen.XPathFunctionContext;
17  
18  // FIXME Can this function be extended to work on non-AST attributes?
19  public class MatchesFunction implements Function {
20  
21      public static void registerSelfInSimpleContext() {
22          // see http://jaxen.org/extensions.html
23          ((SimpleFunctionContext) XPathFunctionContext.getInstance()).registerFunction(null, "matches", new MatchesFunction());
24      }
25  
26      public Object call(Context context, List args) throws FunctionCallException {
27          if (args.isEmpty()) {
28              return Boolean.FALSE;
29          }
30          List attributes = (List) args.get(0);
31          Attribute attr = (Attribute) attributes.get(0);
32  
33          for(int i = 1; i < args.size(); i++) {
34              Pattern check = Pattern.compile((String) args.get(i));
35              Matcher matcher = check.matcher(attr.getStringValue());
36              if (matcher.find()) {
37                  return context.getNodeSet();
38              }
39          }
40          return Boolean.FALSE;
41      }
42  
43      public static boolean matches(String s, String... patterns) {
44  	for (String pattern: patterns) {
45              Pattern check = Pattern.compile(pattern);
46              Matcher matcher = check.matcher(s);
47              if (matcher.find()) {
48          	return true;
49              }
50          }
51          return false;
52      }
53  }