~ubuntu-branches/ubuntu/trusty/libcommons-validator-java/trusty

« back to all changes in this revision

Viewing changes to src/example/org/apache/commons/validator/example/ValidateExample.java

  • Committer: Bazaar Package Importer
  • Author(s): Arnaud Vandyck
  • Date: 2004-11-19 13:35:53 UTC
  • Revision ID: james.westby@ubuntu.com-20041119133553-qtl7whjkjv9q1rbd
Tags: upstream-1.3
ImportĀ upstreamĀ versionĀ 1.3

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/*
 
2
 * $Header: /home/cvs/jakarta-commons/validator/src/example/org/apache/commons/validator/example/ValidateExample.java,v 1.17 2004/02/21 17:10:29 rleland Exp $
 
3
 * $Revision: 1.17 $
 
4
 * $Date: 2004/02/21 17:10:29 $
 
5
 *
 
6
 * ====================================================================
 
7
 * Copyright 2000-2004 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;
 
25
import java.io.InputStream;
 
26
import java.text.MessageFormat;
 
27
import java.util.Iterator;
 
28
import java.util.Locale;
 
29
import java.util.Map;
 
30
import java.util.ResourceBundle;
 
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;
 
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 {
 
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 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[] args)
 
68
        throws ValidatorException, IOException, SAXException {
 
69
            
 
70
        InputStream 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 propertyNames = results.getPropertyNames().iterator();
 
152
        while (propertyNames.hasNext()) {
 
153
            String propertyName = (String) 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 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 actionMap = result.getActionMap();
 
166
            Iterator keys = actionMap.keySet().iterator();
 
167
            while (keys.hasNext()) {
 
168
                String actName = (String) 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 message = apps.getString(action.getMsg());
 
186
                    Object[] 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
}