(no commit message)
[utils] / support / src / main / java / wamblee / conditions / PropertyRegexCondition.java
1 /*
2  * Copyright 2005 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.wamblee.conditions;
18
19 import java.lang.reflect.InvocationTargetException;
20 import java.util.regex.Matcher;
21 import java.util.regex.Pattern;
22
23 import org.apache.commons.beanutils.PropertyUtils;
24
25 /**
26  * Condition to check whether a given property value matches a certain 
27  * regular expression.
28  */
29 public class PropertyRegexCondition<T> implements Condition<T> {
30     
31     /**
32      * Property name. 
33      */
34     private String _property;
35     
36     /**
37      * Regular expression. 
38      */
39     private Pattern _regex;
40     
41     /**
42      * Whether or not to convert the value to lowercase before matching. 
43      */
44     private boolean _tolower; 
45     
46     /**
47      * Constructs the condition. 
48      * @param aProperty Name of the property to examine. 
49      * @param aRegex Regular expression to use. 
50      * @param aTolower Whether or not to convert the value to lowercase before matching. 
51      */
52     public PropertyRegexCondition(String aProperty, String aRegex, boolean aTolower) {
53         _property = aProperty;
54         _regex = Pattern.compile(aRegex);
55         _tolower = aTolower;
56     }
57
58     /* (non-Javadoc)
59      * @see org.wamblee.conditions.Condition#matches(T)
60      */
61     public boolean matches(T aObject) {
62         try {
63             String value = PropertyUtils.getProperty(aObject, _property) + "";
64             if ( _tolower ) { 
65                 value = value.toLowerCase(); 
66             }
67             Matcher matcher = _regex.matcher(value); 
68             return matcher.matches(); 
69         } catch (IllegalAccessException e) {
70             throw new RuntimeException(e.getMessage(), e);
71         } catch (InvocationTargetException e) {
72             throw new RuntimeException(e.getMessage(), e);
73         } catch (NoSuchMethodException e) {
74             throw new RuntimeException(e.getMessage(), e);
75         }
76     }
77 }