Source Code Cross Referenced for ValidateExample.java in  » Library » Apache-commons-validator-1.3.1-src » org » apache » commons » validator » example » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » Library » Apache commons validator 1.3.1 src » org.apache.commons.validator.example 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


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:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.