001    /*
002     * Copyright 2002-2004 the original author or authors.
003     *
004     * Licensed under the Apache License, Version 2.0 (the "License"); you may not
005     * use this file except in compliance with the License. You may obtain a copy of
006     * the License at
007     *
008     * http://www.apache.org/licenses/LICENSE-2.0
009     *
010     * Unless required by applicable law or agreed to in writing, software
011     * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
012     * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
013     * License for the specific language governing permissions and limitations under
014     * the License.
015     */
016    package org.springframework.rules.constraint;
017    
018    import java.util.regex.Matcher;
019    import java.util.regex.Pattern;
020    
021    import org.springframework.rules.constraint.Constraint;
022    import org.springframework.rules.reporting.TypeResolvable;
023    import org.springframework.rules.reporting.TypeResolvableSupport;
024    
025    /**
026     * A constraint based on a regular expression pattern.
027     *
028     * @see TypeResolvable
029     * @see Pattern
030     *
031     * @author Keith Donald
032     */
033    public class RegexpConstraint extends TypeResolvableSupport implements Constraint {
034    
035            private Pattern pattern;
036    
037            /**
038             * Creates a RegexpConstraint with the provided regular expression pattern
039             * string.
040             *
041             * @param regex The regular expression
042             */
043            public RegexpConstraint(String regex) {
044                    this(regex, null);
045            }
046    
047            /**
048             * Creates a RegexpConstraint with the provided regular expression pattern
049             * string and sets the type of the constraint to provide specific messages.
050             *
051             * @param regex the regular expression.
052             * @param type  id used to fetch the message.
053             */
054            public RegexpConstraint(String regex, String type) {
055                    super(type);
056                    pattern = Pattern.compile(regex);
057            }
058    
059            /**
060             * Test if the argument matches the pattern.
061             */
062            public boolean test(Object argument) {
063                    if (argument == null) {
064                            argument = "";
065                    }
066                    Matcher m = pattern.matcher((CharSequence) argument);
067                    return m.matches();
068            }
069    
070            public String toString() {
071                    return getDefaultMessage() + " " + pattern.pattern();
072            }
073    }