001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.openstreetmap.josm.data.validation.routines;
018
019import java.util.regex.Matcher;
020import java.util.regex.Pattern;
021
022/**
023 * <b>Regular Expression</b> validation (using JDK 1.4+ regex support).
024 * <p>
025 * Construct the validator either for a single regular expression or a set (array) of
026 * regular expressions. By default validation is <i>case sensitive</i> but constructors
027 * are provided to allow  <i>case in-sensitive</i> validation. For example to create
028 * a validator which does <i>case in-sensitive</i> validation for a set of regular
029 * expressions:
030 * <pre>
031 *         String[] regexs = new String[] {...};
032 *         RegexValidator validator = new RegexValidator(regexs, false);
033 * </pre>
034 * <p>
035 * <ul>
036 *   <li>Validate <code>true</code> or <code>false</code>:</li>
037 *   <ul>
038 *     <li><code>boolean valid = validator.isValid(value);</code></li>
039 *   </ul>
040 *   <li>Validate returning an aggregated String of the matched groups:</li>
041 *   <ul>
042 *     <li><code>String result = validator.validate(value);</code></li>
043 *   </ul>
044 *   <li>Validate returning the matched groups:</li>
045 *   <ul>
046 *     <li><code>String[] result = validator.match(value);</code></li>
047 *   </ul>
048 * </ul>
049 * <p>
050 * Cached instances pre-compile and re-use {@link Pattern}(s) - which according
051 * to the {@link Pattern} API are safe to use in a multi-threaded environment.
052 *
053 * @version $Revision: 1227719 $ $Date: 2012-01-05 18:45:51 +0100 (Thu, 05 Jan 2012) $
054 * @since Validator 1.4
055 */
056public class RegexValidator extends AbstractValidator {
057
058    private final Pattern[] patterns;
059
060    /**
061     * Construct a <i>case sensitive</i> validator for a single
062     * regular expression.
063     *
064     * @param regex The regular expression this validator will
065     * validate against
066     */
067    public RegexValidator(String regex) {
068        this(regex, true);
069    }
070
071    /**
072     * Construct a validator for a single regular expression
073     * with the specified case sensitivity.
074     *
075     * @param regex The regular expression this validator will
076     * validate against
077     * @param caseSensitive when <code>true</code> matching is <i>case
078     * sensitive</i>, otherwise matching is <i>case in-sensitive</i>
079     */
080    public RegexValidator(String regex, boolean caseSensitive) {
081        this(new String[] {regex}, caseSensitive);
082    }
083
084    /**
085     * Construct a <i>case sensitive</i> validator that matches any one
086     * of the set of regular expressions.
087     *
088     * @param regexs The set of regular expressions this validator will
089     * validate against
090     */
091    public RegexValidator(String[] regexs) {
092        this(regexs, true);
093    }
094
095    /**
096     * Construct a validator that matches any one of the set of regular
097     * expressions with the specified case sensitivity.
098     *
099     * @param regexs The set of regular expressions this validator will
100     * validate against
101     * @param caseSensitive when <code>true</code> matching is <i>case
102     * sensitive</i>, otherwise matching is <i>case in-sensitive</i>
103     */
104    public RegexValidator(String[] regexs, boolean caseSensitive) {
105        if (regexs == null || regexs.length == 0) {
106            throw new IllegalArgumentException("Regular expressions are missing");
107        }
108        patterns = new Pattern[regexs.length];
109        int flags =  (caseSensitive ? 0: Pattern.CASE_INSENSITIVE);
110        for (int i = 0; i < regexs.length; i++) {
111            if (regexs[i] == null || regexs[i].length() == 0) {
112                throw new IllegalArgumentException("Regular expression[" + i + "] is missing");
113            }
114            patterns[i] =  Pattern.compile(regexs[i], flags);
115        }
116    }
117
118    /**
119     * Validate a value against the set of regular expressions.
120     *
121     * @param value The value to validate.
122     * @return <code>true</code> if the value is valid
123     * otherwise <code>false</code>.
124     */
125    public boolean isValid(String value) {
126        if (value == null) {
127            return false;
128        }
129        for (int i = 0; i < patterns.length; i++) {
130            if (patterns[i].matcher(value).matches()) {
131                return true;
132            }
133        }
134        return false;
135    }
136
137    /**
138     * Validate a value against the set of regular expressions
139     * returning the array of matched groups.
140     *
141     * @param value The value to validate.
142     * @return String array of the <i>groups</i> matched if
143     * valid or <code>null</code> if invalid
144     */
145    public String[] match(String value) {
146        if (value == null) {
147            return null;
148        }
149        for (int i = 0; i < patterns.length; i++) {
150            Matcher matcher = patterns[i].matcher(value);
151            if (matcher.matches()) {
152                int count = matcher.groupCount();
153                String[] groups = new String[count];
154                for (int j = 0; j < count; j++) {
155                    groups[j] = matcher.group(j+1);
156                }
157                return groups;
158            }
159        }
160        return null;
161    }
162
163
164    /**
165     * Validate a value against the set of regular expressions
166     * returning a String value of the aggregated groups.
167     *
168     * @param value The value to validate.
169     * @return Aggregated String value comprised of the
170     * <i>groups</i> matched if valid or <code>null</code> if invalid
171     */
172    public String validate(String value) {
173        if (value == null) {
174            return null;
175        }
176        for (int i = 0; i < patterns.length; i++) {
177            Matcher matcher = patterns[i].matcher(value);
178            if (matcher.matches()) {
179                int count = matcher.groupCount();
180                if (count == 1) {
181                    return matcher.group(1);
182                }
183                StringBuffer buffer = new StringBuffer();
184                for (int j = 0; j < count; j++) {
185                    String component = matcher.group(j+1);
186                    if (component != null) {
187                        buffer.append(component);
188                    }
189                }
190                return buffer.toString();
191            }
192        }
193        return null;
194    }
195
196    /**
197     * Provide a String representation of this validator.
198     * @return A String representation of this validator
199     */
200    @Override
201    public String toString() {
202        StringBuffer buffer = new StringBuffer();
203        buffer.append("RegexValidator{");
204        for (int i = 0; i < patterns.length; i++) {
205            if (i > 0) {
206                buffer.append(",");
207            }
208            buffer.append(patterns[i].pattern());
209        }
210        buffer.append("}");
211        return buffer.toString();
212    }
213
214}