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