KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > cocoon > faces > samples > carstore > FormatValidator


1 /*
2  * $Id: FormatValidator.java 53793 2004-10-05 13:47:48Z vgritsenko $
3  */

4
5 /*
6  * Copyright 2004 Sun Microsystems, Inc. All Rights Reserved.
7  *
8  * Redistribution and use in source and binary forms, with or
9  * without modification, are permitted provided that the following
10  * conditions are met:
11  *
12  * - Redistributions of source code must retain the above copyright
13  * notice, this list of conditions and the following disclaimer.
14  *
15  * - Redistribution in binary form must reproduce the above
16  * copyright notice, this list of conditions and the following
17  * disclaimer in the documentation and/or other materials
18  * provided with the distribution.
19  *
20  * Neither the name of Sun Microsystems, Inc. or the names of
21  * contributors may be used to endorse or promote products derived
22  * from this software without specific prior written permission.
23  *
24  * This software is provided "AS IS," without a warranty of any
25  * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
26  * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
27  * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
28  * EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY
29  * DAMAGES OR LIABILITIES SUFFERED BY LICENSEE AS A RESULT OF OR
30  * RELATING TO USE, MODIFICATION OR DISTRIBUTION OF THIS SOFTWARE OR
31  * ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE
32  * FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT,
33  * SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER
34  * CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF
35  * THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS
36  * BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
37  *
38  * You acknowledge that this software is not designed, licensed or
39  * intended for use in the design, construction, operation or
40  * maintenance of any nuclear facility.
41  */

42
43 package org.apache.cocoon.faces.samples.carstore;
44
45 import javax.faces.application.FacesMessage;
46 import javax.faces.component.StateHolder;
47 import javax.faces.component.UIComponent;
48 import javax.faces.component.UIOutput;
49 import javax.faces.context.FacesContext;
50 import javax.faces.validator.Validator;
51 import javax.faces.validator.ValidatorException;
52
53 import java.util.ArrayList JavaDoc;
54 import java.util.Iterator JavaDoc;
55 import java.util.StringTokenizer JavaDoc;
56
57
58 /**
59  * <p><strong>FormatValidator</strong> is a Validator that checks
60  * the validity of String representation of the value of the
61  * associated component against a list of specified patterns.</p>
62  * <ul>
63  * <li>Call getValue() to retrieve the current value of the component.
64  * If it is <code>null</code>, exit immediately. (If null values
65  * should not be allowed, a RequiredValidator can be configured
66  * to check for this case.)</li>
67  * <li><code>formatPattern</code> is a <code>|</code> separated string
68  * of allowed patterns. </li>
69  * <li> This validator uses the following rules to match a value against a
70  * pattern.
71  * <li> if the matching pattern has a "A", then corresponding character
72  * in input value should be a letter.
73  * <li> if the matching pattern has a "9", then corresponding character
74  * in input value should be a number.
75  * <li> if the matching pattern has a "#", then corresponding character
76  * in input value should be a number or a letter.
77  * <li> Any other character must match literally.
78  * </ul> </ul>
79  *
80  * Validators have to be Serializable, so you can't maintain a reference to
81  * a java.sql.Connection or javax.sql.DataSource inside this class in case
82  * you need to hook upto the database or some other back end resource.
83  * One approach would be to use JNDI-based data source lookups or do
84  * this verification in the business tier.
85  */

