View Javadoc
1   package com.randomnoun.common.jexl.eval.function;
2   
3   /* (c) 2013-2018 randomnoun. All Rights Reserved. This work is licensed under a
4    * BSD Simplified License. (http://www.randomnoun.com/bsd-simplified.html)
5    */
6   
7   import java.util.List;
8   
9   import com.randomnoun.common.jexl.eval.EvalContext;
10  import com.randomnoun.common.jexl.eval.EvalException;
11  import com.randomnoun.common.jexl.eval.EvalFunction;
12  
13  /** Defines a like() function.
14   *
15   * <p>like() takes a two parameters, the string being matched and the SQL LIKE pattern we
16   * are matching on. The LIKE pattern uses the "%" character to represent any sequence of
17   * characters, and "_" to indicate a single character. This class automatically deals
18   * with conflicts with the Java regex parser, so the pattern may contain any other
19   * Unicode or regular expression characters, which will be treated like any other
20   * character.
21   *
22   * <p>The result of the function is of type Boolean.
23   */
24  public class LikeFunction
25      implements EvalFunction
26  {
27      /** Implements the function as per the class description. */
28      public Object evaluate(String functionName, EvalContext context, List<Object> arguments)
29          throws EvalException
30      {
31          if (arguments.size() != 2) { throw new EvalException(functionName + "() must contain two parameters"); }
32          if (!(arguments.get(0) instanceof String)) {
33              throw new EvalException(functionName + "() parameter 1 must be a string type");
34          }
35          if (!(arguments.get(1) instanceof String)) {
36              throw new EvalException(functionName + "() parameter 2 must be a string type");
37          }
38  
39          String arg0 = (String)arguments.get(0);
40          String arg1 = (String)arguments.get(1);
41          if (arg0 == null) {
42              throw new EvalException(functionName + "() first parameter cannot be null");
43          }
44          if (arg1 == null) {
45              throw new EvalException(functionName + "() second parameter cannot be null");
46          }
47  
48          // convert arg1 into a regex; first escape any chars that may confuse the
49          // regex engine (see java.util.regex.Pattern class to see how this list was derived)
50          String specialChars = "\\[]^$?*+{}|().";
51          for (int i = 0; i < specialChars.length(); i++) {
52              arg1 = arg1.replaceAll("\\" + specialChars.charAt(i),
53                      "\\\\" + "\\" + specialChars.charAt(i));
54          }
55          arg1 = arg1.replaceAll("%", ".*");
56          arg1 = arg1.replaceAll("_", ".");
57          return Boolean.valueOf(arg0.matches(arg1));
58      }
59  }