2 * Copyright 2005-2010 the original author or authors.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
16 package org.wamblee.conditions;
18 import java.lang.reflect.InvocationTargetException;
19 import java.lang.reflect.Method;
20 import java.util.regex.Matcher;
21 import java.util.regex.Pattern;
24 * Condition to check whether a given property of an object matches a certain
25 * regular expression. The method name to use of the object passed in to
26 * {@link #matches(Object)} is obtained using the Javabean conventions.
28 * @author Erik Brakkee
31 public class PropertyRegexCondition<T> implements Condition<T> {
35 private String property;
40 private Pattern regex;
43 * Whether or not to convert the value to lowercase before matching.
45 private boolean tolower;
48 * Constructs the condition.
51 * Name of the property to examine.
53 * Regular expression to use.
55 * Whether or not to convert the value to lowercase before
58 public PropertyRegexCondition(String aProperty, String aRegex,
61 regex = Pattern.compile(aRegex);
68 * @see org.wamblee.conditions.Condition#matches(T)
70 public boolean matches(T aObject) {
72 String readerName = "get" + property.substring(0, 1).toUpperCase() +
73 property.substring(1);
74 Method reader = aObject.getClass().getMethod(readerName);
75 String value = reader.invoke(aObject) + "";
78 value = value.toLowerCase();
81 Matcher matcher = regex.matcher(value);
83 return matcher.matches();
84 } catch (NoSuchMethodException e) {
85 throw new RuntimeException(e.getMessage(), e);
86 } catch (IllegalAccessException e) {
87 throw new RuntimeException(e.getMessage(), e);
88 } catch (InvocationTargetException e) {
89 throw new RuntimeException(e.getMessage(), e);