86
87 public class FormatValidator implements Validator, StateHolder {
88
89
90     // ----------------------------------------------------- Manifest Constants
91

92     /**
93      * <p>The message identifier of the Message to be created if
94      * the validation fails. The message format string for this
95      * message may optionally include a <code>{0}</code> placeholder, which
96      * will be replaced by list of format patterns.</p>
97      */

98     public static final String JavaDoc FORMAT_INVALID_MESSAGE_ID =
99         "carstore.Format_Invalid";
100
101     private ArrayList JavaDoc formatPatternsList = null;
102
103
104     //
105
// Constructors and Initializers
106
//
107
public FormatValidator() {
108         super();
109     }
110
111
112     /**
113      * <p>Construct a FormatValidator with the specified formatPatterns
114      * String. </p>
115      *
116      * @param formatPatterns <code>|</code> separated String of format patterns
117      * that this validator must match against.
118      */

119     public FormatValidator(String JavaDoc formatPatterns) {
120         super();
121         this.formatPatterns = formatPatterns;
122         parseFormatPatterns();
123     }
124
125     //
126
// General Methods
127
//
128
/**
129      * <code>|</code> separated String of format patterns
130      * that this validator must match against.
131      */

132     private String JavaDoc formatPatterns = null;
133
134
135     /**
136      * <p>Return the format patterns that the validator supports.
137      */

138     public String JavaDoc getFormatPatterns() {
139
140         return (this.formatPatterns);
141
142     }
143
144
145     /**
146      * <p>Set the format patterns that the validator support..</p>
147      *
148      * @param formatPatterns <code>|</code> separated String of format patterns
149      * that this validator must match against.
150      */

151     public void setFormatPatterns(String JavaDoc formatPatterns) {
152
153         this.formatPatterns = formatPatterns;
154         parseFormatPatterns();
155     }
156
157
158     /**
159      * Parses the <code>formatPatterns</code> into validPatterns
160      * <code>ArrayList</code>. The delimiter must be "|".
161      */

162     public void parseFormatPatterns() {
163         if (formatPatterns == null || formatPatterns.length() == 0) {
164             return;
165         }
166         if (formatPatternsList != null) {
167             // formatPatterns have been parsed already.
168
return;
169         } else {
170             formatPatternsList = new ArrayList JavaDoc();
171         }
172         StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(formatPatterns, "|");
173         while (st.hasMoreTokens()) {
174             String JavaDoc token = st.nextToken();
175             formatPatternsList.add(token);
176         }
177     }
178
179
180     //
181
// Methods from Validator
182
//
183
public void validate(FacesContext context, UIComponent component,
184                          Object JavaDoc toValidate) {
185         boolean valid = false;
186         String JavaDoc value = null;
187         if ((context == null) || (component == null)) {
188             throw new NullPointerException JavaDoc();
189         }
190         if (!(component instanceof UIOutput)) {
191             return;
192         }
193
194         if (null == formatPatternsList || null == toValidate) {
195             return;
196         }
197
198         value = toValidate.toString();
199         // validate the value against the list of valid patterns.
200
Iterator JavaDoc patternIt = formatPatternsList.iterator();
201         while (patternIt.hasNext()) {
202             valid = isFormatValid(((String JavaDoc) patternIt.next()), value);
203             if (valid) {
204                 break;
205             }
206         }
207         if (!valid) {
208             FacesMessage errMsg = MessageFactory.getMessage(context,
209                                                             FORMAT_INVALID_MESSAGE_ID,
210                                                             (new Object JavaDoc[]{
211                                                                 formatPatterns
212                                                             }));
213             throw new ValidatorException(errMsg);
214         }
215     }
216
217
218     /**
219      * Returns true if the value matches one of the valid patterns.
220      */

221     protected boolean isFormatValid(String JavaDoc pattern, String JavaDoc value) {
222         boolean valid = true;
223         // if there is no pattern to match then value is valid
224
if (pattern == null || pattern.length() == 0) {
225             return true;
226         }
227         // if the value is null or a zero length string return false.
228
if (value == null || value.length() == 0) {
229             return false;
230         }
231         // if the length of the value is not equal to the length of the
232
// pattern string then the value is not valid.
233
if (value.length() != pattern.length()) {
234             return false;
235         }
236         value = value.trim();
237         // rules for matching.
238
// 1. if the matching pattern has a "A", then corresponding character
239
// in the value should a letter.
240
// 2. if the matching pattern has a "9", then corresponding character
241
// in the value should a number
242
// 3. if the matching pattern has a "#", then corresponding character
243
// in the value should a number or a letter
244
// 4.. any other character must match literally.
245
char[] input = value.toCharArray();
246         char[] fmtpattern = pattern.toCharArray();
247         for (int i = 0; i < fmtpattern.length; ++i) {
248             if (fmtpattern[i] == 'A') {
249                 if (!(Character.isLetter(input[i]))) {
250                     valid = false;
251                 }
252             } else if (fmtpattern[i] == '9') {
253                 if (!(Character.isDigit(input[i]))) {
254                     valid = false;
255                 }
256             } else if (fmtpattern[i] == '#') {
257                 if ((!(Character.isDigit(input[i]))) &&
258                     (!(Character.isLetter(input[i])))) {
259                     valid = false;
260                 }
261             } else {
262                 if (!(fmtpattern[i] == input[i])) {
263                     valid = false;
264                 }
265             }
266         }
267         return valid;
268
269     }
270
271
272     public Object JavaDoc saveState(FacesContext context) {
273         Object JavaDoc values[] = new Object JavaDoc[2];
274         values[0] = formatPatterns;
275         values[1] = formatPatternsList;
276         return (values);
277     }
278
279
280     public void restoreState(FacesContext context, Object JavaDoc state) {
281         Object JavaDoc values[] = (Object JavaDoc[]) state;
282         formatPatterns = (String JavaDoc) values[0];
283         formatPatternsList = (ArrayList JavaDoc) values[1];
284     }
285
286
287     private boolean transientValue = false;
288
289
290     public boolean isTransient() {
291         return (this.transientValue);
292     }
293
294
295     public void setTransient(boolean transientValue) {
296         this.transientValue = transientValue;
297     }
298 }
299
Popular Tags