View Javadoc

1   /*
2    * Copyright 2004-2009 the original author or authors.
3    * 
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    * 
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    * 
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package org.springmodules.validation.valang.functions;
18  
19  import java.util.HashMap;
20  import java.util.Map;
21  import java.util.regex.Pattern;
22  
23  /**
24   * Regular expression match function. Takes two arguments: the pattern as a string and the string
25   * to be matched. The toString method of the second parameter value is called to retrieve the
26   * string value. This function is not null-safe.
27   *
28   * @author Steven Devijver
29   * @since Sep 15, 2005
30   */
31  public class RegExFunction extends AbstractFunction {
32  
33      private Map patternCache = null;
34  
35      public RegExFunction(Function[] arguments, int line, int column) {
36          super(arguments, line, column);
37          definedExactNumberOfArguments(2);
38          patternCache = new HashMap();
39      }
40  
41      protected Object doGetResult(Object target) throws Exception {
42          Object value = getArguments()[0].getResult(target);
43          if (value instanceof String) {
44              Pattern pattern = null;
45              if (patternCache.containsKey(value)) {
46                  pattern = (Pattern) patternCache.get(value);
47              } else {
48                  pattern = Pattern.compile((String) value);
49                  patternCache.put(value, pattern);
50              }
51              String str = getArguments()[1].getResult(target).toString();
52              return pattern.matcher(str).matches() ? Boolean.TRUE : Boolean.FALSE;
53          } else {
54              throw new Exception("No String value for regular expression");
55          }
56      }
57  
58  }