KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > commons > validator > example > ValidateExample


1 /*
2  * $Id: ValidateExample.java 155434 2005-02-26 13:16:41Z dirkv $
3  * $Rev$
4  * $Date: 2005-02-26 05:16:41 -0800 (Sat, 26 Feb 2005) $
5  *
6  * ====================================================================
7  * Copyright 2000-2005 The Apache Software Foundation
8  *
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  * http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  */

21
22 package org.apache.commons.validator.example;
23
24 import java.io.IOException JavaDoc;
25 import java.io.InputStream JavaDoc;
26 import java.text.MessageFormat JavaDoc;
27 import java.util.Iterator JavaDoc;
28 import java.util.Locale JavaDoc;
29 import java.util.Map JavaDoc;
30 import java.util.ResourceBundle JavaDoc;
31
32 import org.apache.commons.validator.Field;
33 import org.apache.commons.validator.Form;
34 import org.apache.commons.validator.Validator;
35 import org.apache.commons.validator.ValidatorAction;
36 import org.apache.commons.validator.ValidatorException;
37 import org.apache.commons.validator.ValidatorResources;
38 import org.apache.commons.validator.ValidatorResult;
39 import org.apache.commons.validator.ValidatorResults;
40 import org.xml.sax.SAXException JavaDoc;
41
42 /**
43  * <p>A simple example of setting up and using the Validator.</p>
44  *
45  * This simple example shows all the steps needed to set up and use
46  * the Validator. Note that in most cases, some kind of framework
47  * would be wrapped around the Validator, such as is the case with
48  * the Struts Validator Framework. However, should you wish to use
49  * the Validator against raw Beans in a pure Java application, you
50  * can see everything you need to know to get it working here.
51  */

52 public class ValidateExample extends Object JavaDoc {
53
54     /**
55      * We need a resource bundle to get our field names and errors messages
56      * from. Note that this is not strictly required to make the Validator
57      * work, but is a good coding practice.
58      */

59     private static ResourceBundle JavaDoc apps =
60         ResourceBundle.getBundle(
61             "org.apache.commons.validator.example.applicationResources");
62
63     /**
64      * This is the main method that will be called to initialize the Validator, create some sample beans, and
65      * run the Validator against them.
66      */

67     public static void main(String JavaDoc[] args)
68         throws ValidatorException, IOException JavaDoc, SAXException JavaDoc {
69             
70         InputStream JavaDoc in = null;
71         ValidatorResources resources = null;
72         
73         try {
74         
75             // Create a new instance of a ValidatorResource, then get a stream
76
// handle on the XML file with the actions in it, and initialize the
77
// resources from it. This would normally be done by a servlet
78
// run during JSP initialization or some other application-startup
79
// routine.
80
in = ValidateExample.class.getResourceAsStream("validator-example.xml");
81             resources = new ValidatorResources(in);
82             
83         } finally {
84             // Make sure we close the input stream.
85
if (in != null) {
86                 in.close();
87             }
88         }
89         
90         // Create a test bean to validate against.
91
ValidateBean bean = new ValidateBean();
92         
93         // Create a validator with the ValidateBean actions for the bean
94
// we're interested in.
95
Validator validator = new Validator(resources, "ValidateBean");
96         
97         // Tell the validator which bean to validate against.
98
validator.setParameter(Validator.BEAN_PARAM, bean);
99         
100         ValidatorResults results = null;
101         
102         // Run the validation actions against the bean. Since all of the properties
103
// are null, we expect them all to error out except for street2, which has
104
// no validations (it's an optional property)
105

106         results = validator.validate();
107         printResults(bean, results, resources);
108         
109         // Now set all the required properties, but make the age a non-integer.
110
// You'll notice that age will pass the required test, but fail the int
111
// test.
112
bean.setLastName("Tester");
113         bean.setFirstName("John");
114         bean.setStreet1("1 Test Street");
115         bean.setCity("Testville");
116         bean.setState("TE");
117         bean.setPostalCode("12345");
118         bean.setAge("Too Old");
119         results = validator.validate();
120         printResults(bean, results, resources);
121         
122         // Now only report failed fields
123
validator.setOnlyReturnErrors(true);
124         results = validator.validate();
125         printResults(bean, results, resources);
126         
127         // Now everything should pass.
128
validator.setOnlyReturnErrors(false);
129         bean.setAge("123");
130         results = validator.validate();
131         printResults(bean, results, resources);
132     }
133
134     /**
135      * Dumps out the Bean in question and the results of validating it.
136      */

137     public static void printResults(
138         ValidateBean bean,
139         ValidatorResults results,
140         ValidatorResources resources) {
141             
142         boolean success = true;
143
144         // Start by getting the form for the current locale and Bean.
145
Form form = resources.getForm(Locale.getDefault(), "ValidateBean");
146
147         System.out.println("\n\nValidating:");
148         System.out.println(bean);
149
150         // Iterate over each of the properties of the Bean which had messages.
151
Iterator JavaDoc propertyNames = results.getPropertyNames().iterator();
152         while (propertyNames.hasNext()) {
153             String JavaDoc propertyName = (String JavaDoc) propertyNames.next();
154
155             // Get the Field associated with that property in the Form
156
Field field = form.getField(propertyName);
157
158             // Look up the formatted name of the field from the Field arg0
159
String JavaDoc prettyFieldName = apps.getString(field.getArg(0).getKey());
160
161             // Get the result of validating the property.
162
ValidatorResult result = results.getValidatorResult(propertyName);
163
164             // Get all the actions run against the property, and iterate over their names.
165
Map JavaDoc actionMap = result.getActionMap();
166             Iterator JavaDoc keys = actionMap.keySet().iterator();
167             while (keys.hasNext()) {
168                 String JavaDoc actName = (String JavaDoc) keys.next();
169
170                 // Get the Action for that name.
171
ValidatorAction action = resources.getValidatorAction(actName);
172
173                 // If the result is valid, print PASSED, otherwise print FAILED
174
System.out.println(
175                     propertyName
176                         + "["
177                         + actName
178                         + "] ("
179                         + (result.isValid(actName) ? "PASSED" : "FAILED")
180                         + ")");
181
182                 //If the result failed, format the Action's message against the formatted field name
183
if (!result.isValid(actName)) {
184                     success = false;
185                     String JavaDoc message = apps.getString(action.getMsg());
186                     Object JavaDoc[] args = { prettyFieldName };
187                     System.out.println(
188                         " Error message will be: "
189                             + MessageFormat.format(message, args));
190
191                 }
192             }
193         }
194         if (success) {
195             System.out.println("FORM VALIDATION PASSED");
196         } else {
197             System.out.println("FORM VALIDATION FAILED");
198         }
199
200     }
201
202 }
203
Popular Tags