View Javadoc
1   /*
2    * Copyright 2007 Kasper B. Graversen
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.supercsv.cellprocessor.constraint;
17  
18  import java.util.HashMap;
19  import java.util.Map;
20  import java.util.regex.Pattern;
21  import java.util.regex.PatternSyntaxException;
22  
23  import org.supercsv.cellprocessor.CellProcessorAdaptor;
24  import org.supercsv.cellprocessor.ift.StringCellProcessor;
25  import org.supercsv.exception.SuperCsvCellProcessorException;
26  import org.supercsv.exception.SuperCsvConstraintViolationException;
27  import org.supercsv.util.CsvContext;
28  
29  /**
30   * This constraint ensures that the input data matches the given regular expression.
31   * 
32   * @author Dominique De Vito
33   * @author James Bassett
34   * @since 1.50
35   */
36  public class StrRegEx extends CellProcessorAdaptor implements StringCellProcessor {
37  	
38  	private final String regex;
39  	private final Pattern regexPattern;
40  	
41  	private static final Map<String, String> REGEX_MSGS = new HashMap<String, String>();
42  	
43  	/**
44  	 * Constructs a new <tt>StrRegEx</tt> processor, which ensures that the input data matches the given regular
45  	 * expression.
46  	 * 
47  	 * @param regex
48  	 *            the regular expression to match
49  	 * @throws NullPointerException
50  	 *             if regex is null
51  	 * @throws IllegalArgumentException
52  	 *             if regex is empty
53  	 * @throws PatternSyntaxException
54  	 *             if regex is not a valid regular expression
55  	 */
56  	public StrRegEx(final String regex) {
57  		super();
58  		checkPreconditions(regex);
59  		this.regexPattern = Pattern.compile(regex);
60  		this.regex = regex;
61  	}
62  	
63  	/**
64  	 * Constructs a new <tt>StrRegEx</tt> processor, which ensures that the input data matches the given regular
65  	 * expression, then calls the next processor in the chain.
66  	 * 
67  	 * @param regex
68  	 *            the regular expression to match
69  	 * @param next
70  	 *            the next processor in the chain
71  	 * @throws NullPointerException
72  	 *             if regex is null
73  	 * @throws IllegalArgumentException
74  	 *             if regex is empty
75  	 * @throws PatternSyntaxException
76  	 *             if regex is not a valid regular expression
77  	 */
78  	public StrRegEx(final String regex, final StringCellProcessor next) {
79  		super(next);
80  		checkPreconditions(regex);
81  		this.regexPattern = Pattern.compile(regex);
82  		this.regex = regex;
83  	}
84  	
85  	/**
86  	 * Checks the preconditions for creating a new StrRegEx processor.
87  	 * 
88  	 * @param regex
89  	 *            the regular expression to match
90  	 * @throws NullPointerException
91  	 *             if regex is null
92  	 * @throws IllegalArgumentException
93  	 *             if regex is empty
94  	 */
95  	private static void checkPreconditions(final String regex) {
96  		if( regex == null ) {
97  			throw new NullPointerException("regex should not be null");
98  		} else if( regex.length() == 0 ) {
99  			throw new IllegalArgumentException("regex should not be empty");
100 		}
101 	}
102 	
103 	/**
104 	 * {@inheritDoc}
105 	 * 
106 	 * @throws SuperCsvCellProcessorException
107 	 *             if value is null
108 	 * @throws SuperCsvConstraintViolationException
109 	 *             if value doesn't match the regular expression
110 	 */
111 	public Object execute(final Object value, final CsvContext context) {
112 		validateInputNotNull(value, context);
113 		
114 		final boolean matches = regexPattern.matcher((String) value).matches();
115 		if( !matches ) {
116 			final String msg = REGEX_MSGS.get(regex);
117 			if( msg == null ) {
118 				throw new SuperCsvConstraintViolationException(String.format(
119 					"'%s' does not match the regular expression '%s'", value, regex), context, this);
120 			} else {
121 				throw new SuperCsvConstraintViolationException(
122 					String.format("'%s' does not match the constraint '%s' defined by the regular expression '%s'",
123 						value, msg, regex), context, this);
124 			}
125 		}
126 		return next.execute(value, context);
127 	}
128 	
129 	/**
130 	 * Register a message detailing in plain language the constraint representing a regular expression. For example, the
131 	 * regular expression \d{0,6}(\.\d{0,3})? could be associated with the message
132 	 * "up to 6 digits whole digits, followed by up to 3 fractional digits".
133 	 * 
134 	 * @param regex
135 	 *            the regular expression
136 	 * @param message
137 	 *            the message to associate with the regex
138 	 */
139 	public static void registerMessage(String regex, String message) {
140 		REGEX_MSGS.put(regex, message);
141 	}
142 	
143 }