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: */
017: package org.apache.commons.validator.example;
018:
019: import java.io.IOException;
020: import java.io.InputStream;
021: import java.text.MessageFormat;
022: import java.util.Iterator;
023: import java.util.Locale;
024: import java.util.Map;
025: import java.util.ResourceBundle;
026:
027: import org.apache.commons.validator.Field;
028: import org.apache.commons.validator.Form;
029: import org.apache.commons.validator.Validator;
030: import org.apache.commons.validator.ValidatorAction;
031: import org.apache.commons.validator.ValidatorException;
032: import org.apache.commons.validator.ValidatorResources;
033: import org.apache.commons.validator.ValidatorResult;
034: import org.apache.commons.validator.ValidatorResults;
035: import org.xml.sax.SAXException;
036:
037: /**
038: * <p>A simple example of setting up and using the Validator.</p>
039: *
040: * This simple example shows all the steps needed to set up and use
041: * the Validator. Note that in most cases, some kind of framework
042: * would be wrapped around the Validator, such as is the case with
043: * the Struts Validator Framework. However, should you wish to use
044: * the Validator against raw Beans in a pure Java application, you
045: * can see everything you need to know to get it working here.
046: *
047: * @version $Revision: 478334 $ $Date: 2006-11-22 21:31:54 +0000 (Wed, 22 Nov 2006) $
048: */
049: public class ValidateExample extends Object {
050:
051: /**
052: * We need a resource bundle to get our field names and errors messages
053: * from. Note that this is not strictly required to make the Validator
054: * work, but is a good coding practice.
055: */
056: private static ResourceBundle apps = ResourceBundle
057: .getBundle("org.apache.commons.validator.example.applicationResources");
058:
059: /**
060: * This is the main method that will be called to initialize the Validator, create some sample beans, and
061: * run the Validator against them.
062: */
063: public static void main(String[] args) throws ValidatorException,
064: IOException, SAXException {
065:
066: InputStream in = null;
067: ValidatorResources resources = null;
068:
069: try {
070:
071: // Create a new instance of a ValidatorResource, then get a stream
072: // handle on the XML file with the actions in it, and initialize the
073: // resources from it. This would normally be done by a servlet
074: // run during JSP initialization or some other application-startup
075: // routine.
076: in = ValidateExample.class
077: .getResourceAsStream("validator-example.xml");
078: resources = new ValidatorResources(in);
079:
080: } finally {
081: // Make sure we close the input stream.
082: if (in != null) {
083: in.close();
084: }
085: }
086:
087: // Create a test bean to validate against.
088: ValidateBean bean = new ValidateBean();
089:
090: // Create a validator with the ValidateBean actions for the bean
091: // we're interested in.
092: Validator validator = new Validator(resources, "ValidateBean");
093:
094: // Tell the validator which bean to validate against.
095: validator.setParameter(Validator.BEAN_PARAM, bean);
096:
097: ValidatorResults results = null;
098:
099: // Run the validation actions against the bean. Since all of the properties
100: // are null, we expect them all to error out except for street2, which has
101: // no validations (it's an optional property)
102:
103: results = validator.validate();
104: printResults(bean, results, resources);
105:
106: // Now set all the required properties, but make the age a non-integer.
107: // You'll notice that age will pass the required test, but fail the int
108: // test.
109: bean.setLastName("Tester");
110: bean.setFirstName("John");
111: bean.setStreet1("1 Test Street");
112: bean.setCity("Testville");
113: bean.setState("TE");
114: bean.setPostalCode("12345");
115: bean.setAge("Too Old");
116: results = validator.validate();
117: printResults(bean, results, resources);
118:
119: // Now only report failed fields
120: validator.setOnlyReturnErrors(true);
121: results = validator.validate();
122: printResults(bean, results, resources);
123:
124: // Now everything should pass.
125: validator.setOnlyReturnErrors(false);
126: bean.setAge("123");
127: results = validator.validate();
128: printResults(bean, results, resources);
129: }
130:
131: /**
132: * Dumps out the Bean in question and the results of validating it.
133: */
134: public static void printResults(ValidateBean bean,
135: ValidatorResults results, ValidatorResources resources) {
136:
137: boolean success = true;
138:
139: // Start by getting the form for the current locale and Bean.
140: Form form = resources.getForm(Locale.getDefault(),
141: "ValidateBean");
142:
143: System.out.println("\n\nValidating:");
144: System.out.println(bean);
145:
146: // Iterate over each of the properties of the Bean which had messages.
147: Iterator propertyNames = results.getPropertyNames().iterator();
148: while (propertyNames.hasNext()) {
149: String propertyName = (String) propertyNames.next();
150:
151: // Get the Field associated with that property in the Form
152: Field field = form.getField(propertyName);
153:
154: // Look up the formatted name of the field from the Field arg0
155: String prettyFieldName = apps.getString(field.getArg(0)
156: .getKey());
157:
158: // Get the result of validating the property.
159: ValidatorResult result = results
160: .getValidatorResult(propertyName);
161:
162: // Get all the actions run against the property, and iterate over their names.
163: Map actionMap = result.getActionMap();
164: Iterator keys = actionMap.keySet().iterator();
165: while (keys.hasNext()) {
166: String actName = (String) keys.next();
167:
168: // Get the Action for that name.
169: ValidatorAction action = resources
170: .getValidatorAction(actName);
171:
172: // If the result is valid, print PASSED, otherwise print FAILED
173: System.out.println(propertyName
174: + "["
175: + actName
176: + "] ("
177: + (result.isValid(actName) ? "PASSED"
178: : "FAILED") + ")");
179:
180: //If the result failed, format the Action's message against the formatted field name
181: if (!result.isValid(actName)) {
182: success = false;
183: String message = apps.getString(action.getMsg());
184: Object[] args = { prettyFieldName };
185: System.out.println(" Error message will be: "
186: + MessageFormat.format(message, args));
187:
188: }
189: }
190: }
191: if (success) {
192: System.out.println("FORM VALIDATION PASSED");
193: } else {
194: System.out.println("FORM VALIDATION FAILED");
195: }
196:
197: }
198:
199: }
|