commons-validator-1.4.0-src/LICENSE.txt100644 765 0 26136 11711227702 20656 0ustarsimonetripodiwheel 0 0 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. commons-validator-1.4.0-src/NOTICE.txt100644 765 0 262 11711227702 20505 0ustarsimonetripodiwheel 0 0 Apache Commons Validator Copyright 2001-2012 The Apache Software Foundation This product includes software developed by The Apache Software Foundation (http://www.apache.org/). commons-validator-1.4.0-src/RELEASE-NOTES.txt100644 765 0 14011 11711227702 21527 0ustarsimonetripodiwheel 0 0 $Id: RELEASE-NOTES.txt 1236877 2012-01-27 20:36:39Z sebb $ Commons Validator Package Version 1.4.0 Release Notes INTRODUCTION ============ This is a maintenance release with improvements. New projects are encouraged to use this release of Commons Validator. IMPORTANT NOTES ================ BREAKING CHANGES: * NONE. DEPENDENCIES ============= The dependencies for Validator 1.4 have only one change since the 1.3.1 release, in that the Jakarta ORO dependency has been removed (VALIDATOR-193). For the current list of dependencies, please see http://commons.apache.org/validator/dependencies.html BUGS FROM PREVIOUS RELEASE =========================== * [VALIDATOR-216] - UrlValidator rejects top-level domains (TLDs) with more than 4 characters * [VALIDATOR-218] - UrlValidator fail when path contains "(" / ")" * [VALIDATOR-220] - EmailValidator fails with ArrayIndexOutOfBoundsException on domain names longer than 10 segments * [VALIDATOR-223] - Move the trim() function from validateRequired.js to validateUtilities.js * [VALIDATOR-271] - gmail testing addresses do not validate * [VALIDATOR-276] - isValidURL call returns false for file scheme/protocol when URL is correct * [VALIDATOR-282] - formatDate(String value, Locale locale) in GenericTypeValidator uses DateFormat.SHORT instead of DateFormat.DEFAULT * [VALIDATOR-286] - isValid method for EmailValidator should return false for domain with special characters only * [VALIDATOR-289] - UrlValidator.isValid does not properly validate *.travel domains * [VALIDATOR-292] - @localhost and @localhost.localdomain email addresses aren't correctly detected as valid * [VALIDATOR-293] - Email validation fails with dash or hyphen at end of local address IMPROVEMENTS OVER PREVIOUS RELEASE =================================== * [VALIDATOR-188] - Extend ISBN validator to support smooth transition to ISBN-13 / EAN-13 standard * [VALIDATOR-191] - Remove the dependency on Jakarta ORO (move to JDK 1.4 regular expression support) * [VALIDATOR-192] - Adding ISBNValidator to GenericValidator * [VALIDATOR-193] - Removing ORO dep. from GenericValidator * [VALIDATOR-203] - Refactor UrlValidator - especially the line 370-ish. * [VALIDATOR-211] - Upgrade to Digester 1.8 * [VALIDATOR-213] - Factor out Check Digit logic into separate implementations * [VALIDATOR-214] - New Regular Expression validator using JDK 1.4's Regex * [VALIDATOR-215] - New generic CodeValidator that validates format, length and Check Digit for a code * [VALIDATOR-224] - validatorUtilities.js - replace colon characters in the function name (JSF/Shale) * [VALIDATOR-226] - Null-Stream input to ValidatorResources leads to MalformedURLExceptions * [VALIDATOR-232] - Add script attribute to control script generation * [VALIDATOR-233] - Switch to using Version 0.4.3 of the Dojo Compressor from the maven repo * [VALIDATOR-234] - Create 1.4 DTD * [VALIDATOR-240] - Support the 65 prefix for Discover Card * [VALIDATOR-241] - New InetAdress Validator implementation * [VALIDATOR-242] - Move EmailValidator to routines package * [VALIDATOR-247] - Move CreditCardValidator to routines package and refactor to use new CodeValidator * [VALIDATOR-248] - Add an option to allow 'localhost' as a valid hostname part in the URL * [VALIDATOR-249] - Add Diners card validation to CreditCardValidator * [VALIDATOR-250] - Banking CheckDigit implementations: ABA, CUSIP, IBAN, ISIN and Sedol * [VALIDATOR-251] - url with brackets is not validated thru URLvalidator class. * [VALIDATOR-252] - Performance improvement of DomainValidator by change the regular expression * [VALIDATOR-275] - EmailValidator.isValid(String) follows RFC822 but violates RFC1034 * [VALIDATOR-288] - UrlValidator does not validate URL with simple domains (eg: http://hostname ) * [VALIDATOR-300] - clirr Report - EmailValidator.isValidIpAddress() argument type change * [VALIDATOR-301] - CheckStyle and FindBug Issues - inner classes and key sets DEPRECATIONS ============ * Most of the org.apache.commons.validator classes have been deprecated, in favour of the new org.apache.commons.validator.routines classes. OTHER NOTES ============ Users should be aware of the following potential issues with migration: * The protected method validator.EmailValidator.isValidIpAddress() previously exposed a Jakarta ORO class via its signature. The signature has been modified to accept a a java.lang.String and is not therefore not compatible. However, this class is deprecated and clients should use the equivalent class in the validator.routines package. * Invocations of the method GenericValidator.matchRegexp() should be inspected for semantic differences between Jakarta ORO and Java regular expressions. commons-validator-1.4.0-src/build-javascript.xml100644 765 0 14664 11711227702 23023 0ustarsimonetripodiwheel 0 0 commons-validator-1.4.0-src/build.properties.sample100644 765 0 5112 11711227702 23477 0ustarsimonetripodiwheel 0 0 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # $Id: build.properties.sample 1237244 2012-01-29 11:23:19Z simonetripodi $ # $Rev: 1237244 $ # $Date: 2012-01-29 12:23:19 +0100 (Sun, 29 Jan 2012) $ # ----------------------------------------------------------------------------- # This is an example "build.properties" file. Make any changes you need, # and rename this file to "build.properties" in the same directory that # contains the "build.xml" file. # ----------------------------------------------------------------------------- apache.dir=D:/Java/Programs/Apache # The JAR file containing version 1.7.0 (or later) of the Beanutils package # from the Jakarta Commons project. commons-beanutils.jar=../beanutils/dist/commons-beanutils.jar # The JAR file containing version 1.8 (or later) of the Digester package # from the Jakarta Commons project. commons-digester.jar=../digester/dist/commons-digester.jar # The JAR file containing version 1.1 (or later) of the Logging package # from the Jakarta Commons project. commons-logging.jar=../logging/dist/commons-logging.jar # The JAR file containing version 3.8.1 (or later) of # JUnit Unit Testing (http://www.junit.org) junit.jar=D:/java/Lib/junit3.8.1/junit.jar # Needed for building the version Javadocs xerces.jar=${apache.dir}/xerces-2_5_0/xercesImpl.jar # jsdoc 1.5.2 or Newer is needed for building the Javascript Javadocs jsdoc.home=/cygdrive/d/Projects/Sourceforge/JsDoc/JSDoc-1.5.2 #############################Maven Variables ####################################### # CVS Start Change Log date maven.changelog.range=2000 # If you are using ssh tunneling & have a .cvspass file setup cvs.developer.host=localhost # Maven deploy user cvs.developer.id=rleland ######## Maven Variables located in your $HOME/build.properties #### # maven.username=rleland # maven.mode.online=true # maven.debugOn=true commons-validator-1.4.0-src/build.xml100644 765 0 50441 11711227702 20650 0ustarsimonetripodiwheel 0 0 commons-validator-1.4.0-src/checkstyle.xml100644 765 0 12631 11711227702 21706 0ustarsimonetripodiwheel 0 0 commons-validator-1.4.0-src/doap_validator.rdf100644 765 0 7626 11711227702 22503 0ustarsimonetripodiwheel 0 0 Apache Commons Validator Commons Validator Java Validation Framework and Routines Commons Validator provides the building blocks for both client side validation and server side data validation. It may be used standalone or with a framework like Struts. Latest Stable Release 2006-11-28 1.3.1 1.3.0 2006-03-24 1.3.0 1.2.0 2005-11-15 1.2.0 1.1.4 2004-11-12 1.1.4 1.1.3 2004-08-25 1.1.3 1.1.2 (alpha) 2004-04-03 1.1.2 1.1.1 (alpha) 2003-12-15 1.1.1 1.1.0 (alpha) 2003-08-26 1.1.0 1.0.2 2003-04-17 1.0.2 1.0.1 2002-12-16 1.0.1 1.0 2002-11-01 1.0 commons-validator-1.4.0-src/license-header.txt100644 765 0 1443 11711227702 22416 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ commons-validator-1.4.0-src/pom.xml100644 765 0 23606 11711227702 20347 0ustarsimonetripodiwheel 0 0 org.apache.commons commons-parent 23 4.0.0 commons-validator commons-validator 1.4.0 Commons Validator Commons Validator provides the building blocks for both client side validation and server side data validation. It may be used standalone or with a framework like Struts. http://commons.apache.org/validator/ jira http://issues.apache.org/jira/browse/VALIDATOR 2002 Don Brown mrdon mrdon@apache.org Martin Cooper martinc martinc@apache.org David Graham dgraham dgraham@apache.org Ted Husted husted husted@apache.org Rob Leland rleland rleland at apache.org Craig McClanahan craigmcc craigmcc@apache.org James Mitchell jmitchell jmitchell NOSPAM apache.org EdgeTech, Inc Niall Pemberton niallp James Turner turner turner@apache.org David Winterfeldt dwinterfeldt dwinterfeldt@apache.org Henri Yandell bayard Ben Speakmon bspeakmon Nick Burch nick SimoneTripodi simonetripodi Makoto Uchino scm:svn:http://svn.apache.org/repos/asf/commons/proper/validator/tags/VALIDATOR_1_4_0_RC2 scm:svn:https://svn.apache.org/repos/asf/commons/proper/validator/tags/VALIDATOR_1_4_0_RC2 http://svn.apache.org/viewvc/commons/proper/validator/tags/VALIDATOR_1_4_0_RC2 apache.website Apache Commons Release Site ${commons.deployment.protocol}://people.apache.org/www/commons.apache.org/validator/ 1.4 1.4 validator 1.4.0 RC2 (requires JDK 1.4) 1.3.1 (requires JDK 1.3) VALIDATOR 12310494 ${basedir} META-INF NOTICE.txt LICENSE.txt ${basedir}/src/main/resources ${basedir}/src/javascript **/*.js maven-antrun-plugin javascript.compress prepare-package run maven-assembly-plugin ${basedir}/src/main/assembly/bin.xml ${basedir}/src/main/assembly/src.xml gnu false commons-beanutils commons-beanutils 1.8.3 commons-digester commons-digester 1.8 commons-beanutils commons-beanutils commons-logging commons-logging commons-logging commons-logging 1.1.1 junit junit 3.8.2 test org.apache.maven.plugins maven-changes-plugin 2.0 ${basedir}/src/changes/changes.xml %URL%/%ISSUE% changes-report org.apache.maven.plugins maven-checkstyle-plugin 2.7 ${basedir}/checkstyle.xml false ${basedir}/license-header.txt org.codehaus.mojo cobertura-maven-plugin 2.5.1 org.codehaus.mojo clirr-maven-plugin 2.2.3 1.3.1 info org.codehaus.mojo findbugs-maven-plugin 2.3.2 Normal Default rc apache.website Apache Commons Release Candidate Staging Site ${commons.deployment.protocol}://people.apache.org/www/people.apache.org/builds/commons/${commons.componentid}/${commons.release.version}/${commons.rc.version}/site commons-validator-1.4.0-src/etc/ 40755 765 0 0 11711227702 17461 5ustarsimonetripodiwheel 0 0 commons-validator-1.4.0-src/etc/jsdoc.bat100644 765 0 4446 11711227702 21360 0ustarsimonetripodiwheel 0 0 @echo off rem * $Id: jsdoc.bat 1228187 2012-01-06 13:56:52Z simonetripodi $ rem * ==================================================================== rem * rem * Licensed to the Apache Software Foundation (ASF) under one or more rem * contributor license agreements. See the NOTICE file distributed with rem * this work for additional information regarding copyright ownership. rem * The ASF licenses this file to You under the Apache License, Version 2.0 rem * (the "License"); you may not use this file except in compliance with rem * the License. You may obtain a copy of the License at rem * rem * http://www.apache.org/licenses/LICENSE-2.0 rem * rem * Unless required by applicable law or agreed to in writing, software rem * distributed under the License is distributed on an "AS IS" BASIS, rem * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. rem * See the License for the specific language governing permissions and rem * limitations under the License. rem *--------------------------------------------------------------* rem * * rem * JSDoc is a perl script for generating javadoc for javascript.* rem * * rem * The latest version can be downloaded from : * rem * * rem * http://sourceforge.net/projects/jsdoc/ * rem * * rem * N.B. You also need something like ActivePerl installed to * rem * run this on windows. See the Installation instructions: * rem * * rem * http://jsdoc.sourceforge.net/#install * rem * * rem *--------------------------------------------------------------* set _PACKAGE=/org/apache/commons/validator/javascript set _JSDOC_HOME=%1 set _JAVASCRIPT_DIR=%2%_PACKAGE% set _OUTPUT_DIR=%3%_PACKAGE% set _COPYRIGHT="Copyright © 2000-2012 - Apache Software Foundation" perl %_JSDOC_HOME%/jsdoc.pl --project-summary %_JAVASCRIPT_DIR%/package.html --project-name "Package %_PACKAGE%" --page-footer %_COPYRIGHT% -d %_OUTPUT_DIR% %_JAVASCRIPT_DIR% commons-validator-1.4.0-src/etc/jsdoc.sh100644 765 0 3101 11711227702 21207 0ustarsimonetripodiwheel 0 0 #!/bin/sh # $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//validator/etc/jsdoc.sh,v 1.4 2004/05/21 14:28:12 rleland Exp $ # $Revision: 1228187 $ # $Date: 2012-01-06 14:56:52 +0100 (Fri, 06 Jan 2012) $ # # ==================================================================== # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # jsdoc is a perl script for generating javadoc for javascript. # The latest version can be downloaded from : # http://sourceforge.net/projects/jsdoc/ # dirtoprocess=$2 outputto=$3 package=/org/apache/commons/validator/javascript perl $1/jsdoc.pl --project-summary ${dirtoprocess}${package}/package.html --project-name "Package org.apache.commons.validator.javascript" --page-footer "Copyright © 2000-2012 - Apache Software Foundation " -d ${outputto}/${package} -r $dirtoprocess commons-validator-1.4.0-src/src/ 40755 765 0 0 11711227702 17475 5ustarsimonetripodiwheel 0 0 commons-validator-1.4.0-src/src/changes/ 40755 765 0 0 11711227702 21105 5ustarsimonetripodiwheel 0 0 commons-validator-1.4.0-src/src/example/ 40755 765 0 0 11711227702 21130 5ustarsimonetripodiwheel 0 0 commons-validator-1.4.0-src/src/example/org/ 40755 765 0 0 11711227702 21717 5ustarsimonetripodiwheel 0 0 commons-validator-1.4.0-src/src/example/org/apache/ 40755 765 0 0 11711227702 23140 5ustarsimonetripodiwheel 0 0 commons-validator-1.4.0-src/src/example/org/apache/commons/ 40755 765 0 0 11711227702 24613 5ustarsimonetripodiwheel 0 0 commons-validator-1.4.0-src/src/example/org/apache/commons/validator/ 40755 765 0 0 11711227702 26600 5ustarsimonetripodiwheel 0 0 commons-validator-1.4.0-src/src/example/org/apache/commons/validator/example/ 40755 765 0 0 11711227702 30233 5ustarsimonetripodiwheel 0 0 commons-validator-1.4.0-src/src/javascript/ 40755 765 0 0 11711227702 21643 5ustarsimonetripodiwheel 0 0 commons-validator-1.4.0-src/src/javascript/org/ 40755 765 0 0 11711227702 22432 5ustarsimonetripodiwheel 0 0 commons-validator-1.4.0-src/src/javascript/org/apache/ 40755 765 0 0 11711227702 23653 5ustarsimonetripodiwheel 0 0 commons-validator-1.4.0-src/src/javascript/org/apache/commons/ 40755 765 0 0 11711227702 25326 5ustarsimonetripodiwheel 0 0 commons-validator-1.4.0-src/src/javascript/org/apache/commons/validator/ 40755 765 0 0 11711227702 27313 5ustarsimonetripodiwheel 0 0 commons-validator-1.4.0-src/src/javascript/org/apache/commons/validator/javascript/ 40755 765 0 0 11711227702 31461 5ustarsimonetripodiwheel 0 0 commons-validator-1.4.0-src/src/javascript/org/apache/commons/validator/javascript/doc-files/ 40755 765 0 0 11711227702 33326 5ustarsimonetripodiwheel 0 0 commons-validator-1.4.0-src/src/main/ 40755 765 0 0 11711227702 20421 5ustarsimonetripodiwheel 0 0 commons-validator-1.4.0-src/src/main/assembly/ 40755 765 0 0 11711227700 22236 5ustarsimonetripodiwheel 0 0 commons-validator-1.4.0-src/src/main/java/ 40755 765 0 0 11711227700 21340 5ustarsimonetripodiwheel 0 0 commons-validator-1.4.0-src/src/main/java/org/ 40755 765 0 0 11711227700 22127 5ustarsimonetripodiwheel 0 0 commons-validator-1.4.0-src/src/main/java/org/apache/ 40755 765 0 0 11711227700 23350 5ustarsimonetripodiwheel 0 0 commons-validator-1.4.0-src/src/main/java/org/apache/commons/ 40755 765 0 0 11711227700 25023 5ustarsimonetripodiwheel 0 0 commons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/ 40755 765 0 0 11711227702 27012 5ustarsimonetripodiwheel 0 0 commons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/routines/ 40755 765 0 0 11711227701 30661 5ustarsimonetripodiwheel 0 0 commons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/routines/checkdigit/ 40755 765 0 0 11711227701 32757 5ustarsimonetripodiwheel 0 0 commons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/util/ 40755 765 0 0 11711227702 27767 5ustarsimonetripodiwheel 0 0 commons-validator-1.4.0-src/src/main/resources/ 40755 765 0 0 11711227702 22433 5ustarsimonetripodiwheel 0 0 commons-validator-1.4.0-src/src/main/resources/org/ 40755 765 0 0 11711227702 23222 5ustarsimonetripodiwheel 0 0 commons-validator-1.4.0-src/src/main/resources/org/apache/ 40755 765 0 0 11711227702 24443 5ustarsimonetripodiwheel 0 0 commons-validator-1.4.0-src/src/main/resources/org/apache/commons/ 40755 765 0 0 11711227702 26116 5ustarsimonetripodiwheel 0 0 commons-validator-1.4.0-src/src/main/resources/org/apache/commons/validator/ 40755 765 0 0 11711227702 30103 5ustarsimonetripodiwheel 0 0 commons-validator-1.4.0-src/src/main/resources/org/apache/commons/validator/resources/ 40755 765 0 0 11711227702 32115 5ustarsimonetripodiwheel 0 0 commons-validator-1.4.0-src/src/site/ 40755 765 0 0 11711227702 20441 5ustarsimonetripodiwheel 0 0 commons-validator-1.4.0-src/src/site/resources/ 40755 765 0 0 11711227702 22453 5ustarsimonetripodiwheel 0 0 commons-validator-1.4.0-src/src/site/resources/images/ 40755 765 0 0 11711227702 23720 5ustarsimonetripodiwheel 0 0 commons-validator-1.4.0-src/src/site/xdoc/ 40755 765 0 0 11711227702 21376 5ustarsimonetripodiwheel 0 0 commons-validator-1.4.0-src/src/test/ 40755 765 0 0 11711227700 20452 5ustarsimonetripodiwheel 0 0 commons-validator-1.4.0-src/src/test/java/ 40755 765 0 0 11711227676 21407 5ustarsimonetripodiwheel 0 0 commons-validator-1.4.0-src/src/test/java/org/ 40755 765 0 0 11711227676 22176 5ustarsimonetripodiwheel 0 0 commons-validator-1.4.0-src/src/test/java/org/apache/ 40755 765 0 0 11711227676 23417 5ustarsimonetripodiwheel 0 0 commons-validator-1.4.0-src/src/test/java/org/apache/commons/ 40755 765 0 0 11711227676 25072 5ustarsimonetripodiwheel 0 0 commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/ 40755 765 0 0 11711227700 27043 5ustarsimonetripodiwheel 0 0 commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/custom/ 40755 765 0 0 11711227700 30355 5ustarsimonetripodiwheel 0 0 commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/routines/ 40755 765 0 0 11711227700 30713 5ustarsimonetripodiwheel 0 0 commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/routines/checkdigit/ 40755 765 0 0 11711227677 33026 5ustarsimonetripodiwheel 0 0 commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/util/ 40755 765 0 0 11711227700 30020 5ustarsimonetripodiwheel 0 0 commons-validator-1.4.0-src/src/test/resources/ 40755 765 0 0 11711227700 22464 5ustarsimonetripodiwheel 0 0 commons-validator-1.4.0-src/src/test/resources/org/ 40755 765 0 0 11711227700 23253 5ustarsimonetripodiwheel 0 0 commons-validator-1.4.0-src/src/test/resources/org/apache/ 40755 765 0 0 11711227700 24474 5ustarsimonetripodiwheel 0 0 commons-validator-1.4.0-src/src/test/resources/org/apache/commons/ 40755 765 0 0 11711227700 26147 5ustarsimonetripodiwheel 0 0 commons-validator-1.4.0-src/src/test/resources/org/apache/commons/validator/ 40755 765 0 0 11711227700 30134 5ustarsimonetripodiwheel 0 0 commons-validator-1.4.0-src/src/test/resources/org/apache/commons/validator/routines/ 40755 765 0 0 11711227700 32004 5ustarsimonetripodiwheel 0 0 commons-validator-1.4.0-src/src/changes/changes.xml100644 765 0 74034 11711227702 23364 0ustarsimonetripodiwheel 0 0 Release Notes CheckStyle and FindBug Issues - inner classes and key sets Email validation fails with dash or hyphen at end of local address @localhost and @localhost.localdomain email addresses aren't correctly detected as valid UrlValidator.isValid does not properly validate *.travel domains UrlValidator does not validate URL with simple domains (eg: http://hostname ) isValid method for EmailValidator should return false for domain with special characters only formatDate(String value, Locale locale) in GenericTypeValidator uses DateFormat.SHORT instead of DateFormat.DEFAULT isValidURL call returns false for file scheme/protocol when URL is correct gmail testing addresses do not validate EmailValidator.isValid(String) follows RFC822 but violates RFC1034 Performance improvement of DomainValidator by change the regular expression url with brackets is not validated thru URLvalidator class. Banking CheckDigit implementations: ABA, CUSIP, IBAN, ISIN and Sedol Add Diners card validation to CreditCardValidator Add an option to allow 'localhost' as a valid hostname part in the URL Move CreditCardValidator to routines package and refactor to use new CodeValidator Move EmailValidator to routines package New InetAdress Validator implementation Support the 65 prefix for Discover Card Create 1.4 DTD Switch to using Version 0.4.3 of the Dojo Compressor from the maven repo Add script attribute to control script generation clirr Report - EmailValidator.isValidIpAddress() argument type change Null-Stream input to ValidatorResources leads to MalformedURLExceptions validatorUtilities.js - replace colon characters in the function name (JSF/Shale) Move the trim() function from validateRequired.js to validateUtilities.js EmailValidator fails with ArrayIndexOutOfBoundsException on domain names longer than 10 segments UrlValidator fail when path contains "(" / ")" UrlValidator rejects top-level domains (TLDs) with more than 4 characters New generic CodeValidator that validates format, length and Check Digit for a code New Regular Expression validator using JDK 1.4's Regex Factor out Check Digit logic into separate implementations Upgrade to Digester 1.8 Refactor UrlValidator - especially the line 370-ish. Copy remaining Validation Routines to the new routines package Removing ORO dep. from GenericValidator Adding ISBNValidator to GenericValidator Remove the dependency on Jakarta ORO (move to JDK 1.4 regular expression support) Extend ISBN validator to support smooth transition to ISBN-13 / EAN-13 standard JDK 1.4 - change minimum dependency for validator to be JDK 1.4 (was 1.3). Primary reason for this is to use JDK 1.4+ built in regular expression support and remove the dependency on Jakarta ORO.

Dependencies: dependencies for Validator 1.3.1 are unchanged since the 1.3.0 release.

N.B.Jakarta ORO has now been marked as an optional dependency in the project.xml as it is only required by the Email, URL and Regular Expression validations.

JavaScript function jcv_isFieldPresent() causes error in IE5 using "undefined". EmailValidator allows control characters (ASCII 0-31 and 127). JavaScript Causes HTML Page to Contain Illegal HTML. Additional constructor for ValidatorResources that takes URL["> instead of String[">. Fix loading of Digester rules for custom ValidatorResources implementations. Validator incorrectly storing itself under the FORM_PARAM key rather than the Form. Urlvalidator returns false for a valid URL containing an underscore. Urlvalidator fails with an ArrayIndexOutOfBoundsException. The ant build.xml doesn't include validator_1_1_3.dtd in the jar. Example does not compile using ant build script. Validating indexed properties fails when null. Fix a thread safety issue in parameter initialization.
ValidatorResult only contains last run dependency for the field. Validator argument - resource="false" ignored for arg0 - arg3. Change JavaScript validators to cater for disabled being undefined (an issue in Netscape 4.7).

Add new routines package containing standard validations - first step in the process of clearly separating standard validation functions which can be used independantly, from the framework aspect of Commons Validator.

New validators added for Date, Time, Calendar, Byte, Short, Integer, Long, Float, Double, BigInteger, BigDecimal, Currency and Percent.

See Routines Package JavaDocs

Deprecate ValidatorResult's getActionMap() and add getActions() method to provide an Iterator of the set of action names. Use the Dojo/Rhino JavaScript compressor to created compressed versions of the static JavaScript files. Additionally create single file distros of all the static JavaScript in un-compressed and compressed format. See Dojo/Rhino Compressor. Prefix remaining JavaScript utility methods with "jcv_" to reduce the likelihood of clashes with other libraries - validator still needs to be properly namespaced (as per Bug 38184). Change JavaScript validators so that they don't fail when the field is not present on the form. Fix min/max length validation for different line endings. Fix email validator to not allow spaces at the end of the user component or start of the domain component. Added validator_1_3_0.dtd and changed form rules so that a minimum of one field is no longer required (i.e. changed (field+) to (field*) for a form). Resolve issue in JavaScript validation when the prototype library is used. Re-factor JavaScript error handling into a common method and only set focus on fields which are not 'hidden' type or hidden by CSS. Remove static Log instances to avoid problems if deployed via a shared classloader in a container. See here for more details. Reverse change for to Credit Card Validator for visa card blue in France. Fix JavaScript validation for Internet Explorer 5.0.
Added ISBNValidator for validating book numbers. Upgrade dependency versions to Commons BeanUtils 1.7.0, Commons Digester 1.6 and Commons Logging 1.0.4. Remove dependency on Commons Collections (BeanUtils 1.7.0 has removed its dependency on Collections by including the few Collections classes required in its distribution). Add support for min or max numeric values. Allow validators to register errors for multiple fields. Fixed EmailValidator failing on valid email addresses. Allow forms to inherit validation rules from other forms. Remove the need to specify an Arguement's position. Deprecated all FastHashMap usage and provided protected get methods that return generic Maps to be used by subclasses. Handling of float and double should use the locale object. Fixes 21282 More informative Exception message when validation method not found. Client-side required validation inconsistent with server-side. EmailValidator allows apostrophes in domain name. Changing the strategy for locating form name/id, now use a common utility function which works in both IE and Firefox. Fixes 35127 and 32760 Validation fails when "name" attribute in form not specified. UrlValidator fails http://www.google.com. Email: inexisting dashes and TLD erroneously accepted. Float validator can't validate the string with several dot. CreditValidator does not handle Visa correctly. datePattern not supported by JavaScript. validateRequired on a single radio button. Field.validate() cannot be invoked from user-defined code. Locale validation doesn't validate all fields. XML file included into validation.xml via entity reference not found. Update maven build to Include DTDs and xdocs in the source distribution. Remove logging of exceptions when the Date validation fails (correctly) with an invalid date. Add version 1.1.3 of the DTD from the VALIDATOR_1_1_2_BRANCH and change digester rules so that the old arg0-arg3 values are not ignored for versions of the DTD prior to 1.2.0. Add 'resource' and 'bundle' elements to the 1.2.0 DTD. Provide access to the result object in ValidatorResult. Validation breaks on multiple validation.xml (eg. with Struts 1.3). GenericTypeValidator does not accept negative Floats/Doubles. correct UrlValidator JavaDoc. Search the locale 'hierarchy' of formsets for a Form. Int validation in Java and Javascript have different semantics. Javascript Validation currently uses unsupported DOM method getAttributeNode(). Added getMessage(key) and getMessages() methods to Field Added resource property (including getter/setter) to Msg to support the 'resource' attribute specified in the DTD. Fixed javascript file reading in Java WebStart environment. Fixed javascript email domain length limited to 2 or 3 chars. Javascript validation doesn't work if a form field is called "name". Allow multiple forms to be on the same page by generating a unique variable name based on form name. Fixes 17667 Validate file extensions for file uploads. Add Support for hidden fields in javascript validations. The framework will convert checked exceptions into ValidatorExceptions so any ValidatorException thrown out of the framework indicates a 'system' exception that stops validation processing. If a pluggable validation method throws a ValidatorException it will be rethrown and passed out of the framework. Any other exception from a pluggable validation method is still considered a validation failure rather than a system exception to maintain backwards compatibility. Added a more flexible card validation system that doesn't require CreditCardValidator to support every brand of credit card. Throw RuntimeException if clone fails instead of InternalError. Added Flags.clear(). Add javadoc to javascript, and use jsdoc to process it. Ignore validation criteria when field is disabled for all field types. Add required check for single checkbox. Let max/min length also cover passwords fields. Don't use these for checking login pages, only when the user is modifying the password. Added Field.getArgs(String) to make it easier to retrieve all of the Args for a given validator. Modify javascript to honor datapattern option. Add ability of required to handle checkboxes, radio, select-one, and select-multiple field types. Add ability to use required condition on array types like checkboxes. Move Digester rule configuration to XML file and remove ValidatorResourcesInitializer. ValidatorResources now knows how to initialize itself. Clean up scopes of methods and variables. Make Arg system more flexible to allow any number of args in a message. Validate validation.xml files while initializing a Validator to alert developers to configuration errors. Refactored GenericValidator methods into reusable objects. These include: CreditCardValidator, EmailValidator, DateValidator, and UrlValidator.

Backwards Incompatible Changes

  • <msg>'s name and key attributes are now required. The Validator code was enforcing this constraint so now it's formally defined in the DTD.

Deprecated items; see the javadoc for details and replacements.

  • The <arg0-3> elements have been replaced with a single <arg> element with a new position attribute. Setting position to 0 is the equivalent of an <arg0> element.
  • Arg.getResource()
  • CreditCardValidator.isValidPrefix()
  • Field.ARG_DEFAULT
  • Field.hDependencies
  • Field.hArg0 - Field.hArg3
  • Field.addArg0() - Field.addArg3()
  • Field.getArg0() - Field.getArg3()
  • Field.addVarParam()
  • Field.process()
  • Field.processMessageComponents()
  • Field.getDependencies()
  • Form.getFieldMap()
  • Form.process()
  • FormSet.addConstant()
  • FormSet.addConstantParam()
  • FormSet.getForm(Object)
  • FormSet.process()
  • GenericValidator.REGEXP_DELIM
  • GenericValidator.validateCreditCardLuhnCheck()
  • GenericValidator.validateCreditCardPrefixCheck()
  • GenericValidator.getDelimittedRegExp()
  • Validator.BEAN_KEY
  • Validator.VALIDATOR_ACTION_KEY
  • Validator.FIELD_KEY
  • Validator.VALIDATOR_KEY
  • Validator.LOCALE_KEY
  • Validator.hResources
  • Validator.addResource()
  • Validator.getResource()
  • ValidatorAction.process()
  • ValidatorAction.getDependencies()
  • ValidatorResources.put()
  • ValidatorResources.addConstant()
  • ValidatorResources.addConstantParam()
  • ValidatorResources.get()
  • ValidatorResources.processForms()
  • ValidatorResourcesInitializer
  • ValidatorResult.getValid()
  • ValidatorResults.empty()
  • ValidatorResults.get()
  • ValidatorResults.properties()
  • ValidatorUtil
GenericValidaor.isEmail bug. NPE in Validator.java after upgrading to Struts 1.1b3. i18n issue, variant not being picked up by Validator. isEmail accepts Umlauts and other non-ASCII characters. Email address validation incorrectly accepts commas. unknown host when loading app. Serialization problem with org.apache.commons.validator.ValidatorResult$ResultStatus. ValidatorResources.get-method not working properly. First Release.
commons-validator-1.4.0-src/src/example/org/apache/commons/validator/example/ValidateBean.java100644 765 0 5603 11711227702 33516 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.example; /** * A simple bean to use with the Validator Example. * * @version $Revision: 478334 $ $Date: 2006-11-22 22:31:54 +0100 (Wed, 22 Nov 2006) $ */ public class ValidateBean extends Object { String lastName, firstName, street1, street2, city, state, postalCode, age; public void setLastName(String lastName) { this.lastName = lastName; } public void setFirstName(String firstName) { this.firstName = firstName; } public void setStreet1(String street1) { this.street1 = street1; } public void setStreet2(String street2) { this.street2 = street2; } public void setCity(String city) { this.city = city; } public void setState(String state) { this.state = state; } public void setPostalCode(String postalCode) { this.postalCode = postalCode; } public void setAge(String age) { this.age = age; } public String getLastName() { return this.lastName; } public String getFirstName() { return this.firstName; } public String getStreet1() { return this.street1; } public String getStreet2() { return this.street2; } public String getCity() { return this.city; } public String getState() { return this.state; } public String getPostalCode() { return this.postalCode; } public String getAge() { return this.age; } public String toString() { return "{lastname=" + this.lastName + ", firstname=" + this.firstName + ", street1=" + this.street1 + ",\n street2=" + this.street2 + ", " + "city=" + this.city + ", state=" + this.state + ",\n postalcode=" + this.postalCode + ", age=" + this.age + "}"; } } commons-validator-1.4.0-src/src/example/org/apache/commons/validator/example/ValidateExample.java100644 765 0 17366 11711227702 34275 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.example; import java.io.IOException; import java.io.InputStream; import java.text.MessageFormat; import java.util.Iterator; import java.util.Locale; import java.util.Map; import java.util.ResourceBundle; import org.apache.commons.validator.Field; import org.apache.commons.validator.Form; import org.apache.commons.validator.Validator; import org.apache.commons.validator.ValidatorAction; import org.apache.commons.validator.ValidatorException; import org.apache.commons.validator.ValidatorResources; import org.apache.commons.validator.ValidatorResult; import org.apache.commons.validator.ValidatorResults; import org.xml.sax.SAXException; /** *

A simple example of setting up and using the Validator.

* * This simple example shows all the steps needed to set up and use * the Validator. Note that in most cases, some kind of framework * would be wrapped around the Validator, such as is the case with * the Struts Validator Framework. However, should you wish to use * the Validator against raw Beans in a pure Java application, you * can see everything you need to know to get it working here. * * @version $Revision: 478334 $ $Date: 2006-11-22 22:31:54 +0100 (Wed, 22 Nov 2006) $ */ public class ValidateExample extends Object { /** * We need a resource bundle to get our field names and errors messages * from. Note that this is not strictly required to make the Validator * work, but is a good coding practice. */ private static ResourceBundle apps = ResourceBundle.getBundle( "org.apache.commons.validator.example.applicationResources"); /** * This is the main method that will be called to initialize the Validator, create some sample beans, and * run the Validator against them. */ public static void main(String[] args) throws ValidatorException, IOException, SAXException { InputStream in = null; ValidatorResources resources = null; try { // Create a new instance of a ValidatorResource, then get a stream // handle on the XML file with the actions in it, and initialize the // resources from it. This would normally be done by a servlet // run during JSP initialization or some other application-startup // routine. in = ValidateExample.class.getResourceAsStream("validator-example.xml"); resources = new ValidatorResources(in); } finally { // Make sure we close the input stream. if (in != null) { in.close(); } } // Create a test bean to validate against. ValidateBean bean = new ValidateBean(); // Create a validator with the ValidateBean actions for the bean // we're interested in. Validator validator = new Validator(resources, "ValidateBean"); // Tell the validator which bean to validate against. validator.setParameter(Validator.BEAN_PARAM, bean); ValidatorResults results = null; // Run the validation actions against the bean. Since all of the properties // are null, we expect them all to error out except for street2, which has // no validations (it's an optional property) results = validator.validate(); printResults(bean, results, resources); // Now set all the required properties, but make the age a non-integer. // You'll notice that age will pass the required test, but fail the int // test. bean.setLastName("Tester"); bean.setFirstName("John"); bean.setStreet1("1 Test Street"); bean.setCity("Testville"); bean.setState("TE"); bean.setPostalCode("12345"); bean.setAge("Too Old"); results = validator.validate(); printResults(bean, results, resources); // Now only report failed fields validator.setOnlyReturnErrors(true); results = validator.validate(); printResults(bean, results, resources); // Now everything should pass. validator.setOnlyReturnErrors(false); bean.setAge("123"); results = validator.validate(); printResults(bean, results, resources); } /** * Dumps out the Bean in question and the results of validating it. */ public static void printResults( ValidateBean bean, ValidatorResults results, ValidatorResources resources) { boolean success = true; // Start by getting the form for the current locale and Bean. Form form = resources.getForm(Locale.getDefault(), "ValidateBean"); System.out.println("\n\nValidating:"); System.out.println(bean); // Iterate over each of the properties of the Bean which had messages. Iterator propertyNames = results.getPropertyNames().iterator(); while (propertyNames.hasNext()) { String propertyName = (String) propertyNames.next(); // Get the Field associated with that property in the Form Field field = form.getField(propertyName); // Look up the formatted name of the field from the Field arg0 String prettyFieldName = apps.getString(field.getArg(0).getKey()); // Get the result of validating the property. ValidatorResult result = results.getValidatorResult(propertyName); // Get all the actions run against the property, and iterate over their names. Map actionMap = result.getActionMap(); Iterator keys = actionMap.keySet().iterator(); while (keys.hasNext()) { String actName = (String) keys.next(); // Get the Action for that name. ValidatorAction action = resources.getValidatorAction(actName); // If the result is valid, print PASSED, otherwise print FAILED System.out.println( propertyName + "[" + actName + "] (" + (result.isValid(actName) ? "PASSED" : "FAILED") + ")"); //If the result failed, format the Action's message against the formatted field name if (!result.isValid(actName)) { success = false; String message = apps.getString(action.getMsg()); Object[] args = { prettyFieldName }; System.out.println( " Error message will be: " + MessageFormat.format(message, args)); } } } if (success) { System.out.println("FORM VALIDATION PASSED"); } else { System.out.println("FORM VALIDATION FAILED"); } } } ././@LongLink100644 0 0 155 11711231552 10252 Lustar 0 0 commons-validator-1.4.0-src/src/example/org/apache/commons/validator/example/applicationResources.propertiescommons-validator-1.4.0-src/src/example/org/apache/commons/validator/example/applicationResources.pr100644 765 0 2336 11711227702 35075 0ustarsimonetripodiwheel 0 0 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # The error messages for the Validation Actions errors.required=The {0} field is required. errors.int=The {0} field is not an integer. # The formatted names of the properties nameForm.age.displayname=Age nameForm.lastname.displayname=Last Name nameForm.firstname.displayname=First Name nameForm.city.displayname=City nameForm.state.displayname=State nameForm.postalCode.displayname=Postal Code nameForm.street1.displayname=Street Address commons-validator-1.4.0-src/src/example/org/apache/commons/validator/example/validator-example.xml100644 765 0 4777 11711227702 34507 0ustarsimonetripodiwheel 0 0
././@LongLink100644 0 0 152 11711231552 10247 Lustar 0 0 commons-validator-1.4.0-src/src/javascript/org/apache/commons/validator/javascript/doc-files/sm-maybe.gifcommons-validator-1.4.0-src/src/javascript/org/apache/commons/validator/javascript/doc-files/sm-mayb100644 765 0 1555 11711227702 34721 0ustarsimonetripodiwheel 0 0 GIF87a÷€€€€€€€€€ÀÀÀÀÜÀ¦Êð@ ` €   À à @ @@@`@€@ @À@à@` `@```€` `À`à`€ €@€`€€€ €À€à€   @ ` €   À à À À@À`À€À ÀÀÀàÀà à@à`à€à àÀààà@ @@@`@€@ @À@à@ @ @@ @` @€ @  @À @à @@@ @@@@@`@@€@@ @@À@@à@@`@ `@@`@``@€`@ `@À`@à`@€@ €@@€@`€@€€@ €@À€@à€@ @  @@ @` @€ @  @À @à @À@ À@@À@`À@€À@ À@ÀÀ@àÀ@à@ à@@à@`à@€à@ à@Àà@àà@€ €@€`€€€ €À€à€ € €@ €` €€ €  €À €à €@€ @€@@€`@€€@€ @€À@€à@€`€ `€@`€``€€`€ `€À`€à`€€€ €€@€€`€€€€€ €€À€€à€€ €  €@ €` €€ €  €À €à €À€ À€@À€`À€€À€ À€ÀÀ€àÀ€à€ à€@à€`à€€à€ à€Àà€àà€À À@À`À€À ÀÀÀàÀ À À@ À` À€ À  ÀÀ Àà À@À @À@@À`@À€@À @ÀÀ@Àà@À`À `À@`À``À€`À `ÀÀ`Àà`À€À €À@€À`€À€€À €ÀÀ€Àà€À À  À@ À` À€ À  ÀÀ Àà ÀÀÀ ÀÀ@ÀÀ`ÀÀ€ÀÀ ÀÀÿûð  ¤€€€ÿÿÿÿÿÿÿÿÿÿÿÿ!ù,Jÿ  `ÁÿÜÇáA„Jt80âĉ:´¸oaG… =vä(ò¢Ä’&7¦ÄÈqåG‹cRé2£Æ”6+¶™P§Á„;././@LongLink100644 0 0 147 11711231552 10253 Lustar 0 0 commons-validator-1.4.0-src/src/javascript/org/apache/commons/validator/javascript/doc-files/sm-no.gifcommons-validator-1.4.0-src/src/javascript/org/apache/commons/validator/javascript/doc-files/sm-no.g100644 765 0 1557 11711227702 34634 0ustarsimonetripodiwheel 0 0 GIF87a÷€€€€€€€€€ÀÀÀÀÜÀ¦Êð@ ` €   À à @ @@@`@€@ @À@à@` `@```€` `À`à`€ €@€`€€€ €À€à€   @ ` €   À à À À@À`À€À ÀÀÀàÀà à@à`à€à àÀààà@ @@@`@€@ @À@à@ @ @@ @` @€ @  @À @à @@@ @@@@@`@@€@@ @@À@@à@@`@ `@@`@``@€`@ `@À`@à`@€@ €@@€@`€@€€@ €@À€@à€@ @  @@ @` @€ @  @À @à @À@ À@@À@`À@€À@ À@ÀÀ@àÀ@à@ à@@à@`à@€à@ à@Àà@àà@€ €@€`€€€ €À€à€ € €@ €` €€ €  €À €à €@€ @€@@€`@€€@€ @€À@€à@€`€ `€@`€``€€`€ `€À`€à`€€€ €€@€€`€€€€€ €€À€€à€€ €  €@ €` €€ €  €À €à €À€ À€@À€`À€€À€ À€ÀÀ€àÀ€à€ à€@à€`à€€à€ à€Àà€àà€À À@À`À€À ÀÀÀàÀ À À@ À` À€ À  ÀÀ Àà À@À @À@@À`@À€@À @ÀÀ@Àà@À`À `À@`À``À€`À `ÀÀ`Àà`À€À €À@€À`€À€€À €ÀÀ€Àà€À À  À@ À` À€ À  ÀÀ Àà ÀÀÀ ÀÀ@ÀÀ`ÀÀ€ÀÀ ÀÀÿûð  ¤€€€ÿÿÿÿÿÿÿÿÿÿÿÿ!ù,Lÿ  `ÁÿÌÇáA„Jt80âĉ:´˜oaG… =vä(ò¢Ä’&7ž4ÈqdHŒ!A¶|™dJŠSÖ¬8óaB…,;././@LongLink100644 0 0 150 11711231552 10245 Lustar 0 0 commons-validator-1.4.0-src/src/javascript/org/apache/commons/validator/javascript/doc-files/sm-yes.gifcommons-validator-1.4.0-src/src/javascript/org/apache/commons/validator/javascript/doc-files/sm-yes.100644 765 0 1557 11711227702 34651 0ustarsimonetripodiwheel 0 0 GIF87a÷€€€€€€€€€ÀÀÀÀÜÀ¦Êð@ ` €   À à @ @@@`@€@ @À@à@` `@```€` `À`à`€ €@€`€€€ €À€à€   @ ` €   À à À À@À`À€À ÀÀÀàÀà à@à`à€à àÀààà@ @@@`@€@ @À@à@ @ @@ @` @€ @  @À @à @@@ @@@@@`@@€@@ @@À@@à@@`@ `@@`@``@€`@ `@À`@à`@€@ €@@€@`€@€€@ €@À€@à€@ @  @@ @` @€ @  @À @à @À@ À@@À@`À@€À@ À@ÀÀ@àÀ@à@ à@@à@`à@€à@ à@Àà@àà@€ €@€`€€€ €À€à€ € €@ €` €€ €  €À €à €@€ @€@@€`@€€@€ @€À@€à@€`€ `€@`€``€€`€ `€À`€à`€€€ €€@€€`€€€€€ €€À€€à€€ €  €@ €` €€ €  €À €à €À€ À€@À€`À€€À€ À€ÀÀ€àÀ€à€ à€@à€`à€€à€ à€Àà€àà€À À@À`À€À ÀÀÀàÀ À À@ À` À€ À  ÀÀ Àà À@À @À@@À`@À€@À @ÀÀ@Àà@À`À `À@`À``À€`À `ÀÀ`Àà`À€À €À@€À`€À€€À €ÀÀ€Àà€À À  À@ À` À€ À  ÀÀ Àà ÀÀÀ ÀÀ@ÀÀ`ÀÀ€ÀÀ ÀÀÿûð  ¤€€€ÿÿÿÿÿÿÿÿÿÿÿÿ!ù,Lÿ  `ÁÿÔÇáA„Jt80âĉ:´¨oaG… =vä(ò¢Ä’&7¦Äh‘ãIŠ-1R¹Ñ`ÈŠ+3Bt92aEƒ:;commons-validator-1.4.0-src/src/javascript/org/apache/commons/validator/javascript/package.html100644 765 0 35043 11711227702 34064 0ustarsimonetripodiwheel 0 0 Validator JavaScript package

The validator javascript package provides a series of functions to validate form input data.


Package Specification


Field Type
validate
Byte
validate
CreditCard
validate
Date
validate
Email
validate
Float
validate
FloatRange
validate
IntRange
validate
Integer
validate
Mask
validate
MaxRange
validate
MinRange
validate
Required
validate
Short
checkbox











Yes
file







Yes 1


Yes
hidden 2 Yes   Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes
password








Caution
Caution Yes
radio Yes


Yes

Yes


Yes Yes
select-multiple










Yes
select-one Yes


Yes

Yes


Yes Yes
text Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes
textarea Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes

Notes

1)  

Since few browser support the 'accept' attribute for file upload input fields, a mask can be used to validate the uploaded file extension.

2)   Hidden fields can be used with complicated HTML interface. like cascading inter-dependent menus. The menus themselves don't represent real data fields, but are used with javascript to set the value of a hidden field.

 

commons-validator-1.4.0-src/src/javascript/org/apache/commons/validator/javascript/validateByte.js100644 765 0 5771 11711227702 34543 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*$RCSfile: validateByte.js,v $ $Rev: 478676 $ $Date: 2006-11-23 22:35:44 +0100 (Thu, 23 Nov 2006) $ */ /** * Check to see if fields are a valid byte. * Fields are not checked if they are disabled. * @param form The form validation is taking place on. */ function validateByte(form) { var bValid = true; var focusField = null; var i = 0; var fields = new Array(); var oByte = eval('new ' + jcv_retrieveFormName(form) + '_ByteValidations()'); for (var x in oByte) { if (!jcv_verifyArrayElement(x, oByte[x])) { continue; } var field = form[oByte[x][0]]; if (!jcv_isFieldPresent(field)) { continue; } if ((field.type == 'hidden' || field.type == 'text' || field.type == 'textarea' || field.type == 'select-one' || field.type == 'radio')) { var value = ''; // get field's value if (field.type == "select-one") { var si = field.selectedIndex; if (si >= 0) { value = field.options[si].value; } } else { value = field.value; } if (value.length > 0) { if (!jcv_isDecimalDigits(value)) { bValid = false; if (i == 0) { focusField = field; } fields[i++] = oByte[x][1]; } else { var iValue = parseInt(value, 10); if (isNaN(iValue) || !(iValue >= -128 && iValue <= 127)) { if (i == 0) { focusField = field; } fields[i++] = oByte[x][1]; bValid = false; } } } } } if (fields.length > 0) { jcv_handleErrors(fields, focusField); } return bValid; } ././@LongLink100644 0 0 151 11711231552 10246 Lustar 0 0 commons-validator-1.4.0-src/src/javascript/org/apache/commons/validator/javascript/validateCreditCard.jscommons-validator-1.4.0-src/src/javascript/org/apache/commons/validator/javascript/validateCreditCar100644 765 0 6604 11711227702 35061 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*$RCSfile: validateCreditCard.js,v $ $Rev: 478676 $ $Date: 2006-11-23 22:35:44 +0100 (Thu, 23 Nov 2006) $ */ /** * Check to see if fields are a valid creditcard number based on Luhn checksum. * Fields are not checked if they are disabled. * @param form The form validation is taking place on. */ function validateCreditCard(form) { var bValid = true; var focusField = null; var i = 0; var fields = new Array(); var oCreditCard = eval('new ' + jcv_retrieveFormName(form) + '_creditCard()'); for (var x in oCreditCard) { if (!jcv_verifyArrayElement(x, oCreditCard[x])) { continue; } var field = form[oCreditCard[x][0]]; if (!jcv_isFieldPresent(field)) { continue; } if ((field.type == 'text' || field.type == 'textarea') && (field.value.length > 0)) { if (!jcv_luhnCheck(field.value)) { if (i == 0) { focusField = field; } fields[i++] = oCreditCard[x][1]; bValid = false; } } } if (fields.length > 0) { jcv_handleErrors(fields, focusField); } return bValid; } /** * Checks whether a given credit card number has a valid Luhn checksum. * This allows you to spot most randomly made-up or garbled credit card numbers immediately. * Reference: http://www.speech.cs.cmu.edu/~sburke/pub/luhn_lib.html */ function jcv_luhnCheck(cardNumber) { if (jcv_isLuhnNum(cardNumber)) { var no_digit = cardNumber.length; var oddoeven = no_digit & 1; var sum = 0; for (var count = 0; count < no_digit; count++) { var digit = parseInt(cardNumber.charAt(count)); if (!((count & 1) ^ oddoeven)) { digit *= 2; if (digit > 9) digit -= 9; }; sum += digit; }; if (sum == 0) return false; if (sum % 10 == 0) return true; }; return false; } function jcv_isLuhnNum(argvalue) { argvalue = argvalue.toString(); if (argvalue.length == 0) { return false; } for (var n = 0; n < argvalue.length; n++) { if ((argvalue.substring(n, n+1) < "0") || (argvalue.substring(n,n+1) > "9")) { return false; } } return true; } commons-validator-1.4.0-src/src/javascript/org/apache/commons/validator/javascript/validateDate.js100644 765 0 23262 11711227702 34530 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*$RCSfile: validateDate.js,v $ $Rev: 478676 $ $Date: 2006-11-23 22:35:44 +0100 (Thu, 23 Nov 2006) $ */ /** * Check to see if fields are a valid date. * Fields are not checked if they are disabled. * @param form The form validation is taking place on. */ function validateDate(form) { var bValid = true; var focusField = null; var i = 0; var fields = new Array(); var oDate = eval('new ' + jcv_retrieveFormName(form) + '_DateValidations()'); for (var x in oDate) { if (!jcv_verifyArrayElement(x, oDate[x])) { continue; } var field = form[oDate[x][0]]; if (!jcv_isFieldPresent(field)) { continue; } var value = field.value; var isStrict = true; var datePattern = oDate[x][2]("datePatternStrict"); // try loose pattern if (datePattern == null) { datePattern = oDate[x][2]("datePattern"); isStrict = false; } if ((field.type == 'hidden' || field.type == 'text' || field.type == 'textarea') && (value.length > 0) && (datePattern.length > 0)) { var MONTH = "MM"; var DAY = "dd"; var YEAR = "yyyy"; var orderMonth = datePattern.indexOf(MONTH); var orderDay = datePattern.indexOf(DAY); var orderYear = datePattern.indexOf(YEAR); if ((orderDay < orderYear && orderDay > orderMonth)) { var iDelim1 = orderMonth + MONTH.length; var iDelim2 = orderDay + DAY.length; var delim1 = datePattern.substring(iDelim1, iDelim1 + 1); var delim2 = datePattern.substring(iDelim2, iDelim2 + 1); if (iDelim1 == orderDay && iDelim2 == orderYear) { dateRegexp = isStrict ? new RegExp("^(\\d{2})(\\d{2})(\\d{4})$") : new RegExp("^(\\d{1,2})(\\d{1,2})(\\d{4})$"); } else if (iDelim1 == orderDay) { dateRegexp = isStrict ? new RegExp("^(\\d{2})(\\d{2})[" + delim2 + "](\\d{4})$") : new RegExp("^(\\d{1,2})(\\d{1,2})[" + delim2 + "](\\d{4})$"); } else if (iDelim2 == orderYear) { dateRegexp = isStrict ? new RegExp("^(\\d{2})[" + delim1 + "](\\d{2})(\\d{4})$") : new RegExp("^(\\d{1,2})[" + delim1 + "](\\d{1,2})(\\d{4})$"); } else { dateRegexp = isStrict ? new RegExp("^(\\d{2})[" + delim1 + "](\\d{2})[" + delim2 + "](\\d{4})$") : new RegExp("^(\\d{1,2})[" + delim1 + "](\\d{1,2})[" + delim2 + "](\\d{4})$"); } var matched = dateRegexp.exec(value); if(matched != null) { if (!jcv_isValidDate(matched[2], matched[1], matched[3])) { if (i == 0) { focusField = field; } fields[i++] = oDate[x][1]; bValid = false; } } else { if (i == 0) { focusField = field; } fields[i++] = oDate[x][1]; bValid = false; } } else if ((orderMonth < orderYear && orderMonth > orderDay)) { var iDelim1 = orderDay + DAY.length; var iDelim2 = orderMonth + MONTH.length; var delim1 = datePattern.substring(iDelim1, iDelim1 + 1); var delim2 = datePattern.substring(iDelim2, iDelim2 + 1); if (iDelim1 == orderMonth && iDelim2 == orderYear) { dateRegexp = isStrict ? new RegExp("^(\\d{2})(\\d{2})(\\d{4})$") : new RegExp("^(\\d{1,2})(\\d{1,2})(\\d{4})$"); } else if (iDelim1 == orderMonth) { dateRegexp = isStrict ? new RegExp("^(\\d{2})(\\d{2})[" + delim2 + "](\\d{4})$") : new RegExp("^(\\d{1,2})(\\d{1,2})[" + delim2 + "](\\d{4})$"); } else if (iDelim2 == orderYear) { dateRegexp = isStrict ? new RegExp("^(\\d{2})[" + delim1 + "](\\d{2})(\\d{4})$") : new RegExp("^(\\d{1,2})[" + delim1 + "](\\d{1,2})(\\d{4})$"); } else { dateRegexp = isStrict ? new RegExp("^(\\d{2})[" + delim1 + "](\\d{2})[" + delim2 + "](\\d{4})$") : new RegExp("^(\\d{1,2})[" + delim1 + "](\\d{1,2})[" + delim2 + "](\\d{4})$"); } var matched = dateRegexp.exec(value); if(matched != null) { if (!jcv_isValidDate(matched[1], matched[2], matched[3])) { if (i == 0) { focusField = field; } fields[i++] = oDate[x][1]; bValid = false; } } else { if (i == 0) { focusField = field; } fields[i++] = oDate[x][1]; bValid = false; } } else if ((orderMonth > orderYear && orderMonth < orderDay)) { var iDelim1 = orderYear + YEAR.length; var iDelim2 = orderMonth + MONTH.length; var delim1 = datePattern.substring(iDelim1, iDelim1 + 1); var delim2 = datePattern.substring(iDelim2, iDelim2 + 1); if (iDelim1 == orderMonth && iDelim2 == orderDay) { dateRegexp = isStrict ? new RegExp("^(\\d{4})(\\d{2})(\\d{2})$") : new RegExp("^(\\d{4})(\\d{1,2})(\\d{1,2})$"); } else if (iDelim1 == orderMonth) { dateRegexp = isStrict ? new RegExp("^(\\d{4})(\\d{2})[" + delim2 + "](\\d{2})$") : new RegExp("^(\\d{4})(\\d{1,2})[" + delim2 + "](\\d{1,2})$"); } else if (iDelim2 == orderDay) { dateRegexp = isStrict ? new RegExp("^(\\d{4})[" + delim1 + "](\\d{2})(\\d{2})$") : new RegExp("^(\\d{4})[" + delim1 + "](\\d{1,2})(\\d{1,2})$"); } else { dateRegexp = isStrict ? new RegExp("^(\\d{4})[" + delim1 + "](\\d{2})[" + delim2 + "](\\d{2})$") : new RegExp("^(\\d{4})[" + delim1 + "](\\d{1,2})[" + delim2 + "](\\d{1,2})$"); } var matched = dateRegexp.exec(value); if(matched != null) { if (!jcv_isValidDate(matched[3], matched[2], matched[1])) { if (i == 0) { focusField = field; } fields[i++] = oDate[x][1]; bValid = false; } } else { if (i == 0) { focusField = field; } fields[i++] = oDate[x][1]; bValid = false; } } else { if (i == 0) { focusField = field; } fields[i++] = oDate[x][1]; bValid = false; } } } if (fields.length > 0) { jcv_handleErrors(fields, focusField); } return bValid; } function jcv_isValidDate(day, month, year) { if (month < 1 || month > 12) { return false; } if (day < 1 || day > 31) { return false; } if ((month == 4 || month == 6 || month == 9 || month == 11) && (day == 31)) { return false; } if (month == 2) { var leap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)); if (day>29 || (day == 29 && !leap)) { return false; } } return true; } commons-validator-1.4.0-src/src/javascript/org/apache/commons/validator/javascript/validateEmail.js100644 765 0 10345 11711227702 34700 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*$RCSfile: validateEmail.js,v $ $Rev: 478676 $ $Date: 2006-11-23 22:35:44 +0100 (Thu, 23 Nov 2006) $ */ /** * Check to see if fields are a valid email address. * Fields are not checked if they are disabled. * @param form The form validation is taking place on. */ function validateEmail(form) { var bValid = true; var focusField = null; var i = 0; var fields = new Array(); var oEmail = eval('new ' + jcv_retrieveFormName(form) + '_email()'); for (var x in oEmail) { if (!jcv_verifyArrayElement(x, oEmail[x])) { continue; } var field = form[oEmail[x][0]]; if (!jcv_isFieldPresent(field)) { continue; } if ((field.type == 'hidden' || field.type == 'text' || field.type == 'textarea') && (field.value.length > 0)) { if (!jcv_checkEmail(field.value)) { if (i == 0) { focusField = field; } fields[i++] = oEmail[x][1]; bValid = false; } } } if (fields.length > 0) { jcv_handleErrors(fields, focusField); } return bValid; } /** * Reference: Sandeep V. Tamhankar (stamhankar@hotmail.com), * http://javascript.internet.com */ function jcv_checkEmail(emailStr) { if (emailStr.length == 0) { return true; } // TLD checking turned off by default var checkTLD=0; var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/; var emailPat=/^(.+)@(.+)$/; var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]"; var validChars="\[^\\s" + specialChars + "\]"; var quotedUser="(\"[^\"]*\")"; var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/; var atom=validChars + '+'; var word="(" + atom + "|" + quotedUser + ")"; var userPat=new RegExp("^" + word + "(\\." + word + ")*$"); var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$"); var matchArray=emailStr.match(emailPat); if (matchArray==null) { return false; } var user=matchArray[1]; var domain=matchArray[2]; for (i=0; i127) { return false; } } for (i=0; i127) { return false; } } if (user.match(userPat)==null) { return false; } var IPArray=domain.match(ipDomainPat); if (IPArray!=null) { for (var i=1;i<=4;i++) { if (IPArray[i]>255) { return false; } } return true; } var atomPat=new RegExp("^" + atom + "$"); var domArr=domain.split("."); var len=domArr.length; for (i=0;i= 0) { value = field.options[si].value; } } else { value = field.value; } if (value.length > 0) { // remove '.' before checking digits var tempArray = value.split('.'); //Strip off leading '0' var zeroIndex = 0; var joinedString= tempArray.join(''); while (joinedString.charAt(zeroIndex) == '0') { zeroIndex++; } var noZeroString = joinedString.substring(zeroIndex,joinedString.length); if (!jcv_isAllDigits(noZeroString) || tempArray.length > 2) { bValid = false; if (i == 0) { focusField = field; } fields[i++] = oFloat[x][1]; } else { var iValue = parseFloat(value); if (isNaN(iValue)) { if (i == 0) { focusField = field; } fields[i++] = oFloat[x][1]; bValid = false; } } } } } if (fields.length > 0) { jcv_handleErrors(fields, focusField); } return bValid; } ././@LongLink100644 0 0 151 11711231552 10246 Lustar 0 0 commons-validator-1.4.0-src/src/javascript/org/apache/commons/validator/javascript/validateFloatRange.jscommons-validator-1.4.0-src/src/javascript/org/apache/commons/validator/javascript/validateFloatRang100644 765 0 4465 11711227702 35101 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*$RCSfile: validateFloatRange.js,v $ $Rev: 478676 $ $Date: 2006-11-23 22:35:44 +0100 (Thu, 23 Nov 2006) $ */ /** * Check to see if fields are in a valid float range. * Fields are not checked if they are disabled. * @param form The form validation is taking place on. */ function validateFloatRange(form) { var isValid = true; var focusField = null; var i = 0; var fields = new Array(); var oRange = eval('new ' + jcv_retrieveFormName(form) + '_floatRange()'); for (var x in oRange) { if (!jcv_verifyArrayElement(x, oRange[x])) { continue; } var field = form[oRange[x][0]]; if (!jcv_isFieldPresent(field)) { continue; } if ((field.type == 'hidden' || field.type == 'text' || field.type == 'textarea') && (field.value.length > 0)) { var fMin = parseFloat(oRange[x][2]("min")); var fMax = parseFloat(oRange[x][2]("max")); var fValue = parseFloat(field.value); if (!(fValue >= fMin && fValue <= fMax)) { if (i == 0) { focusField = field; } fields[i++] = oRange[x][1]; isValid = false; } } } if (fields.length > 0) { jcv_handleErrors(fields, focusField); } return isValid; } ././@LongLink100644 0 0 147 11711231552 10253 Lustar 0 0 commons-validator-1.4.0-src/src/javascript/org/apache/commons/validator/javascript/validateIntRange.jscommons-validator-1.4.0-src/src/javascript/org/apache/commons/validator/javascript/validateIntRange.100644 765 0 5232 11711227702 35002 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*$RCSfile: validateIntRange.js,v $ $Rev: 478676 $ $Date: 2006-11-23 22:35:44 +0100 (Thu, 23 Nov 2006) $ */ /** * Check to see if fields is in a valid integer range. * Fields are not checked if they are disabled. * @param form The form validation is taking place on. */ function validateIntRange(form) { var isValid = true; var focusField = null; var i = 0; var fields = new Array(); var oRange = eval('new ' + jcv_retrieveFormName(form) + '_intRange()'); for (var x in oRange) { if (!jcv_verifyArrayElement(x, oRange[x])) { continue; } var field = form[oRange[x][0]]; if (jcv_isFieldPresent(field)) { var value = ''; if (field.type == 'hidden' || field.type == 'text' || field.type == 'textarea' || field.type == 'radio' ) { value = field.value; } if (field.type == 'select-one') { var si = field.selectedIndex; if (si >= 0) { value = field.options[si].value; } } if (value.length > 0) { var iMin = parseInt(oRange[x][2]("min")); var iMax = parseInt(oRange[x][2]("max")); var iValue = parseInt(value, 10); if (!(iValue >= iMin && iValue <= iMax)) { if (i == 0) { focusField = field; } fields[i++] = oRange[x][1]; isValid = false; } } } } if (fields.length > 0) { jcv_handleErrors(fields, focusField); } return isValid; } ././@LongLink100644 0 0 146 11711231552 10252 Lustar 0 0 commons-validator-1.4.0-src/src/javascript/org/apache/commons/validator/javascript/validateInteger.jscommons-validator-1.4.0-src/src/javascript/org/apache/commons/validator/javascript/validateInteger.j100644 765 0 6032 11711227702 35041 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*$RCSfile: validateInteger.js,v $ $Rev: 478676 $ $Date: 2006-11-23 22:35:44 +0100 (Thu, 23 Nov 2006) $ */ /** * Check to see if fields are a valid integer. * Fields are not checked if they are disabled. * @param form The form validation is taking place on. */ function validateInteger(form) { var bValid = true; var focusField = null; var i = 0; var fields = new Array(); var oInteger = eval('new ' + jcv_retrieveFormName(form) + '_IntegerValidations()'); for (var x in oInteger) { if (!jcv_verifyArrayElement(x, oInteger[x])) { continue; } var field = form[oInteger[x][0]]; if (!jcv_isFieldPresent(field)) { continue; } if ((field.type == 'hidden' || field.type == 'text' || field.type == 'textarea' || field.type == 'select-one' || field.type == 'radio')) { var value = ''; // get field's value if (field.type == "select-one") { var si = field.selectedIndex; if (si >= 0) { value = field.options[si].value; } } else { value = field.value; } if (value.length > 0) { if (!jcv_isDecimalDigits(value)) { bValid = false; if (i == 0) { focusField = field; } fields[i++] = oInteger[x][1]; } else { var iValue = parseInt(value, 10); if (isNaN(iValue) || !(iValue >= -2147483648 && iValue <= 2147483647)) { if (i == 0) { focusField = field; } fields[i++] = oInteger[x][1]; bValid = false; } } } } } if (fields.length > 0) { jcv_handleErrors(fields, focusField); } return bValid; } commons-validator-1.4.0-src/src/javascript/org/apache/commons/validator/javascript/validateMask.js100644 765 0 4407 11711227702 34526 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*$RCSfile: validateMask.js,v $ $Rev: 478676 $ $Date: 2006-11-23 22:35:44 +0100 (Thu, 23 Nov 2006) $ */ /** * Check to see if fields are a valid using a regular expression. * Fields are not checked if they are disabled. * @param form The form validation is taking place on. */ function validateMask(form) { var isValid = true; var focusField = null; var i = 0; var fields = new Array(); var oMasked = eval('new ' + jcv_retrieveFormName(form) + '_mask()'); for (var x in oMasked) { if (!jcv_verifyArrayElement(x, oMasked[x])) { continue; } var field = form[oMasked[x][0]]; if (!jcv_isFieldPresent(field)) { continue; } if ((field.type == 'hidden' || field.type == 'text' || field.type == 'textarea' || field.type == 'file') && (field.value.length > 0)) { if (!jcv_matchPattern(field.value, oMasked[x][2]("mask"))) { if (i == 0) { focusField = field; } fields[i++] = oMasked[x][1]; isValid = false; } } } if (fields.length > 0) { jcv_handleErrors(fields, focusField); } return isValid; } function jcv_matchPattern(value, mask) { return mask.exec(value); } ././@LongLink100644 0 0 150 11711231552 10245 Lustar 0 0 commons-validator-1.4.0-src/src/javascript/org/apache/commons/validator/javascript/validateMaxLength.jscommons-validator-1.4.0-src/src/javascript/org/apache/commons/validator/javascript/validateMaxLength100644 765 0 6522 11711227702 35107 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*$RCSfile: validateMaxLength.js,v $ $Rev: 478676 $ $Date: 2006-11-23 22:35:44 +0100 (Thu, 23 Nov 2006) $ */ /** * A field is considered valid if less than the specified maximum. * Fields are not checked if they are disabled. * * Caution: Using validateMaxLength() on a password field in a * login page gives unnecessary information away to hackers. While it only slightly * weakens security, we suggest using it only when modifying a password. * @param form The form validation is taking place on. */ function validateMaxLength(form) { var isValid = true; var focusField = null; var i = 0; var fields = new Array(); var oMaxLength = eval('new ' + jcv_retrieveFormName(form) + '_maxlength()'); for (var x in oMaxLength) { if (!jcv_verifyArrayElement(x, oMaxLength[x])) { continue; } var field = form[oMaxLength[x][0]]; if (!jcv_isFieldPresent(field)) { continue; } if ((field.type == 'hidden' || field.type == 'text' || field.type == 'password' || field.type == 'textarea')) { /* Adjust length for carriage returns - see Bug 37962 */ var lineEndLength = oMaxLength[x][2]("lineEndLength"); var adjustAmount = 0; if (lineEndLength) { var rCount = 0; var nCount = 0; var crPos = 0; while (crPos < field.value.length) { var currChar = field.value.charAt(crPos); if (currChar == '\r') { rCount++; } if (currChar == '\n') { nCount++; } crPos++; } var endLength = parseInt(lineEndLength); adjustAmount = (nCount * endLength) - (rCount + nCount); } var iMax = parseInt(oMaxLength[x][2]("maxlength")); if ((field.value.length + adjustAmount) > iMax) { if (i == 0) { focusField = field; } fields[i++] = oMaxLength[x][1]; isValid = false; } } } if (fields.length > 0) { jcv_handleErrors(fields, focusField); } return isValid; } ././@LongLink100644 0 0 150 11711231552 10245 Lustar 0 0 commons-validator-1.4.0-src/src/javascript/org/apache/commons/validator/javascript/validateMinLength.jscommons-validator-1.4.0-src/src/javascript/org/apache/commons/validator/javascript/validateMinLength100644 765 0 6560 11711227702 35107 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*$RCSfile: validateMinLength.js,v $ $Rev: 478676 $ $Date: 2006-11-23 22:35:44 +0100 (Thu, 23 Nov 2006) $ */ /** * A field is considered valid if greater than the specified minimum. * Fields are not checked if they are disabled. * * Caution: Using validateMinLength() on a password field in a * login page gives unnecessary information away to hackers. While it only slightly * weakens security, we suggest using it only when modifying a password. * @param form The form validation is taking place on. */ function validateMinLength(form) { var isValid = true; var focusField = null; var i = 0; var fields = new Array(); var oMinLength = eval('new ' + jcv_retrieveFormName(form) + '_minlength()'); for (var x in oMinLength) { if (!jcv_verifyArrayElement(x, oMinLength[x])) { continue; } var field = form[oMinLength[x][0]]; if (!jcv_isFieldPresent(field)) { continue; } if ((field.type == 'hidden' || field.type == 'text' || field.type == 'password' || field.type == 'textarea')) { /* Adjust length for carriage returns - see Bug 37962 */ var lineEndLength = oMinLength[x][2]("lineEndLength"); var adjustAmount = 0; if (lineEndLength) { var rCount = 0; var nCount = 0; var crPos = 0; while (crPos < field.value.length) { var currChar = field.value.charAt(crPos); if (currChar == '\r') { rCount++; } if (currChar == '\n') { nCount++; } crPos++; } var endLength = parseInt(lineEndLength); adjustAmount = (nCount * endLength) - (rCount + nCount); } var iMin = parseInt(oMinLength[x][2]("minlength")); if ((trim(field.value).length > 0) && ((field.value.length + adjustAmount) < iMin)) { if (i == 0) { focusField = field; } fields[i++] = oMinLength[x][1]; isValid = false; } } } if (fields.length > 0) { jcv_handleErrors(fields, focusField); } return isValid; } ././@LongLink100644 0 0 147 11711231552 10253 Lustar 0 0 commons-validator-1.4.0-src/src/javascript/org/apache/commons/validator/javascript/validateRequired.jscommons-validator-1.4.0-src/src/javascript/org/apache/commons/validator/javascript/validateRequired.100644 765 0 10325 11711227702 35072 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*$RCSfile: validateRequired.js,v $ $Rev: 507611 $ $Date: 2007-02-14 17:40:49 +0100 (Wed, 14 Feb 2007) $ */ /** * Check to see if fields must contain a value. * Fields are not checked if they are disabled. * * @param form The form validation is taking place on. */ function validateRequired(form) { var isValid = true; var focusField = null; var i = 0; var fields = new Array(); var oRequired = eval('new ' + jcv_retrieveFormName(form) + '_required()'); for (var x in oRequired) { if (!jcv_verifyArrayElement(x, oRequired[x])) { continue; } var field = form[oRequired[x][0]]; if (!jcv_isFieldPresent(field)) { fields[i++] = oRequired[x][1]; isValid=false; } else if ((field.type == 'hidden' || field.type == 'text' || field.type == 'textarea' || field.type == 'file' || field.type == 'radio' || field.type == 'checkbox' || field.type == 'select-one' || field.type == 'password')) { var value = ''; // get field's value if (field.type == "select-one") { var si = field.selectedIndex; if (si >= 0) { value = field.options[si].value; } } else if (field.type == 'radio' || field.type == 'checkbox') { if (field.checked) { value = field.value; } } else { value = field.value; } if (trim(value).length == 0) { if ((i == 0) && (field.type != 'hidden')) { focusField = field; } fields[i++] = oRequired[x][1]; isValid = false; } } else if (field.type == "select-multiple") { var numOptions = field.options.length; lastSelected=-1; for(loop=numOptions-1;loop>=0;loop--) { if(field.options[loop].selected) { lastSelected = loop; value = field.options[loop].value; break; } } if(lastSelected < 0 || trim(value).length == 0) { if(i == 0) { focusField = field; } fields[i++] = oRequired[x][1]; isValid=false; } } else if ((field.length > 0) && (field[0].type == 'radio' || field[0].type == 'checkbox')) { isChecked=-1; for (loop=0;loop < field.length;loop++) { if (field[loop].checked) { isChecked=loop; break; // only one needs to be checked } } if (isChecked < 0) { if (i == 0) { focusField = field[0]; } fields[i++] = oRequired[x][1]; isValid=false; } } } if (fields.length > 0) { jcv_handleErrors(fields, focusField); } return isValid; } commons-validator-1.4.0-src/src/javascript/org/apache/commons/validator/javascript/validateShort.js100644 765 0 6005 11711227702 34726 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*$RCSfile: validateShort.js,v $ $Rev: 478676 $ $Date: 2006-11-23 22:35:44 +0100 (Thu, 23 Nov 2006) $ */ /** * Check to see if fields are a valid short. * Fields are not checked if they are disabled. * * @param form The form validation is taking place on. */ function validateShort(form) { var bValid = true; var focusField = null; var i = 0; var fields = new Array(); var oShort = eval('new ' + jcv_retrieveFormName(form) + '_ShortValidations()'); for (var x in oShort) { if (!jcv_verifyArrayElement(x, oShort[x])) { continue; } var field = form[oShort[x][0]]; if (!jcv_isFieldPresent(field)) { continue; } if ((field.type == 'hidden' || field.type == 'text' || field.type == 'textarea' || field.type == 'select-one' || field.type == 'radio')) { var value = ''; // get field's value if (field.type == "select-one") { var si = field.selectedIndex; if (si >= 0) { value = field.options[si].value; } } else { value = field.value; } if (value.length > 0) { if (!jcv_isDecimalDigits(value)) { bValid = false; if (i == 0) { focusField = field; } fields[i++] = oShort[x][1]; } else { var iValue = parseInt(value, 10); if (isNaN(iValue) || !(iValue >= -32768 && iValue <= 32767)) { if (i == 0) { focusField = field; } fields[i++] = oShort[x][1]; bValid = false; } } } } } if (fields.length > 0) { jcv_handleErrors(fields, focusField); } return bValid; } ././@LongLink100644 0 0 150 11711231552 10245 Lustar 0 0 commons-validator-1.4.0-src/src/javascript/org/apache/commons/validator/javascript/validateUtilities.jscommons-validator-1.4.0-src/src/javascript/org/apache/commons/validator/javascript/validateUtilities100644 765 0 11613 11711227702 35210 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*$RCSfile: validateUtilities.js,v $ $Rev: 507685 $ $Date: 2007-02-14 21:41:34 +0100 (Wed, 14 Feb 2007) $ */ /** * This is a place holder for common utilities used across the javascript validation * **/ /** * Retreive the name of the form * @param form The form validation is taking place on. */ function jcv_retrieveFormName(form) { // Please refer to Bugs 31534, 35127, 35294, 37315 & 38159 // for the history of the following code var formName; if (form.getAttributeNode) { if (form.getAttributeNode("id") && form.getAttributeNode("id").value) { formName = form.getAttributeNode("id").value; } else { formName = form.getAttributeNode("name").value; } } else if (form.getAttribute) { if (form.getAttribute("id")) { formName = form.getAttribute("id"); } else { formName = form.attributes["name"]; } } else { if (form.id) { formName = form.id; } else { formName = form.name; } } /* fix for VALIDATOR-224 */ formName = formName.replace(/:/gi, "_"); return formName; } /** * Handle error messages. * @param messages Array of error messages. * @param focusField Field to set focus on. */ function jcv_handleErrors(messages, focusField) { if (focusField && focusField != null) { var doFocus = true; if (focusField.disabled || focusField.type == 'hidden') { doFocus = false; } if (doFocus && focusField.style && focusField.style.visibility && focusField.style.visibility == 'hidden') { doFocus = false; } if (doFocus) { focusField.focus(); } } alert(messages.join('\n')); } /** * Checks that the array element is a valid * Commons Validator element and not one inserted by * other JavaScript libraries (for example the * prototype library inserts an "extends" into * all objects, including Arrays). * @param name The element name. * @param value The element value. */ function jcv_verifyArrayElement(name, element) { if (element && element.length && element.length == 3) { return true; } else { return false; } } /** * Checks whether the field is present on the form. * @param field The form field. */ function jcv_isFieldPresent(field) { var fieldPresent = true; if (field == null || (typeof field == 'undefined')) { fieldPresent = false; } else { if (field.disabled) { fieldPresent = false; } } return fieldPresent; } /** * Check a value only contains valid numeric digits * @param argvalue The value to check. */ function jcv_isAllDigits(argvalue) { argvalue = argvalue.toString(); var validChars = "0123456789"; var startFrom = 0; if (argvalue.substring(0, 2) == "0x") { validChars = "0123456789abcdefABCDEF"; startFrom = 2; } else if (argvalue.charAt(0) == "0") { validChars = "01234567"; startFrom = 1; } else if (argvalue.charAt(0) == "-") { startFrom = 1; } for (var n = startFrom; n < argvalue.length; n++) { if (validChars.indexOf(argvalue.substring(n, n+1)) == -1) return false; } return true; } /** * Check a value only contains valid decimal digits * @param argvalue The value to check. */ function jcv_isDecimalDigits(argvalue) { argvalue = argvalue.toString(); var validChars = "0123456789"; var startFrom = 0; if (argvalue.charAt(0) == "-") { startFrom = 1; } for (var n = startFrom; n < argvalue.length; n++) { if (validChars.indexOf(argvalue.substring(n, n+1)) == -1) return false; } return true; } // Trim whitespace from left and right sides of s. function trim(s) { return s.replace( /^\s*/, "" ).replace( /\s*$/, "" ); } commons-validator-1.4.0-src/src/main/assembly/bin.xml100644 765 0 3131 11711227700 23623 0ustarsimonetripodiwheel 0 0 bin tar.gz zip false LICENSE.txt NOTICE.txt RELEASE-NOTES.txt target *.jar *.js target/site/apidocs apidocs commons-validator-1.4.0-src/src/main/assembly/src.xml100644 765 0 3321 11711227700 23643 0ustarsimonetripodiwheel 0 0 src tar.gz zip ${artifactId}-${version}-src build.properties.sample build.xml build-javascript.xml doap_validator.rdf checkstyle.xml LICENSE.txt license-header.txt NOTICE.txt pom.xml RELEASE-NOTES.txt etc src commons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/Arg.java100644 765 0 12365 11711227702 30512 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator; import java.io.Serializable; /** *

* A default argument or an argument for a * specific validator definition (ex: required) * can be stored to pass into a message as parameters. This can be used in a * pluggable validator for constructing locale * sensitive messages by using java.text.MessageFormat * or an equivalent class. The resource field can be * used to determine if the value stored in the argument * is a value to be retrieved from a locale sensitive * message retrieval system like java.util.PropertyResourceBundle. * The resource field defaults to 'true'. *

*

Instances of this class are configured with an <arg> xml element.

* * @version $Revision: 1227719 $ $Date: 2012-01-05 18:45:51 +0100 (Thu, 05 Jan 2012) $ */ public class Arg implements Cloneable, Serializable { private static final long serialVersionUID = -8922606779669839294L; /** * The resource bundle name that this Arg's key should be * resolved in (optional). * @since Validator 1.1 */ protected String bundle = null; /** * The key or value of the argument. */ protected String key = null; /** * The name dependency that this argument goes with (optional). */ protected String name = null; /** * This argument's position in the message. Set postion=0 to * make a replacement in this string: "some msg {0}". * @since Validator 1.1 */ protected int position = -1; /** * Whether or not the key is a message resource (optional). Defaults to * true. If it is 'true', the value will try to be resolved as a message * resource. */ protected boolean resource = true; /** * Creates and returns a copy of this object. * @return A copy of this object. */ public Object clone() { try { return super.clone(); } catch(CloneNotSupportedException e) { throw new RuntimeException(e.toString()); } } /** * Returns the resource bundle name. * @return the bundle name. * @since Validator 1.1 */ public String getBundle() { return this.bundle; } /** * Gets the key/value. * @return the key value. */ public String getKey() { return this.key; } /** * Gets the name of the dependency. * @return the name of the dependency. */ public String getName() { return this.name; } /** * Argument's replacement position. * @return This argument's replacement position. */ public int getPosition() { return this.position; } /** * Tests whether or not the key is a resource key or literal value. * @return true if key is a resource key. */ public boolean isResource() { return this.resource; } /** * Sets the resource bundle name. * @param bundle The new bundle name. * @since Validator 1.1 */ public void setBundle(String bundle) { this.bundle = bundle; } /** * Sets the key/value. * @param key They to access the argument. */ public void setKey(String key) { this.key = key; } /** * Sets the name of the dependency. * @param name the name of the dependency. */ public void setName(String name) { this.name = name; } /** * Set this argument's replacement position. * @param position set this argument's replacement position. */ public void setPosition(int position) { this.position = position; } /** * Sets whether or not the key is a resource. * @param resource If true indicates the key is a resource. */ public void setResource(boolean resource) { this.resource = resource; } /** * Returns a string representation of the object. * @return a string representation of the object. */ public String toString() { StringBuffer results = new StringBuffer(); results.append("Arg: name="); results.append(name); results.append(" key="); results.append(key); results.append(" position="); results.append(position); results.append(" bundle="); results.append(bundle); results.append(" resource="); results.append(resource); results.append("\n"); return results.toString(); } }commons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/CreditCardValidator.java100644 765 0 17662 11711227702 33660 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import org.apache.commons.validator.util.Flags; /** *

Perform credit card validations.

*

* By default, all supported card types are allowed. You can specify which * cards should pass validation by configuring the validation options. For * example,
CreditCardValidator ccv = new CreditCardValidator(CreditCardValidator.AMEX + CreditCardValidator.VISA); * configures the validator to only pass American Express and Visa cards. * If a card type is not directly supported by this class, you can implement * the CreditCardType interface and pass an instance into the * addAllowedCardType method. *

* For a similar implementation in Perl, reference Sean M. Burke's * script. * More information is also available * here. * * @version $Revision: 1227688 $ $Date: 2012-01-05 17:43:11 +0100 (Thu, 05 Jan 2012) $ * @since Validator 1.1 * @deprecated Use the new CreditCardValidator in the routines package. This class * will be removed in a future release. */ public class CreditCardValidator { /** * Option specifying that no cards are allowed. This is useful if * you want only custom card types to validate so you turn off the * default cards with this option. *
*
     * CreditCardValidator v = new CreditCardValidator(CreditCardValidator.NONE);
     * v.addAllowedCardType(customType);
     * v.isValid(aCardNumber);
     * 
* @since Validator 1.1.2 */ public static final int NONE = 0; /** * Option specifying that American Express cards are allowed. */ public static final int AMEX = 1 << 0; /** * Option specifying that Visa cards are allowed. */ public static final int VISA = 1 << 1; /** * Option specifying that Mastercard cards are allowed. */ public static final int MASTERCARD = 1 << 2; /** * Option specifying that Discover cards are allowed. */ public static final int DISCOVER = 1 << 3; /** * The CreditCardTypes that are allowed to pass validation. */ private Collection cardTypes = new ArrayList(); /** * Create a new CreditCardValidator with default options. */ public CreditCardValidator() { this(AMEX + VISA + MASTERCARD + DISCOVER); } /** * Create a new CreditCardValidator with the specified options. * @param options Pass in * CreditCardValidator.VISA + CreditCardValidator.AMEX to specify that * those are the only valid card types. */ public CreditCardValidator(int options) { super(); Flags f = new Flags(options); if (f.isOn(VISA)) { this.cardTypes.add(new Visa()); } if (f.isOn(AMEX)) { this.cardTypes.add(new Amex()); } if (f.isOn(MASTERCARD)) { this.cardTypes.add(new Mastercard()); } if (f.isOn(DISCOVER)) { this.cardTypes.add(new Discover()); } } /** * Checks if the field is a valid credit card number. * @param card The card number to validate. * @return Whether the card number is valid. */ public boolean isValid(String card) { if ((card == null) || (card.length() < 13) || (card.length() > 19)) { return false; } if (!this.luhnCheck(card)) { return false; } Iterator types = this.cardTypes.iterator(); while (types.hasNext()) { CreditCardType type = (CreditCardType) types.next(); if (type.matches(card)) { return true; } } return false; } /** * Add an allowed CreditCardType that participates in the card * validation algorithm. * @param type The type that is now allowed to pass validation. * @since Validator 1.1.2 */ public void addAllowedCardType(CreditCardType type){ this.cardTypes.add(type); } /** * Checks for a valid credit card number. * @param cardNumber Credit Card Number. * @return Whether the card number passes the luhnCheck. */ protected boolean luhnCheck(String cardNumber) { // number must be validated as 0..9 numeric first!! int digits = cardNumber.length(); int oddOrEven = digits & 1; long sum = 0; for (int count = 0; count < digits; count++) { int digit = 0; try { digit = Integer.parseInt(cardNumber.charAt(count) + ""); } catch(NumberFormatException e) { return false; } if (((count & 1) ^ oddOrEven) == 0) { // not digit *= 2; if (digit > 9) { digit -= 9; } } sum += digit; } return (sum == 0) ? false : (sum % 10 == 0); } /** * CreditCardType implementations define how validation is performed * for one type/brand of credit card. * @since Validator 1.1.2 */ public interface CreditCardType { /** * Returns true if the card number matches this type of credit * card. Note that this method is not responsible * for analyzing the general form of the card number because * CreditCardValidator performs those checks before * calling this method. It is generally only required to valid the * length and prefix of the number to determine if it's the correct * type. * @param card The card number, never null. * @return true if the number matches. */ boolean matches(String card); } /** * Change to support Visa Carte Blue used in France * has been removed - see Bug 35926 */ private static class Visa implements CreditCardType { private static final String PREFIX = "4"; public boolean matches(String card) { return ( card.substring(0, 1).equals(PREFIX) && (card.length() == 13 || card.length() == 16)); } } private static class Amex implements CreditCardType { private static final String PREFIX = "34,37,"; public boolean matches(String card) { String prefix2 = card.substring(0, 2) + ","; return ((PREFIX.indexOf(prefix2) != -1) && (card.length() == 15)); } } private static class Discover implements CreditCardType { private static final String PREFIX = "6011"; public boolean matches(String card) { return (card.substring(0, 4).equals(PREFIX) && (card.length() == 16)); } } private static class Mastercard implements CreditCardType { private static final String PREFIX = "51,52,53,54,55,"; public boolean matches(String card) { String prefix2 = card.substring(0, 2) + ","; return ((PREFIX.indexOf(prefix2) != -1) && (card.length() == 16)); } } } commons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/DateValidator.java100644 765 0 10212 11711227702 32511 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Locale; /** *

Perform date validations.

*

* This class is a Singleton; you can retrieve the instance via the * getInstance() method. *

* * @version $Revision: 594962 $ $Date: 2007-11-14 18:30:27 +0100 (Wed, 14 Nov 2007) $ * @since Validator 1.1 * @deprecated Use the new DateValidator, CalendarValidator or TimeValidator in the * routines package. This class will be removed in a future release. */ public class DateValidator { /** * Singleton instance of this class. */ private static final DateValidator DATE_VALIDATOR = new DateValidator(); /** * Returns the Singleton instance of this validator. * @return A singleton instance of the DateValidator. */ public static DateValidator getInstance() { return DATE_VALIDATOR; } /** * Protected constructor for subclasses to use. */ protected DateValidator() { super(); } /** *

Checks if the field is a valid date. The pattern is used with * java.text.SimpleDateFormat. If strict is true, then the * length will be checked so '2/12/1999' will not pass validation with * the format 'MM/dd/yyyy' because the month isn't two digits. * The setLenient method is set to false for all.

* * @param value The value validation is being performed on. * @param datePattern The pattern passed to SimpleDateFormat. * @param strict Whether or not to have an exact match of the datePattern. * @return true if the date is valid. */ public boolean isValid(String value, String datePattern, boolean strict) { if (value == null || datePattern == null || datePattern.length() <= 0) { return false; } SimpleDateFormat formatter = new SimpleDateFormat(datePattern); formatter.setLenient(false); try { formatter.parse(value); } catch(ParseException e) { return false; } if (strict && (datePattern.length() != value.length())) { return false; } return true; } /** *

Checks if the field is a valid date. The Locale is * used with java.text.DateFormat. The setLenient method * is set to false for all.

* * @param value The value validation is being performed on. * @param locale The locale to use for the date format, defaults to the default * system default if null. * @return true if the date is valid. */ public boolean isValid(String value, Locale locale) { if (value == null) { return false; } DateFormat formatter = null; if (locale != null) { formatter = DateFormat.getDateInstance(DateFormat.SHORT, locale); } else { formatter = DateFormat.getDateInstance( DateFormat.SHORT, Locale.getDefault()); } formatter.setLenient(false); try { formatter.parse(value); } catch(ParseException e) { return false; } return true; } } commons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/EmailValidator.java100644 765 0 17260 11711227702 32675 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator; import org.apache.commons.validator.routines.InetAddressValidator; import java.util.regex.Matcher; import java.util.regex.Pattern; /** *

Perform email validations.

*

* This class is a Singleton; you can retrieve the instance via the getInstance() method. *

*

* Based on a script by Sandeep V. Tamhankar * http://javascript.internet.com *

*

* This implementation is not guaranteed to catch all possible errors in an email address. * For example, an address like nobody@noplace.somedog will pass validator, even though there * is no TLD "somedog" *

. * * @version $Revision: 1195321 $ $Date: 2011-10-31 04:46:07 +0100 (Mon, 31 Oct 2011) $ * @since Validator 1.1 * @deprecated Use the new EmailValidator in the routines package. This class * will be removed in a future release. */ public class EmailValidator { private static final String SPECIAL_CHARS = "\\p{Cntrl}\\(\\)<>@,;:'\\\\\\\"\\.\\[\\]"; private static final String VALID_CHARS = "[^\\s" + SPECIAL_CHARS + "]"; private static final String QUOTED_USER = "(\"[^\"]*\")"; private static final String ATOM = VALID_CHARS + '+'; private static final String WORD = "((" + VALID_CHARS + "|')+|" + QUOTED_USER + ")"; private static final Pattern LEGAL_ASCII_PATTERN = Pattern.compile("^\\p{ASCII}+$"); private static final Pattern EMAIL_PATTERN = Pattern.compile("^(.+)@(.+)$"); private static final Pattern IP_DOMAIN_PATTERN = Pattern.compile("^\\[(.*)\\]$"); private static final Pattern TLD_PATTERN = Pattern.compile("^([a-zA-Z]+)$"); private static final Pattern USER_PATTERN = Pattern.compile("^\\s*" + WORD + "(\\." + WORD + ")*$"); private static final Pattern DOMAIN_PATTERN = Pattern.compile("^" + ATOM + "(\\." + ATOM + ")*\\s*$"); private static final Pattern ATOM_PATTERN = Pattern.compile("(" + ATOM + ")"); /** * Singleton instance of this class. */ private static final EmailValidator EMAIL_VALIDATOR = new EmailValidator(); /** * Returns the Singleton instance of this validator. * @return singleton instance of this validator. */ public static EmailValidator getInstance() { return EMAIL_VALIDATOR; } /** * Protected constructor for subclasses to use. */ protected EmailValidator() { super(); } /** *

Checks if a field has a valid e-mail address.

* * @param email The value validation is being performed on. A null * value is considered invalid. * @return true if the email address is valid. */ public boolean isValid(String email) { return org.apache.commons.validator.routines.EmailValidator.getInstance().isValid(email); } /** * Returns true if the domain component of an email address is valid. * @param domain being validated. * @return true if the email address's domain is valid. */ protected boolean isValidDomain(String domain) { boolean symbolic = false; // see if domain is an IP address in brackets Matcher ipDomainMatcher = IP_DOMAIN_PATTERN.matcher(domain); if (ipDomainMatcher.matches()) { InetAddressValidator inetAddressValidator = InetAddressValidator.getInstance(); if (inetAddressValidator.isValid(ipDomainMatcher.group(1))) { return true; } } else { // Domain is symbolic name symbolic = DOMAIN_PATTERN.matcher(domain).matches(); } if (symbolic) { if (!isValidSymbolicDomain(domain)) { return false; } } else { return false; } return true; } /** * Returns true if the user component of an email address is valid. * @param user being validated * @return true if the user name is valid. */ protected boolean isValidUser(String user) { return USER_PATTERN.matcher(user).matches(); } /** * Validates an IP address. Returns true if valid. * @param ipAddress IP address * @return true if the ip address is valid. */ protected boolean isValidIpAddress(String ipAddress) { Matcher ipAddressMatcher = IP_DOMAIN_PATTERN.matcher(ipAddress); for (int i = 1; i <= 4; i++) { String ipSegment = ipAddressMatcher.group(i); if (ipSegment == null || ipSegment.length() <= 0) { return false; } int iIpSegment = 0; try { iIpSegment = Integer.parseInt(ipSegment); } catch(NumberFormatException e) { return false; } if (iIpSegment > 255) { return false; } } return true; } /** * Validates a symbolic domain name. Returns true if it's valid. * @param domain symbolic domain name * @return true if the symbolic domain name is valid. */ protected boolean isValidSymbolicDomain(String domain) { String[] domainSegment = new String[10]; boolean match = true; int i = 0; Matcher atomMatcher = ATOM_PATTERN.matcher(domain); while (match) { match = atomMatcher.matches(); if (match) { domainSegment[i] = atomMatcher.group(1); int l = domainSegment[i].length() + 1; domain = (l >= domain.length()) ? "" : domain.substring(l); i++; } } int len = i; // Make sure there's a host name preceding the domain. if (len < 2) { return false; } // TODO: the tld should be checked against some sort of configurable // list String tld = domainSegment[len - 1]; if (tld.length() > 1) { if (! TLD_PATTERN.matcher(tld).matches()) { return false; } } else { return false; } return true; } /** * Recursively remove comments, and replace with a single space. The simpler * regexps in the Email Addressing FAQ are imperfect - they will miss escaped * chars in atoms, for example. * Derived From Mail::RFC822::Address * @param emailStr The email address * @return address with comments removed. */ protected String stripComments(String emailStr) { String result = emailStr; String commentPat = "^((?:[^\"\\\\]|\\\\.)*(?:\"(?:[^\"\\\\]|\\\\.)*\"(?:[^\"\\\\]|\111111\\\\.)*)*)\\((?:[^()\\\\]|\\\\.)*\\)/"; Pattern commentMatcher = Pattern.compile(commentPat); while (commentMatcher.matcher(result).matches()) { result = result.replaceFirst(commentPat, "\1 "); } return result; } } commons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/Field.java100644 765 0 71626 11711227702 31031 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator; import java.io.Serializable; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.StringTokenizer; import org.apache.commons.beanutils.PropertyUtils; import org.apache.commons.collections.FastHashMap; // DEPRECATED import org.apache.commons.validator.util.ValidatorUtils; /** * This contains the list of pluggable validators to run on a field and any * message information and variables to perform the validations and generate * error messages. Instances of this class are configured with a * <field> xml element. *

* The use of FastHashMap is deprecated and will be replaced in a future * release. *

* * @version $Revision: 1227719 $ $Date: 2012-01-05 18:45:51 +0100 (Thu, 05 Jan 2012) $ * @see org.apache.commons.validator.Form */ public class Field implements Cloneable, Serializable { private static final long serialVersionUID = -8502647722530192185L; /** * This is the value that will be used as a key if the Arg * name field has no value. */ private static final String DEFAULT_ARG = "org.apache.commons.validator.Field.DEFAULT"; /** * This indicates an indexed property is being referenced. */ public static final String TOKEN_INDEXED = "[]"; /** * The start of a token. */ protected static final String TOKEN_START = "${"; /** * The end of a token. */ protected static final String TOKEN_END = "}"; /** * A Vriable token. */ protected static final String TOKEN_VAR = "var:"; /** * The Field's property name. */ protected String property = null; /** * The Field's indexed property name. */ protected String indexedProperty = null; /** * The Field's indexed list property name. */ protected String indexedListProperty = null; /** * The Field's unique key. */ protected String key = null; /** * A comma separated list of validator's this field depends on. */ protected String depends = null; /** * The Page Number */ protected int page = 0; /** * The flag that indicates whether scripting should be generated * by the client for client-side validation. * @since Validator 1.4 */ protected boolean clientValidation = true; /** * The order of the Field in the Form. */ protected int fieldOrder = 0; /** * Internal representation of this.depends String as a List. This List * gets updated whenever setDepends() gets called. This List is * synchronized so a call to setDepends() (which clears the List) won't * interfere with a call to isDependency(). */ private List dependencyList = Collections.synchronizedList(new ArrayList()); /** * @deprecated Subclasses should use getVarMap() instead. */ protected FastHashMap hVars = new FastHashMap(); /** * @deprecated Subclasses should use getMsgMap() instead. */ protected FastHashMap hMsgs = new FastHashMap(); /** * Holds Maps of arguments. args[0] returns the Map for the first * replacement argument. Start with a 0 length array so that it will * only grow to the size of the highest argument position. * @since Validator 1.1 */ protected Map[] args = new Map[0]; /** * Gets the page value that the Field is associated with for * validation. * @return The page number. */ public int getPage() { return this.page; } /** * Sets the page value that the Field is associated with for * validation. * @param page The page number. */ public void setPage(int page) { this.page = page; } /** * Gets the position of the Field in the validation list. * @return The field position. */ public int getFieldOrder() { return this.fieldOrder; } /** * Sets the position of the Field in the validation list. * @param fieldOrder The field position. */ public void setFieldOrder(int fieldOrder) { this.fieldOrder = fieldOrder; } /** * Gets the property name of the field. * @return The field's property name. */ public String getProperty() { return this.property; } /** * Sets the property name of the field. * @param property The field's property name. */ public void setProperty(String property) { this.property = property; } /** * Gets the indexed property name of the field. This * is the method name that can take an int as * a parameter for indexed property value retrieval. * @return The field's indexed property name. */ public String getIndexedProperty() { return this.indexedProperty; } /** * Sets the indexed property name of the field. * @param indexedProperty The field's indexed property name. */ public void setIndexedProperty(String indexedProperty) { this.indexedProperty = indexedProperty; } /** * Gets the indexed property name of the field. This * is the method name that will return an array or a * Collection used to retrieve the * list and then loop through the list performing the specified * validations. * @return The field's indexed List property name. */ public String getIndexedListProperty() { return this.indexedListProperty; } /** * Sets the indexed property name of the field. * @param indexedListProperty The field's indexed List property name. */ public void setIndexedListProperty(String indexedListProperty) { this.indexedListProperty = indexedListProperty; } /** * Gets the validation rules for this field as a comma separated list. * @return A comma separated list of validator names. */ public String getDepends() { return this.depends; } /** * Sets the validation rules for this field as a comma separated list. * @param depends A comma separated list of validator names. */ public void setDepends(String depends) { this.depends = depends; this.dependencyList.clear(); StringTokenizer st = new StringTokenizer(depends, ","); while (st.hasMoreTokens()) { String depend = st.nextToken().trim(); if (depend != null && depend.length() > 0) { this.dependencyList.add(depend); } } } /** * Add a Msg to the Field. * @param msg A validation message. */ public void addMsg(Msg msg) { hMsgs.put(msg.getName(), msg); } /** * Retrieve a message value. * @param key Validation key. * @return A validation message for a specified validator. */ public String getMsg(String key) { Msg msg = getMessage(key); return (msg == null) ? null : msg.getKey(); } /** * Retrieve a message object. * @since Validator 1.1.4 * @param key Validation key. * @return A validation message for a specified validator. */ public Msg getMessage(String key) { return (Msg) hMsgs.get(key); } /** * The Field's messages are returned as an * unmodifiable Map. * @since Validator 1.1.4 * @return Map of validation messages for the field. */ public Map getMessages() { return Collections.unmodifiableMap(hMsgs); } /** * Determines whether client-side scripting should be generated * for this field. The default is true * @return true for scripting; otherwise false * @see #setClientValidation(boolean) * @since Validator 1.4 */ public boolean isClientValidation() { return this.clientValidation; } /** * Sets the flag that determines whether client-side scripting should * be generated for this field. * @param clientValidation the scripting flag * @see #isClientValidation() * @since Validator 1.4 */ public void setClientValidation(boolean clientValidation) { this.clientValidation = clientValidation; } /** * Add an Arg to the replacement argument list. * @since Validator 1.1 * @param arg Validation message's argument. */ public void addArg(Arg arg) { // TODO this first if check can go away after arg0, etc. are removed from dtd if (arg == null || arg.getKey() == null || arg.getKey().length() == 0) { return; } determineArgPosition(arg); ensureArgsCapacity(arg); Map argMap = this.args[arg.getPosition()]; if (argMap == null) { argMap = new HashMap(); this.args[arg.getPosition()] = argMap; } if (arg.getName() == null) { argMap.put(DEFAULT_ARG, arg); } else { argMap.put(arg.getName(), arg); } } /** * Calculate the position of the Arg */ private void determineArgPosition(Arg arg) { int position = arg.getPosition(); // position has been explicity set if (position >= 0) { return; } // first arg to be added if (args == null || args.length == 0) { arg.setPosition(0); return; } // determine the position of the last argument with // the same name or the last default argument String key = arg.getName() == null ? DEFAULT_ARG : arg.getName(); int lastPosition = -1; int lastDefault = -1; for (int i = 0; i < args.length; i++) { if (args[i] != null && args[i].containsKey(key)) { lastPosition = i; } if (args[i] != null && args[i].containsKey(DEFAULT_ARG)) { lastDefault = i; } } if (lastPosition < 0) { lastPosition = lastDefault; } // allocate the next position arg.setPosition(++lastPosition); } /** * Ensures that the args array can hold the given arg. Resizes the array as * necessary. * @param arg Determine if the args array is long enough to store this arg's * position. */ private void ensureArgsCapacity(Arg arg) { if (arg.getPosition() >= this.args.length) { Map[] newArgs = new Map[arg.getPosition() + 1]; System.arraycopy(this.args, 0, newArgs, 0, this.args.length); this.args = newArgs; } } /** * Gets the default Arg object at the given position. * @param position Validation message argument's position. * @return The default Arg or null if not found. * @since Validator 1.1 */ public Arg getArg(int position) { return this.getArg(DEFAULT_ARG, position); } /** * Gets the Arg object at the given position. If the key * finds a null value then the default value will be * retrieved. * @param key The name the Arg is stored under. If not found, the default * Arg for the given position (if any) will be retrieved. * @param position The Arg number to find. * @return The Arg with the given name and position or null if not found. * @since Validator 1.1 */ public Arg getArg(String key, int position) { if ((position >= this.args.length) || (this.args[position] == null)) { return null; } Arg arg = (Arg) args[position].get(key); // Didn't find default arg so exit, otherwise we would get into // infinite recursion if ((arg == null) && key.equals(DEFAULT_ARG)) { return null; } return (arg == null) ? this.getArg(position) : arg; } /** * Retrieves the Args for the given validator name. * @param key The validator's args to retrieve. * @return An Arg[] sorted by the Args' positions (i.e. the Arg at index 0 * has a position of 0). * @since Validator 1.1.1 */ public Arg[] getArgs(String key){ Arg[] args = new Arg[this.args.length]; for (int i = 0; i < this.args.length; i++) { args[i] = this.getArg(key, i); } return args; } /** * Add a Var to the Field. * @param v The Validator Argument. */ public void addVar(Var v) { this.hVars.put(v.getName(), v); } /** * Add a Var, based on the values passed in, to the * Field. * @param name Name of the validation. * @param value The Argument's value. * @param jsType The Javascript type. */ public void addVar(String name, String value, String jsType) { this.addVar(new Var(name, value, jsType)); } /** * Retrieve a variable. * @param mainKey The Variable's key * @return the Variable */ public Var getVar(String mainKey) { return (Var) hVars.get(mainKey); } /** * Retrieve a variable's value. * @param mainKey The Variable's key * @return the Variable's value */ public String getVarValue(String mainKey) { String value = null; Object o = hVars.get(mainKey); if (o != null && o instanceof Var) { Var v = (Var) o; value = v.getValue(); } return value; } /** * The Field's variables are returned as an * unmodifiable Map. * @return the Map of Variable's for a Field. */ public Map getVars() { return Collections.unmodifiableMap(hVars); } /** * Gets a unique key based on the property and indexedProperty fields. * @return a unique key for the field. */ public String getKey() { if (this.key == null) { this.generateKey(); } return this.key; } /** * Sets a unique key for the field. This can be used to change * the key temporarily to have a unique key for an indexed field. * @param key a unique key for the field */ public void setKey(String key) { this.key = key; } /** * If there is a value specified for the indexedProperty field then * true will be returned. Otherwise it will be * false. * @return Whether the Field is indexed. */ public boolean isIndexed() { return ((indexedListProperty != null && indexedListProperty.length() > 0)); } /** * Generate correct key value. */ public void generateKey() { if (this.isIndexed()) { this.key = this.indexedListProperty + TOKEN_INDEXED + "." + this.property; } else { this.key = this.property; } } /** * Replace constants with values in fields and process the depends field * to create the dependency Map. */ void process(Map globalConstants, Map constants) { this.hMsgs.setFast(false); this.hVars.setFast(true); this.generateKey(); // Process FormSet Constants for (Iterator i = constants.entrySet().iterator(); i.hasNext();) { Entry entry = (Entry) i.next(); String key = (String) entry.getKey(); String key2 = TOKEN_START + key + TOKEN_END; String replaceValue = (String) entry.getValue(); property = ValidatorUtils.replace(property, key2, replaceValue); processVars(key2, replaceValue); this.processMessageComponents(key2, replaceValue); } // Process Global Constants for (Iterator i = globalConstants.entrySet().iterator(); i.hasNext();) { Entry entry = (Entry) i.next(); String key = (String) entry.getKey(); String key2 = TOKEN_START + key + TOKEN_END; String replaceValue = (String) entry.getValue(); property = ValidatorUtils.replace(property, key2, replaceValue); processVars(key2, replaceValue); this.processMessageComponents(key2, replaceValue); } // Process Var Constant Replacement for (Iterator i = hVars.keySet().iterator(); i.hasNext();) { String key = (String) i.next(); String key2 = TOKEN_START + TOKEN_VAR + key + TOKEN_END; Var var = this.getVar(key); String replaceValue = var.getValue(); this.processMessageComponents(key2, replaceValue); } hMsgs.setFast(true); } /** * Replace the vars value with the key/value pairs passed in. */ private void processVars(String key, String replaceValue) { Iterator i = this.hVars.keySet().iterator(); while (i.hasNext()) { String varKey = (String) i.next(); Var var = this.getVar(varKey); var.setValue(ValidatorUtils.replace(var.getValue(), key, replaceValue)); } } /** * Replace the args key value with the key/value pairs passed in. */ private void processMessageComponents(String key, String replaceValue) { String varKey = TOKEN_START + TOKEN_VAR; // Process Messages if (key != null && !key.startsWith(varKey)) { for (Iterator i = hMsgs.values().iterator(); i.hasNext();) { Msg msg = (Msg) i.next(); msg.setKey(ValidatorUtils.replace(msg.getKey(), key, replaceValue)); } } this.processArg(key, replaceValue); } /** * Replace the arg Collection key value with the key/value * pairs passed in. */ private void processArg(String key, String replaceValue) { for (int i = 0; i < this.args.length; i++) { Map argMap = this.args[i]; if (argMap == null) { continue; } Iterator iter = argMap.values().iterator(); while (iter.hasNext()) { Arg arg = (Arg) iter.next(); if (arg != null) { arg.setKey( ValidatorUtils.replace(arg.getKey(), key, replaceValue)); } } } } /** * Checks if the validator is listed as a dependency. * @param validatorName Name of the validator to check. * @return Whether the field is dependant on a validator. */ public boolean isDependency(String validatorName) { return this.dependencyList.contains(validatorName); } /** * Gets an unmodifiable List of the dependencies in the same * order they were defined in parameter passed to the setDepends() method. * @return A list of the Field's dependancies. */ public List getDependencyList() { return Collections.unmodifiableList(this.dependencyList); } /** * Creates and returns a copy of this object. * @return A copy of the Field. */ public Object clone() { Field field = null; try { field = (Field) super.clone(); } catch(CloneNotSupportedException e) { throw new RuntimeException(e.toString()); } field.args = new Map[this.args.length]; for (int i = 0; i < this.args.length; i++) { if (this.args[i] == null) { continue; } Map argMap = new HashMap(this.args[i]); Iterator iter = argMap.entrySet().iterator(); while (iter.hasNext()) { Entry entry = (Entry) iter.next(); String validatorName = (String) entry.getKey(); Arg arg = (Arg) entry.getValue(); argMap.put(validatorName, arg.clone()); } field.args[i] = argMap; } field.hVars = ValidatorUtils.copyFastHashMap(hVars); field.hMsgs = ValidatorUtils.copyFastHashMap(hMsgs); return field; } /** * Returns a string representation of the object. * @return A string representation of the object. */ public String toString() { StringBuffer results = new StringBuffer(); results.append("\t\tkey = " + key + "\n"); results.append("\t\tproperty = " + property + "\n"); results.append("\t\tindexedProperty = " + indexedProperty + "\n"); results.append("\t\tindexedListProperty = " + indexedListProperty + "\n"); results.append("\t\tdepends = " + depends + "\n"); results.append("\t\tpage = " + page + "\n"); results.append("\t\tfieldOrder = " + fieldOrder + "\n"); if (hVars != null) { results.append("\t\tVars:\n"); for (Iterator i = hVars.keySet().iterator(); i.hasNext();) { Object key = i.next(); results.append("\t\t\t"); results.append(key); results.append("="); results.append(hVars.get(key)); results.append("\n"); } } return results.toString(); } /** * Returns an indexed property from the object we're validating. * * @param bean The bean to extract the indexed values from. * @throws ValidatorException If there's an error looking up the property * or, the property found is not indexed. */ Object[] getIndexedProperty(Object bean) throws ValidatorException { Object indexedProperty = null; try { indexedProperty = PropertyUtils.getProperty(bean, this.getIndexedListProperty()); } catch(IllegalAccessException e) { throw new ValidatorException(e.getMessage()); } catch(InvocationTargetException e) { throw new ValidatorException(e.getMessage()); } catch(NoSuchMethodException e) { throw new ValidatorException(e.getMessage()); } if (indexedProperty instanceof Collection) { return ((Collection) indexedProperty).toArray(); } else if (indexedProperty.getClass().isArray()) { return (Object[]) indexedProperty; } else { throw new ValidatorException(this.getKey() + " is not indexed"); } } /** * Returns the size of an indexed property from the object we're validating. * * @param bean The bean to extract the indexed values from. * @throws ValidatorException If there's an error looking up the property * or, the property found is not indexed. */ private int getIndexedPropertySize(Object bean) throws ValidatorException { Object indexedProperty = null; try { indexedProperty = PropertyUtils.getProperty(bean, this.getIndexedListProperty()); } catch(IllegalAccessException e) { throw new ValidatorException(e.getMessage()); } catch(InvocationTargetException e) { throw new ValidatorException(e.getMessage()); } catch(NoSuchMethodException e) { throw new ValidatorException(e.getMessage()); } if (indexedProperty == null) { return 0; } else if (indexedProperty instanceof Collection) { return ((Collection)indexedProperty).size(); } else if (indexedProperty.getClass().isArray()) { return ((Object[])indexedProperty).length; } else { throw new ValidatorException(this.getKey() + " is not indexed"); } } /** * Executes the given ValidatorAction and all ValidatorActions that it * depends on. * @return true if the validation succeeded. */ private boolean validateForRule( ValidatorAction va, ValidatorResults results, Map actions, Map params, int pos) throws ValidatorException { ValidatorResult result = results.getValidatorResult(this.getKey()); if (result != null && result.containsAction(va.getName())) { return result.isValid(va.getName()); } if (!this.runDependentValidators(va, results, actions, params, pos)) { return false; } return va.executeValidationMethod(this, params, results, pos); } /** * Calls all of the validators that this validator depends on. * TODO ValidatorAction should know how to run its own dependencies. * @param va Run dependent validators for this action. * @param results * @param actions * @param pos * @return true if all of the dependent validations passed. * @throws ValidatorException If there's an error running a validator */ private boolean runDependentValidators( ValidatorAction va, ValidatorResults results, Map actions, Map params, int pos) throws ValidatorException { List dependentValidators = va.getDependencyList(); if (dependentValidators.isEmpty()) { return true; } Iterator iter = dependentValidators.iterator(); while (iter.hasNext()) { String depend = (String) iter.next(); ValidatorAction action = (ValidatorAction) actions.get(depend); if (action == null) { this.handleMissingAction(depend); } if (!this.validateForRule(action, results, actions, params, pos)) { return false; } } return true; } /** * Run the configured validations on this field. Run all validations * in the depends clause over each item in turn, returning when the first * one fails. * @param params A Map of parameter class names to parameter values to pass * into validation methods. * @param actions A Map of validator names to ValidatorAction objects. * @return A ValidatorResults object containing validation messages for * this field. * @throws ValidatorException If an error occurs during validation. */ public ValidatorResults validate(Map params, Map actions) throws ValidatorException { if (this.getDepends() == null) { return new ValidatorResults(); } ValidatorResults allResults = new ValidatorResults(); Object bean = params.get(Validator.BEAN_PARAM); int numberOfFieldsToValidate = this.isIndexed() ? this.getIndexedPropertySize(bean) : 1; for (int fieldNumber = 0; fieldNumber < numberOfFieldsToValidate; fieldNumber++) { Iterator dependencies = this.dependencyList.iterator(); ValidatorResults results = new ValidatorResults(); while (dependencies.hasNext()) { String depend = (String) dependencies.next(); ValidatorAction action = (ValidatorAction) actions.get(depend); if (action == null) { this.handleMissingAction(depend); } boolean good = validateForRule(action, results, actions, params, fieldNumber); if (!good) { allResults.merge(results); return allResults; } } allResults.merge(results); } return allResults; } /** * Called when a validator name is used in a depends clause but there is * no know ValidatorAction configured for that name. * @param name The name of the validator in the depends list. * @throws ValidatorException */ private void handleMissingAction(String name) throws ValidatorException { throw new ValidatorException("No ValidatorAction named " + name + " found for field " + this.getProperty()); } /** * Returns a Map of String Msg names to Msg objects. * @since Validator 1.2.0 * @return A Map of the Field's messages. */ protected Map getMsgMap() { return hMsgs; } /** * Returns a Map of String Var names to Var objects. * @since Validator 1.2.0 * @return A Map of the Field's variables. */ protected Map getVarMap() { return hVars; } } commons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/Form.java100644 765 0 25400 11711227702 30676 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.commons.collections.FastHashMap;// DEPRECATED /** *

* * This contains a set of validation rules for a form/JavaBean. The information * is contained in a list of Field objects. Instances of this class * are configured with a <form> xml element.

* * The use of FastHashMap is deprecated and will be replaced in a future * release.

* * @version $Revision: 1227719 $ $Date: 2012-01-05 18:45:51 +0100 (Thu, 05 Jan 2012) $ */ public class Form implements Serializable { private static final long serialVersionUID = 6445211789563796371L; /** The name/key the set of validation rules is stored under. */ protected String name = null; /** * List of Fields. Used to maintain the order they were added * in although individual Fields can be retrieved using Map * of Fields. */ protected List lFields = new ArrayList(); /** * Map of Fields keyed on their property value. * * @deprecated Subclasses should use getFieldMap() instead. */ protected FastHashMap hFields = new FastHashMap(); /** * The name/key of the form which this form extends from. * * @since Validator 1.2.0 */ protected String inherit = null; /** * Whether or not the this Form was processed for replacing * variables in strings with their values. */ private boolean processed = false; /** * Gets the name/key of the set of validation rules. * * @return The name value */ public String getName() { return name; } /** * Sets the name/key of the set of validation rules. * * @param name The new name value */ public void setName(String name) { this.name = name; } /** * Add a Field to the Form. * * @param f The field */ public void addField(Field f) { this.lFields.add(f); this.hFields.put(f.getKey(), f); } /** * A List of Fields is returned as an unmodifiable * List. * * @return The fields value */ public List getFields() { return Collections.unmodifiableList(lFields); } /** * Returns the Field with the given name or null if this Form has no such * field. * * @param fieldName The field name * @return The field value * @since Validator 1.1 */ public Field getField(String fieldName) { return (Field) this.hFields.get(fieldName); } /** * Returns true if this Form contains a Field with the given name. * * @param fieldName The field name * @return True if this form contains the field by the given name * @since Validator 1.1 */ public boolean containsField(String fieldName) { return this.hFields.containsKey(fieldName); } /** * Merges the given form into this one. For any field in depends * not present in this form, include it. depends has precedence * in the way the fields are ordered. * * @param depends the form we want to merge * @since Validator 1.2.0 */ protected void merge(Form depends) { List templFields = new ArrayList(); Map temphFields = new FastHashMap(); Iterator dependsIt = depends.getFields().iterator(); while (dependsIt.hasNext()) { Field defaultField = (Field) dependsIt.next(); if (defaultField != null) { String fieldKey = defaultField.getKey(); if (!this.containsField(fieldKey)) { templFields.add(defaultField); temphFields.put(fieldKey, defaultField); } else { Field old = getField(fieldKey); hFields.remove(fieldKey); lFields.remove(old); templFields.add(old); temphFields.put(fieldKey, old); } } } lFields.addAll(0, templFields); hFields.putAll(temphFields); } /** * Processes all of the Form's Fields. * * @param globalConstants A map of global constants * @param constants Local constants * @param forms Map of forms * @since Validator 1.2.0 */ protected void process(Map globalConstants, Map constants, Map forms) { if (isProcessed()) { return; } int n = 0;//we want the fields from its parent first if (isExtending()) { Form parent = (Form) forms.get(inherit); if (parent != null) { if (!parent.isProcessed()) { //we want to go all the way up the tree parent.process(constants, globalConstants, forms); } for (Iterator i = parent.getFields().iterator(); i.hasNext(); ) { Field f = (Field) i.next(); //we want to be able to override any fields we like if (hFields.get(f.getKey()) == null) { lFields.add(n, f); hFields.put(f.getKey(), f); n++; } } } } hFields.setFast(true); //no need to reprocess parent's fields, we iterate from 'n' for (Iterator i = lFields.listIterator(n); i.hasNext(); ) { Field f = (Field) i.next(); f.process(globalConstants, constants); } processed = true; } /** * Returns a string representation of the object. * * @return string representation */ public String toString() { StringBuffer results = new StringBuffer(); results.append("Form: "); results.append(name); results.append("\n"); for (Iterator i = lFields.iterator(); i.hasNext(); ) { results.append("\tField: \n"); results.append(i.next()); results.append("\n"); } return results.toString(); } /** * Validate all Fields in this Form on the given page and below. * * @param params A Map of parameter class names to parameter * values to pass into validation methods. * @param actions A Map of validator names to ValidatorAction * objects. * @param page Fields on pages higher than this will not be * validated. * @return A ValidatorResults object containing all * validation messages. * @throws ValidatorException */ ValidatorResults validate(Map params, Map actions, int page) throws ValidatorException { return validate(params, actions, page, null); } /** * Validate all Fields in this Form on the given page and below. * * @param params A Map of parameter class names to parameter * values to pass into validation methods. * @param actions A Map of validator names to ValidatorAction * objects. * @param page Fields on pages higher than this will not be * validated. * @return A ValidatorResults object containing all * validation messages. * @throws ValidatorException * @since 1.2.0 */ ValidatorResults validate(Map params, Map actions, int page, String fieldName) throws ValidatorException { ValidatorResults results = new ValidatorResults(); params.put(Validator.VALIDATOR_RESULTS_PARAM, results); // Only validate a single field if specified if (fieldName != null) { Field field = (Field) this.hFields.get(fieldName); if (field == null) { throw new ValidatorException("Unknown field "+fieldName+" in form "+getName()); } params.put(Validator.FIELD_PARAM, field); if (field.getPage() <= page) { results.merge(field.validate(params, actions)); } } else { Iterator fields = this.lFields.iterator(); while (fields.hasNext()) { Field field = (Field) fields.next(); params.put(Validator.FIELD_PARAM, field); if (field.getPage() <= page) { results.merge(field.validate(params, actions)); } } } return results; } /** * Whether or not the this Form was processed for replacing * variables in strings with their values. * * @return The processed value * @since Validator 1.2.0 */ public boolean isProcessed() { return processed; } /** * Gets the name/key of the parent set of validation rules. * * @return The extends value * @since Validator 1.2.0 */ public String getExtends() { return inherit; } /** * Sets the name/key of the parent set of validation rules. * * @param inherit The new extends value * @since Validator 1.2.0 */ public void setExtends(String inherit) { this.inherit = inherit; } /** * Get extends flag. * * @return The extending value * @since Validator 1.2.0 */ public boolean isExtending() { return inherit != null; } /** * Returns a Map of String field keys to Field objects. * * @return The fieldMap value * @since Validator 1.2.0 */ protected Map getFieldMap() { return hFields; } } commons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/FormSet.java100644 765 0 25711 11711227702 31357 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator; import java.io.Serializable; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Holds a set of Forms stored associated with a Locale * based on the country, language, and variant specified. Instances of this * class are configured with a <formset> xml element. * * @version $Revision: 1227719 $ $Date: 2012-01-05 18:45:51 +0100 (Thu, 05 Jan 2012) $ */ public class FormSet implements Serializable { private static final long serialVersionUID = -8936513232763306055L; /** Logging */ private transient Log log = LogFactory.getLog(FormSet.class); /** * Whether or not the this FormSet was processed for replacing * variables in strings with their values. */ private boolean processed = false; /** Language component of Locale (required). */ private String language = null; /** Country component of Locale (optional). */ private String country = null; /** Variant component of Locale (optional). */ private String variant = null; /** * A Map of Forms using the name field of the * Form as the key. */ private Map forms = new HashMap(); /** * A Map of Constants using the name field of the * Constant as the key. */ private Map constants = new HashMap(); /** * This is the type of FormSets where no locale is specified. */ protected final static int GLOBAL_FORMSET = 1; /** * This is the type of FormSets where only language locale is * specified. */ protected final static int LANGUAGE_FORMSET = 2; /** * This is the type of FormSets where only language and country * locale are specified. */ protected final static int COUNTRY_FORMSET = 3; /** * This is the type of FormSets where full locale has been set. */ protected final static int VARIANT_FORMSET = 4; /** * Flag indicating if this formSet has been merged with its parent (higher * rank in Locale hierarchy). */ private boolean merged; /** * Has this formSet been merged? * * @return true if it has been merged * @since Validator 1.2.0 */ protected boolean isMerged() { return merged; } /** * Returns the type of FormSet:GLOBAL_FORMSET, * LANGUAGE_FORMSET,COUNTRY_FORMSET or VARIANT_FORMSET * . * * @return The type value * @since Validator 1.2.0 * @throws NullPointerException if there is inconsistency in the locale * definition (not sure about this) */ protected int getType() { if (getVariant() != null) { if (getLanguage() == null || getCountry() == null) { throw new NullPointerException( "When variant is specified, country and language must be specified."); } return VARIANT_FORMSET; } else if (getCountry() != null) { if (getLanguage() == null) { throw new NullPointerException( "When country is specified, language must be specified."); } return COUNTRY_FORMSET; } else if (getLanguage() != null) { return LANGUAGE_FORMSET; } else { return GLOBAL_FORMSET; } } /** * Merges the given FormSet into this one. If any of depends * s Forms are not in this FormSet then, include * them, else merge both Forms. Theoretically we should only * merge a "parent" formSet. * * @param depends FormSet to be merged * @since Validator 1.2.0 */ protected void merge(FormSet depends) { if (depends != null) { Map pForms = getForms(); Map dForms = depends.getForms(); for (Iterator it = dForms.entrySet().iterator(); it.hasNext(); ) { Entry entry = (Entry) it.next(); Object key = entry.getKey(); Form pForm = (Form) pForms.get(key); if (pForm != null) {//merge, but principal 'rules', don't overwrite // anything pForm.merge((Form) entry.getValue()); } else {//just add addForm((Form) entry.getValue()); } } } merged = true; } /** * Whether or not the this FormSet was processed for replacing * variables in strings with their values. * * @return The processed value */ public boolean isProcessed() { return processed; } /** * Gets the equivalent of the language component of Locale. * * @return The language value */ public String getLanguage() { return language; } /** * Sets the equivalent of the language component of Locale. * * @param language The new language value */ public void setLanguage(String language) { this.language = language; } /** * Gets the equivalent of the country component of Locale. * * @return The country value */ public String getCountry() { return country; } /** * Sets the equivalent of the country component of Locale. * * @param country The new country value */ public void setCountry(String country) { this.country = country; } /** * Gets the equivalent of the variant component of Locale. * * @return The variant value */ public String getVariant() { return variant; } /** * Sets the equivalent of the variant component of Locale. * * @param variant The new variant value */ public void setVariant(String variant) { this.variant = variant; } /** * Add a Constant to the locale level. * * @param name The constant name * @param value The constant value */ public void addConstant(String name, String value) { if (constants.containsKey(name)) { getLog().error("Constant '" + name + "' already exists in FormSet[" + this.displayKey() + "] - ignoring."); } else { constants.put(name, value); } } /** * Add a Form to the FormSet. * * @param f The form */ public void addForm(Form f) { String formName = f.getName(); if (forms.containsKey(formName)) { getLog().error("Form '" + formName + "' already exists in FormSet[" + this.displayKey() + "] - ignoring."); } else { forms.put(f.getName(), f); } } /** * Retrieve a Form based on the form name. * * @param formName The form name * @return The form */ public Form getForm(String formName) { return (Form) this.forms.get(formName); } /** * A Map of Forms is returned as an unmodifiable * Map with the key based on the form name. * * @return The forms map */ public Map getForms() { return Collections.unmodifiableMap(forms); } /** * Processes all of the Forms. * * @param globalConstants Global constants */ synchronized void process(Map globalConstants) { for (Iterator i = forms.values().iterator(); i.hasNext(); ) { Form f = (Form) i.next(); f.process(globalConstants, constants, forms); } processed = true; } /** * Returns a string representation of the object's key. * * @return A string representation of the key */ public String displayKey() { StringBuffer results = new StringBuffer(); if (language != null && language.length() > 0) { results.append("language="); results.append(language); } if (country != null && country.length() > 0) { if (results.length() > 0) { results.append(", "); } results.append("country="); results.append(country); } if (variant != null && variant.length() > 0) { if (results.length() > 0) { results.append(", "); } results.append("variant="); results.append(variant ); } if (results.length() == 0) { results.append("default"); } return results.toString(); } /** * Returns a string representation of the object. * * @return A string representation */ public String toString() { StringBuffer results = new StringBuffer(); results.append("FormSet: language="); results.append(language); results.append(" country="); results.append(country); results.append(" variant="); results.append(variant); results.append("\n"); for (Iterator i = getForms().values().iterator(); i.hasNext(); ) { results.append(" "); results.append(i.next()); results.append("\n"); } return results.toString(); } /** * Accessor method for Log instance. * * The Log instance variable is transient and * accessing it through this method ensures it * is re-initialized when this instance is * de-serialized. * * @return The Log instance. */ private Log getLog() { if (log == null) { log = LogFactory.getLog(FormSet.class); } return log; } } commons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/FormSetFactory.java100644 765 0 7560 11711227702 32671 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator; import org.xml.sax.Attributes; import org.apache.commons.digester.AbstractObjectCreationFactory; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Factory class used by Digester to create FormSet's. * * @version $Revision: 493905 $ $Date: 2007-01-08 03:11:38 +0100 (Mon, 08 Jan 2007) $ * @since Validator 1.2 */ public class FormSetFactory extends AbstractObjectCreationFactory { /** Logging */ private transient Log log = LogFactory.getLog(FormSetFactory.class); /** *

Create or retrieve a FormSet for the specified * attributes.

* * @param attributes The sax attributes for the formset element. * @return The FormSet for a locale. * @throws Exception If an error occurs creating the FormSet. */ public Object createObject(Attributes attributes) throws Exception { ValidatorResources resources = (ValidatorResources)digester.peek(0); String language = attributes.getValue("language"); String country = attributes.getValue("country"); String variant = attributes.getValue("variant"); return createFormSet(resources, language, country, variant); } /** *

Create or retrieve a FormSet based on the language, country * and variant.

* * @param resources The validator resources. * @param language The locale's language. * @param country The locale's country. * @param variant The locale's language variant. * @return The FormSet for a locale. * @since Validator 1.2 */ private FormSet createFormSet(ValidatorResources resources, String language, String country, String variant) throws Exception { // Retrieve existing FormSet for the language/country/variant FormSet formSet = resources.getFormSet(language, country, variant); if (formSet != null) { if (getLog().isDebugEnabled()) { getLog().debug("FormSet[" + formSet.displayKey() + "] found - merging."); } return formSet; } // Create a new FormSet for the language/country/variant formSet = new FormSet(); formSet.setLanguage(language); formSet.setCountry(country); formSet.setVariant(variant); // Add the FormSet to the validator resources resources.addFormSet(formSet); if (getLog().isDebugEnabled()) { getLog().debug("FormSet[" + formSet.displayKey() + "] created."); } return formSet; } /** * Accessor method for Log instance. * * The Log instance variable is transient and * accessing it through this method ensures it * is re-initialized when this instance is * de-serialized. * * @return The Log instance. */ private Log getLog() { if (log == null) { log = LogFactory.getLog(FormSetFactory.class); } return log; } } commons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/GenericTypeValidator.java100644 765 0 37307 11711227702 34070 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator; import java.io.Serializable; import java.util.Date; import java.util.Locale; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.text.NumberFormat; import java.text.ParseException; import java.text.ParsePosition; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * This class contains basic methods for performing validations that return the * correctly typed class based on the validation performed. * * @version $Revision: 1227719 $ $Date: 2012-01-05 18:45:51 +0100 (Thu, 05 Jan 2012) $ */ public class GenericTypeValidator implements Serializable { private static final long serialVersionUID = 5487162314134261703L; /** * Checks if the value can safely be converted to a byte primitive. * *@param value The value validation is being performed on. *@return the converted Byte value. */ public static Byte formatByte(String value) { if (value == null) { return null; } try { return new Byte(value); } catch (NumberFormatException e) { return null; } } /** * Checks if the value can safely be converted to a byte primitive. * *@param value The value validation is being performed on. *@param locale The locale to use to parse the number (system default if * null) *@return the converted Byte value. */ public static Byte formatByte(String value, Locale locale) { Byte result = null; if (value != null) { NumberFormat formatter = null; if (locale != null) { formatter = NumberFormat.getNumberInstance(locale); } else { formatter = NumberFormat.getNumberInstance(Locale.getDefault()); } formatter.setParseIntegerOnly(true); ParsePosition pos = new ParsePosition(0); Number num = formatter.parse(value, pos); // If there was no error and we used the whole string if (pos.getErrorIndex() == -1 && pos.getIndex() == value.length()) { if (num.doubleValue() >= Byte.MIN_VALUE && num.doubleValue() <= Byte.MAX_VALUE) { result = new Byte(num.byteValue()); } } } return result; } /** * Checks if the value can safely be converted to a short primitive. * *@param value The value validation is being performed on. *@return the converted Short value. */ public static Short formatShort(String value) { if (value == null) { return null; } try { return new Short(value); } catch (NumberFormatException e) { return null; } } /** * Checks if the value can safely be converted to a short primitive. * *@param value The value validation is being performed on. *@param locale The locale to use to parse the number (system default if * null)vv *@return the converted Short value. */ public static Short formatShort(String value, Locale locale) { Short result = null; if (value != null) { NumberFormat formatter = null; if (locale != null) { formatter = NumberFormat.getNumberInstance(locale); } else { formatter = NumberFormat.getNumberInstance(Locale.getDefault()); } formatter.setParseIntegerOnly(true); ParsePosition pos = new ParsePosition(0); Number num = formatter.parse(value, pos); // If there was no error and we used the whole string if (pos.getErrorIndex() == -1 && pos.getIndex() == value.length()) { if (num.doubleValue() >= Short.MIN_VALUE && num.doubleValue() <= Short.MAX_VALUE) { result = new Short(num.shortValue()); } } } return result; } /** * Checks if the value can safely be converted to a int primitive. * *@param value The value validation is being performed on. *@return the converted Integer value. */ public static Integer formatInt(String value) { if (value == null) { return null; } try { return new Integer(value); } catch (NumberFormatException e) { return null; } } /** * Checks if the value can safely be converted to an int primitive. * *@param value The value validation is being performed on. *@param locale The locale to use to parse the number (system default if * null) *@return the converted Integer value. */ public static Integer formatInt(String value, Locale locale) { Integer result = null; if (value != null) { NumberFormat formatter = null; if (locale != null) { formatter = NumberFormat.getNumberInstance(locale); } else { formatter = NumberFormat.getNumberInstance(Locale.getDefault()); } formatter.setParseIntegerOnly(true); ParsePosition pos = new ParsePosition(0); Number num = formatter.parse(value, pos); // If there was no error and we used the whole string if (pos.getErrorIndex() == -1 && pos.getIndex() == value.length()) { if (num.doubleValue() >= Integer.MIN_VALUE && num.doubleValue() <= Integer.MAX_VALUE) { result = new Integer(num.intValue()); } } } return result; } /** * Checks if the value can safely be converted to a long primitive. * *@param value The value validation is being performed on. *@return the converted Long value. */ public static Long formatLong(String value) { if (value == null) { return null; } try { return new Long(value); } catch (NumberFormatException e) { return null; } } /** * Checks if the value can safely be converted to a long primitive. * *@param value The value validation is being performed on. *@param locale The locale to use to parse the number (system default if * null) *@return the converted Long value. */ public static Long formatLong(String value, Locale locale) { Long result = null; if (value != null) { NumberFormat formatter = null; if (locale != null) { formatter = NumberFormat.getNumberInstance(locale); } else { formatter = NumberFormat.getNumberInstance(Locale.getDefault()); } formatter.setParseIntegerOnly(true); ParsePosition pos = new ParsePosition(0); Number num = formatter.parse(value, pos); // If there was no error and we used the whole string if (pos.getErrorIndex() == -1 && pos.getIndex() == value.length()) { if (num.doubleValue() >= Long.MIN_VALUE && num.doubleValue() <= Long.MAX_VALUE) { result = new Long(num.longValue()); } } } return result; } /** * Checks if the value can safely be converted to a float primitive. * *@param value The value validation is being performed on. *@return the converted Float value. */ public static Float formatFloat(String value) { if (value == null) { return null; } try { return new Float(value); } catch (NumberFormatException e) { return null; } } /** * Checks if the value can safely be converted to a float primitive. * *@param value The value validation is being performed on. *@param locale The locale to use to parse the number (system default if * null) *@return the converted Float value. */ public static Float formatFloat(String value, Locale locale) { Float result = null; if (value != null) { NumberFormat formatter = null; if (locale != null) { formatter = NumberFormat.getInstance(locale); } else { formatter = NumberFormat.getInstance(Locale.getDefault()); } ParsePosition pos = new ParsePosition(0); Number num = formatter.parse(value, pos); // If there was no error and we used the whole string if (pos.getErrorIndex() == -1 && pos.getIndex() == value.length()) { if (num.doubleValue() >= (Float.MAX_VALUE * -1) && num.doubleValue() <= Float.MAX_VALUE) { result = new Float(num.floatValue()); } } } return result; } /** * Checks if the value can safely be converted to a double primitive. * *@param value The value validation is being performed on. *@return the converted Double value. */ public static Double formatDouble(String value) { if (value == null) { return null; } try { return new Double(value); } catch (NumberFormatException e) { return null; } } /** * Checks if the value can safely be converted to a double primitive. * *@param value The value validation is being performed on. *@param locale The locale to use to parse the number (system default if * null) *@return the converted Double value. */ public static Double formatDouble(String value, Locale locale) { Double result = null; if (value != null) { NumberFormat formatter = null; if (locale != null) { formatter = NumberFormat.getInstance(locale); } else { formatter = NumberFormat.getInstance(Locale.getDefault()); } ParsePosition pos = new ParsePosition(0); Number num = formatter.parse(value, pos); // If there was no error and we used the whole string if (pos.getErrorIndex() == -1 && pos.getIndex() == value.length()) { if (num.doubleValue() >= (Double.MAX_VALUE * -1) && num.doubleValue() <= Double.MAX_VALUE) { result = new Double(num.doubleValue()); } } } return result; } /** *

* * Checks if the field is a valid date. The Locale is used * with java.text.DateFormat. The setLenient method is set to * false for all.

* *@param value The value validation is being performed on. *@param locale The Locale to use to parse the date (system default if * null) *@return the converted Date value. */ public static Date formatDate(String value, Locale locale) { Date date = null; if (value == null) { return null; } try { // Get the formatters to check against DateFormat formatterShort = null; DateFormat formatterDefault = null; if (locale != null) { formatterShort = DateFormat.getDateInstance(DateFormat.SHORT, locale); formatterDefault = DateFormat.getDateInstance(DateFormat.DEFAULT, locale); } else { formatterShort = DateFormat.getDateInstance( DateFormat.SHORT, Locale.getDefault()); formatterDefault = DateFormat.getDateInstance( DateFormat.DEFAULT, Locale.getDefault()); } // Turn off lenient parsing formatterShort.setLenient(false); formatterDefault.setLenient(false); // Firstly, try with the short form try { date = formatterShort.parse(value); } catch (ParseException e) { // Fall back on the default one date = formatterDefault.parse(value); } } catch (ParseException e) { // Bad date, so log and return null Log log = LogFactory.getLog(GenericTypeValidator.class); if (log.isDebugEnabled()) { log.debug("Date parse failed value=[" + value + "], " + "locale=[" + locale + "] " + e); } } return date; } /** *

* Checks if the field is a valid date. The pattern is used with java.text.SimpleDateFormat * . If strict is true, then the length will be checked so '2/12/1999' will * not pass validation with the format 'MM/dd/yyyy' because the month isn't * two digits. The setLenient method is set to false for all. *

* *@param value The value validation is being performed on. *@param datePattern The pattern passed to SimpleDateFormat. *@param strict Whether or not to have an exact match of the * datePattern. *@return the converted Date value. */ public static Date formatDate(String value, String datePattern, boolean strict) { Date date = null; if (value == null || datePattern == null || datePattern.length() == 0) { return null; } try { SimpleDateFormat formatter = new SimpleDateFormat(datePattern); formatter.setLenient(false); date = formatter.parse(value); if (strict) { if (datePattern.length() != value.length()) { date = null; } } } catch (ParseException e) { // Bad date so return null Log log = LogFactory.getLog(GenericTypeValidator.class); if (log.isDebugEnabled()) { log.debug("Date parse failed value=[" + value + "], " + "pattern=[" + datePattern + "], " + "strict=[" + strict + "] " + e); } } return date; } /** *

* Checks if the field is a valid credit card number.

* * Reference Sean M. Burke's * script .

* *@param value The value validation is being performed on. *@return the converted Credit Card number. */ public static Long formatCreditCard(String value) { return GenericValidator.isCreditCard(value) ? new Long(value) : null; } } commons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/GenericValidator.java100644 765 0 36707 11711227702 33231 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator; import java.io.Serializable; import java.util.Locale; import java.util.regex.Pattern; import org.apache.commons.validator.routines.UrlValidator; import org.apache.commons.validator.routines.CreditCardValidator; import org.apache.commons.validator.routines.DateValidator; import org.apache.commons.validator.routines.EmailValidator; /** * This class contains basic methods for performing validations. * * @version $Revision: 1227719 $ $Date: 2012-01-05 18:45:51 +0100 (Thu, 05 Jan 2012) $ */ public class GenericValidator implements Serializable { private static final long serialVersionUID = -7212095066891517618L; /** * UrlValidator used in wrapper method. */ private static final UrlValidator URL_VALIDATOR = new UrlValidator(); /** * CreditCardValidator used in wrapper method. */ private static final CreditCardValidator CREDIT_CARD_VALIDATOR = new CreditCardValidator(); /** *

Checks if the field isn't null and length of the field is greater * than zero not including whitespace.

* * @param value The value validation is being performed on. * @return true if blank or null. */ public static boolean isBlankOrNull(String value) { return ((value == null) || (value.trim().length() == 0)); } /** *

Checks if the value matches the regular expression.

* * @param value The value validation is being performed on. * @param regexp The regular expression. * @return true if matches the regular expression. */ public static boolean matchRegexp(String value, String regexp) { if (regexp == null || regexp.length() <= 0) { return false; } return Pattern.matches(regexp, value); } /** *

Checks if the value can safely be converted to a byte primitive.

* * @param value The value validation is being performed on. * @return true if the value can be converted to a Byte. */ public static boolean isByte(String value) { return (GenericTypeValidator.formatByte(value) != null); } /** *

Checks if the value can safely be converted to a short primitive.

* * @param value The value validation is being performed on. * @return true if the value can be converted to a Short. */ public static boolean isShort(String value) { return (GenericTypeValidator.formatShort(value) != null); } /** *

Checks if the value can safely be converted to a int primitive.

* * @param value The value validation is being performed on. * @return true if the value can be converted to an Integer. */ public static boolean isInt(String value) { return (GenericTypeValidator.formatInt(value) != null); } /** *

Checks if the value can safely be converted to a long primitive.

* * @param value The value validation is being performed on. * @return true if the value can be converted to a Long. */ public static boolean isLong(String value) { return (GenericTypeValidator.formatLong(value) != null); } /** *

Checks if the value can safely be converted to a float primitive.

* * @param value The value validation is being performed on. * @return true if the value can be converted to a Float. */ public static boolean isFloat(String value) { return (GenericTypeValidator.formatFloat(value) != null); } /** *

Checks if the value can safely be converted to a double primitive.

* * @param value The value validation is being performed on. * @return true if the value can be converted to a Double. */ public static boolean isDouble(String value) { return (GenericTypeValidator.formatDouble(value) != null); } /** *

Checks if the field is a valid date. The Locale is * used with java.text.DateFormat. The setLenient method * is set to false for all.

* * @param value The value validation is being performed on. * @param locale The locale to use for the date format, defaults to the * system default if null. * @return true if the value can be converted to a Date. */ public static boolean isDate(String value, Locale locale) { return DateValidator.getInstance().isValid(value, locale); } /** *

Checks if the field is a valid date. The pattern is used with * java.text.SimpleDateFormat. If strict is true, then the * length will be checked so '2/12/1999' will not pass validation with * the format 'MM/dd/yyyy' because the month isn't two digits. * The setLenient method is set to false for all.

* * @param value The value validation is being performed on. * @param datePattern The pattern passed to SimpleDateFormat. * @param strict Whether or not to have an exact match of the datePattern. * @return true if the value can be converted to a Date. */ public static boolean isDate(String value, String datePattern, boolean strict) { // TODO not yet supported in routines version return org.apache.commons.validator.DateValidator.getInstance().isValid(value, datePattern, strict); } /** *

Checks if a value is within a range (min & max specified * in the vars attribute).

* * @param value The value validation is being performed on. * @param min The minimum value of the range. * @param max The maximum value of the range. * @return true if the value is in the specified range. */ public static boolean isInRange(byte value, byte min, byte max) { return ((value >= min) && (value <= max)); } /** *

Checks if a value is within a range (min & max specified * in the vars attribute).

* * @param value The value validation is being performed on. * @param min The minimum value of the range. * @param max The maximum value of the range. * @return true if the value is in the specified range. */ public static boolean isInRange(int value, int min, int max) { return ((value >= min) && (value <= max)); } /** *

Checks if a value is within a range (min & max specified * in the vars attribute).

* * @param value The value validation is being performed on. * @param min The minimum value of the range. * @param max The maximum value of the range. * @return true if the value is in the specified range. */ public static boolean isInRange(float value, float min, float max) { return ((value >= min) && (value <= max)); } /** *

Checks if a value is within a range (min & max specified * in the vars attribute).

* * @param value The value validation is being performed on. * @param min The minimum value of the range. * @param max The maximum value of the range. * @return true if the value is in the specified range. */ public static boolean isInRange(short value, short min, short max) { return ((value >= min) && (value <= max)); } /** *

Checks if a value is within a range (min & max specified * in the vars attribute).

* * @param value The value validation is being performed on. * @param min The minimum value of the range. * @param max The maximum value of the range. * @return true if the value is in the specified range. */ public static boolean isInRange(long value, long min, long max) { return ((value >= min) && (value <= max)); } /** *

Checks if a value is within a range (min & max specified * in the vars attribute).

* * @param value The value validation is being performed on. * @param min The minimum value of the range. * @param max The maximum value of the range. * @return true if the value is in the specified range. */ public static boolean isInRange(double value, double min, double max) { return ((value >= min) && (value <= max)); } /** * Checks if the field is a valid credit card number. * @param value The value validation is being performed on. * @return true if the value is valid Credit Card Number. */ public static boolean isCreditCard(String value) { return CREDIT_CARD_VALIDATOR.isValid(value); } /** *

Checks if a field has a valid e-mail address.

* * @param value The value validation is being performed on. * @return true if the value is valid Email Address. */ public static boolean isEmail(String value) { return EmailValidator.getInstance().isValid(value); } /** *

Checks if a field is a valid url address.

* If you need to modify what is considered valid then * consider using the UrlValidator directly. * * @param value The value validation is being performed on. * @return true if the value is valid Url. */ public static boolean isUrl(String value) { return URL_VALIDATOR.isValid(value); } /** *

Checks if the value's length is less than or equal to the max.

* * @param value The value validation is being performed on. * @param max The maximum length. * @return true if the value's length is less than the specified maximum. */ public static boolean maxLength(String value, int max) { return (value.length() <= max); } /** *

Checks if the value's adjusted length is less than or equal to the max.

* * @param value The value validation is being performed on. * @param max The maximum length. * @param lineEndLength The length to use for line endings. * @return true if the value's length is less than the specified maximum. */ public static boolean maxLength(String value, int max, int lineEndLength) { int adjustAmount = adjustForLineEnding(value, lineEndLength); return ((value.length() + adjustAmount) <= max); } /** *

Checks if the value's length is greater than or equal to the min.

* * @param value The value validation is being performed on. * @param min The minimum length. * @return true if the value's length is more than the specified minimum. */ public static boolean minLength(String value, int min) { return (value.length() >= min); } /** *

Checks if the value's adjusted length is greater than or equal to the min.

* * @param value The value validation is being performed on. * @param min The minimum length. * @param lineEndLength The length to use for line endings. * @return true if the value's length is more than the specified minimum. */ public static boolean minLength(String value, int min, int lineEndLength) { int adjustAmount = adjustForLineEnding(value, lineEndLength); return ((value.length() + adjustAmount) >= min); } /** * Calculate an adjustment amount for line endings. * * See Bug 37962 for the rational behind this. * * @param value The value validation is being performed on. * @param lineEndLength The length to use for line endings. * @return the adjustment amount. */ private static int adjustForLineEnding(String value, int lineEndLength) { int nCount = 0; int rCount = 0; for (int i = 0; i < value.length(); i++) { if (value.charAt(i) == '\n') { nCount++; } if (value.charAt(i) == '\r') { rCount++; } } return ((nCount * lineEndLength) - (rCount + nCount)); } // See http://issues.apache.org/bugzilla/show_bug.cgi?id=29015 WRT the "value" methods /** *

Checks if the value is greater than or equal to the min.

* * @param value The value validation is being performed on. * @param min The minimum numeric value. * @return true if the value is >= the specified minimum. */ public static boolean minValue(int value, int min) { return (value >= min); } /** *

Checks if the value is greater than or equal to the min.

* * @param value The value validation is being performed on. * @param min The minimum numeric value. * @return true if the value is >= the specified minimum. */ public static boolean minValue(long value, long min) { return (value >= min); } /** *

Checks if the value is greater than or equal to the min.

* * @param value The value validation is being performed on. * @param min The minimum numeric value. * @return true if the value is >= the specified minimum. */ public static boolean minValue(double value, double min) { return (value >= min); } /** *

Checks if the value is greater than or equal to the min.

* * @param value The value validation is being performed on. * @param min The minimum numeric value. * @return true if the value is >= the specified minimum. */ public static boolean minValue(float value, float min) { return (value >= min); } /** *

Checks if the value is less than or equal to the max.

* * @param value The value validation is being performed on. * @param max The maximum numeric value. * @return true if the value is <= the specified maximum. */ public static boolean maxValue(int value, int max) { return (value <= max); } /** *

Checks if the value is less than or equal to the max.

* * @param value The value validation is being performed on. * @param max The maximum numeric value. * @return true if the value is <= the specified maximum. */ public static boolean maxValue(long value, long max) { return (value <= max); } /** *

Checks if the value is less than or equal to the max.

* * @param value The value validation is being performed on. * @param max The maximum numeric value. * @return true if the value is <= the specified maximum. */ public static boolean maxValue(double value, double max) { return (value <= max); } /** *

Checks if the value is less than or equal to the max.

* * @param value The value validation is being performed on. * @param max The maximum numeric value. * @return true if the value is <= the specified maximum. */ public static boolean maxValue(float value, float max) { return (value <= max); } } commons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/ISBNValidator.java100644 765 0 4042 11711227702 32353 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator; /** * A class for validating 10 digit ISBN codes. * Based on this * * algorithm * * NOTE: This has been replaced by the new * {@link org.apache.commons.validator.routines.ISBNValidator}. * * @version $Revision: 591503 $ $Date: 2007-11-03 00:00:06 +0100 (Sat, 03 Nov 2007) $ * @since Validator 1.2.0 * @deprecated Use the new ISBNValidator in the routines package */ public class ISBNValidator { /** * Default Constructor. */ public ISBNValidator() { super(); } /** * If the ISBN is formatted with space or dash separators its format is * validated. Then the digits in the number are weighted, summed, and * divided by 11 according to the ISBN algorithm. If the result is zero, * the ISBN is valid. This method accepts formatted or raw ISBN codes. * * @param isbn Candidate ISBN number to be validated. null is * considered invalid. * @return true if the string is a valid ISBN code. */ public boolean isValid(String isbn) { return org.apache.commons.validator.routines.ISBNValidator.getInstance().isValidISBN10(isbn); } } commons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/Msg.java100644 765 0 10415 11711227702 30521 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator; import java.io.Serializable; /** * An alternative message can be associated with a Field * and a pluggable validator instead of using the default message * stored in the ValidatorAction (aka pluggable validator). * Instances of this class are configured with a <msg> xml element. * * @version $Revision: 1227719 $ $Date: 2012-01-05 18:45:51 +0100 (Thu, 05 Jan 2012) $ */ public class Msg implements Cloneable, Serializable { private static final long serialVersionUID = 5690015734364127124L; /** * The resource bundle name that this Msg's key should be * resolved in (optional). * @since Validator 1.1 */ protected String bundle = null; /** * The key or value of the argument. */ protected String key = null; /** * The name dependency that this argument goes with (optional). */ protected String name = null; /** * Whether or not the key is a message resource (optional). Defaults to * true. If it is 'true', the value will try to be resolved as a message * resource. * @since Validator 1.1.4 */ protected boolean resource = true; /** * Returns the resource bundle name. * @return The bundle name. * @since Validator 1.1 */ public String getBundle() { return this.bundle; } /** * Sets the resource bundle name. * @param bundle The new bundle name. * @since Validator 1.1 */ public void setBundle(String bundle) { this.bundle = bundle; } /** * Gets the name of the dependency. * @return The dependency name. */ public String getName() { return name; } /** * Sets the name of the dependency. * @param name The dependency name. */ public void setName(String name) { this.name = name; } /** * Gets the key/value. * @return The message key/value. */ public String getKey() { return key; } /** * Sets the key/value. * @param key The message key/value. */ public void setKey(String key) { this.key = key; } /** * Tests whether or not the key is a resource key or literal value. * @return true if key is a resource key. * @since Validator 1.1.4 */ public boolean isResource() { return this.resource; } /** * Sets whether or not the key is a resource. * @param resource If true indicates the key is a resource. * @since Validator 1.1.4 */ public void setResource(boolean resource) { this.resource = resource; } /** * Creates and returns a copy of this object. * @return A copy of the Msg. */ public Object clone() { try { return super.clone(); } catch(CloneNotSupportedException e) { throw new RuntimeException(e.toString()); } } /** * Returns a string representation of the object. * @return Msg String representation. */ public String toString() { StringBuffer results = new StringBuffer(); results.append("Msg: name="); results.append(name); results.append(" key="); results.append(key); results.append(" resource="); results.append(resource); results.append(" bundle="); results.append(bundle); results.append("\n"); return results.toString(); } }commons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/UrlValidator.java100644 765 0 36176 11711227702 32417 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator; import java.io.Serializable; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.validator.routines.InetAddressValidator; import org.apache.commons.validator.util.Flags; /** *

Validates URLs.

* Behavour of validation is modified by passing in options: *
  • ALLOW_2_SLASHES - [FALSE] Allows double '/' characters in the path * component.
  • *
  • NO_FRAGMENT- [FALSE] By default fragments are allowed, if this option is * included then fragments are flagged as illegal.
  • *
  • ALLOW_ALL_SCHEMES - [FALSE] By default only http, https, and ftp are * considered valid schemes. Enabling this option will let any scheme pass validation.
  • * *

    Originally based in on php script by Debbie Dyer, validation.php v1.2b, Date: 03/07/02, * http://javascript.internet.com. However, this validation now bears little resemblance * to the php original.

    *
     *   Example of usage:
     *   Construct a UrlValidator with valid schemes of "http", and "https".
     *
     *    String[] schemes = {"http","https"}.
     *    UrlValidator urlValidator = new UrlValidator(schemes);
     *    if (urlValidator.isValid("ftp://foo.bar.com/")) {
     *       System.out.println("url is valid");
     *    } else {
     *       System.out.println("url is invalid");
     *    }
     *
     *    prints "url is invalid"
     *   If instead the default constructor is used.
     *
     *    UrlValidator urlValidator = new UrlValidator();
     *    if (urlValidator.isValid("ftp://foo.bar.com/")) {
     *       System.out.println("url is valid");
     *    } else {
     *       System.out.println("url is invalid");
     *    }
     *
     *   prints out "url is valid"
     *  
    * * @see * * Uniform Resource Identifiers (URI): Generic Syntax * * * @version $Revision: 1227719 $ $Date: 2012-01-05 18:45:51 +0100 (Thu, 05 Jan 2012) $ * @since Validator 1.1 * @deprecated Use the new UrlValidator in the routines package. This class * will be removed in a future release. */ public class UrlValidator implements Serializable { private static final long serialVersionUID = 24137157400029593L; /** * Allows all validly formatted schemes to pass validation instead of * supplying a set of valid schemes. */ public static final int ALLOW_ALL_SCHEMES = 1 << 0; /** * Allow two slashes in the path component of the URL. */ public static final int ALLOW_2_SLASHES = 1 << 1; /** * Enabling this options disallows any URL fragments. */ public static final int NO_FRAGMENTS = 1 << 2; private static final String ALPHA_CHARS = "a-zA-Z"; private static final String ALPHA_NUMERIC_CHARS = ALPHA_CHARS + "\\d"; private static final String SPECIAL_CHARS = ";/@&=,.?:+$"; private static final String VALID_CHARS = "[^\\s" + SPECIAL_CHARS + "]"; // Drop numeric, and "+-." for now private static final String AUTHORITY_CHARS_REGEX = "\\p{Alnum}\\-\\."; private static final String ATOM = VALID_CHARS + '+'; /** * This expression derived/taken from the BNF for URI (RFC2396). */ private static final String URL_REGEX = "^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?"; // 12 3 4 5 6 7 8 9 private static final Pattern URL_PATTERN = Pattern.compile(URL_REGEX); /** * Schema/Protocol (ie. http:, ftp:, file:, etc). */ private static final int PARSE_URL_SCHEME = 2; /** * Includes hostname/ip and port number. */ private static final int PARSE_URL_AUTHORITY = 4; private static final int PARSE_URL_PATH = 5; private static final int PARSE_URL_QUERY = 7; private static final int PARSE_URL_FRAGMENT = 9; /** * Protocol (ie. http:, ftp:,https:). */ private static final Pattern SCHEME_PATTERN = Pattern.compile("^\\p{Alpha}[\\p{Alnum}\\+\\-\\.]*"); private static final String AUTHORITY_REGEX = "^([" + AUTHORITY_CHARS_REGEX + "]*)(:\\d*)?(.*)?"; // 1 2 3 4 private static final Pattern AUTHORITY_PATTERN = Pattern.compile(AUTHORITY_REGEX); private static final int PARSE_AUTHORITY_HOST_IP = 1; private static final int PARSE_AUTHORITY_PORT = 2; /** * Should always be empty. */ private static final int PARSE_AUTHORITY_EXTRA = 3; private static final Pattern PATH_PATTERN = Pattern.compile("^(/[-\\w:@&?=+,.!/~*'%$_;]*)?$"); private static final Pattern QUERY_PATTERN = Pattern.compile("^(.*)$"); private static final Pattern LEGAL_ASCII_PATTERN = Pattern.compile("^\\p{ASCII}+$"); private static final Pattern DOMAIN_PATTERN = Pattern.compile("^" + ATOM + "(\\." + ATOM + ")*$"); private static final Pattern PORT_PATTERN = Pattern.compile("^:(\\d{1,5})$"); private static final Pattern ATOM_PATTERN = Pattern.compile("^(" + ATOM + ").*?$"); private static final Pattern ALPHA_PATTERN = Pattern.compile("^[" + ALPHA_CHARS + "]"); /** * Holds the set of current validation options. */ private Flags options = null; /** * The set of schemes that are allowed to be in a URL. */ private Set allowedSchemes = new HashSet(); /** * If no schemes are provided, default to this set. */ protected String[] defaultSchemes = {"http", "https", "ftp"}; /** * Create a UrlValidator with default properties. */ public UrlValidator() { this(null); } /** * Behavior of validation is modified by passing in several strings options: * @param schemes Pass in one or more url schemes to consider valid, passing in * a null will default to "http,https,ftp" being valid. * If a non-null schemes is specified then all valid schemes must * be specified. Setting the ALLOW_ALL_SCHEMES option will * ignore the contents of schemes. */ public UrlValidator(String[] schemes) { this(schemes, 0); } /** * Initialize a UrlValidator with the given validation options. * @param options The options should be set using the public constants declared in * this class. To set multiple options you simply add them together. For example, * ALLOW_2_SLASHES + NO_FRAGMENTS enables both of those options. */ public UrlValidator(int options) { this(null, options); } /** * Behavour of validation is modified by passing in options: * @param schemes The set of valid schemes. * @param options The options should be set using the public constants declared in * this class. To set multiple options you simply add them together. For example, * ALLOW_2_SLASHES + NO_FRAGMENTS enables both of those options. */ public UrlValidator(String[] schemes, int options) { this.options = new Flags(options); if (this.options.isOn(ALLOW_ALL_SCHEMES)) { return; } if (schemes == null) { schemes = this.defaultSchemes; } this.allowedSchemes.addAll(Arrays.asList(schemes)); } /** *

    Checks if a field has a valid url address.

    * * @param value The value validation is being performed on. A null * value is considered invalid. * @return true if the url is valid. */ public boolean isValid(String value) { if (value == null) { return false; } if (!LEGAL_ASCII_PATTERN.matcher(value).matches()) { return false; } // Check the whole url address structure Matcher urlMatcher = URL_PATTERN.matcher(value); if (!urlMatcher.matches()) { return false; } if (!isValidScheme(urlMatcher.group(PARSE_URL_SCHEME))) { return false; } if (!isValidAuthority(urlMatcher.group(PARSE_URL_AUTHORITY))) { return false; } if (!isValidPath(urlMatcher.group(PARSE_URL_PATH))) { return false; } if (!isValidQuery(urlMatcher.group(PARSE_URL_QUERY))) { return false; } if (!isValidFragment(urlMatcher.group(PARSE_URL_FRAGMENT))) { return false; } return true; } /** * Validate scheme. If schemes[] was initialized to a non null, * then only those scheme's are allowed. Note this is slightly different * than for the constructor. * @param scheme The scheme to validate. A null value is considered * invalid. * @return true if valid. */ protected boolean isValidScheme(String scheme) { if (scheme == null) { return false; } if (!SCHEME_PATTERN.matcher(scheme).matches()) { return false; } if (this.options.isOff(ALLOW_ALL_SCHEMES)) { if (!this.allowedSchemes.contains(scheme)) { return false; } } return true; } /** * Returns true if the authority is properly formatted. An authority is the combination * of hostname and port. A null authority value is considered invalid. * @param authority Authority value to validate. * @return true if authority (hostname and port) is valid. */ protected boolean isValidAuthority(String authority) { if (authority == null) { return false; } InetAddressValidator inetAddressValidator = InetAddressValidator.getInstance(); Matcher authorityMatcher = AUTHORITY_PATTERN.matcher(authority); if (!authorityMatcher.matches()) { return false; } boolean hostname = false; // check if authority is IP address or hostname String hostIP = authorityMatcher.group(PARSE_AUTHORITY_HOST_IP); boolean ipV4Address = inetAddressValidator.isValid(hostIP); if (!ipV4Address) { // Domain is hostname name hostname = DOMAIN_PATTERN.matcher(hostIP).matches(); } //rightmost hostname will never start with a digit. if (hostname) { // LOW-TECH FIX FOR VALIDATOR-202 // TODO: Rewrite to use ArrayList and .add semantics: see VALIDATOR-203 char[] chars = hostIP.toCharArray(); int size = 1; for(int i=0; i= hostIP.length()) ? "" : hostIP.substring(segmentLength); segmentCount++; } } String topLevel = domainSegment[segmentCount - 1]; if (topLevel.length() < 2 || topLevel.length() > 4) { return false; } // First letter of top level must be a alpha if (!ALPHA_PATTERN.matcher(topLevel.substring(0, 1)).matches()) { return false; } // Make sure there's a host name preceding the authority. if (segmentCount < 2) { return false; } } if (!hostname && !ipV4Address) { return false; } String port = authorityMatcher.group(PARSE_AUTHORITY_PORT); if (port != null) { if (!PORT_PATTERN.matcher(port).matches()) { return false; } } String extra = authorityMatcher.group(PARSE_AUTHORITY_EXTRA); if (!GenericValidator.isBlankOrNull(extra)) { return false; } return true; } /** * Returns true if the path is valid. A null value is considered invalid. * @param path Path value to validate. * @return true if path is valid. */ protected boolean isValidPath(String path) { if (path == null) { return false; } if (!PATH_PATTERN.matcher(path).matches()) { return false; } int slash2Count = countToken("//", path); if (this.options.isOff(ALLOW_2_SLASHES) && (slash2Count > 0)) { return false; } int slashCount = countToken("/", path); int dot2Count = countToken("..", path); if (dot2Count > 0) { if ((slashCount - slash2Count - 1) <= dot2Count) { return false; } } return true; } /** * Returns true if the query is null or it's a properly formatted query string. * @param query Query value to validate. * @return true if query is valid. */ protected boolean isValidQuery(String query) { if (query == null) { return true; } return QUERY_PATTERN.matcher(query).matches(); } /** * Returns true if the given fragment is null or fragments are allowed. * @param fragment Fragment value to validate. * @return true if fragment is valid. */ protected boolean isValidFragment(String fragment) { if (fragment == null) { return true; } return this.options.isOff(NO_FRAGMENTS); } /** * Returns the number of times the token appears in the target. * @param token Token value to be counted. * @param target Target value to count tokens in. * @return the number of tokens. */ protected int countToken(String token, String target) { int tokenIndex = 0; int count = 0; while (tokenIndex != -1) { tokenIndex = target.indexOf(token, tokenIndex); if (tokenIndex > -1) { tokenIndex++; count++; } } return count; } } commons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/Validator.java100644 765 0 32020 11711227702 31714 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator; import java.io.Serializable; import java.util.HashMap; import java.util.Locale; import java.util.Map; /** * Validations are processed by the validate method. An instance of * ValidatorResources is used to define the validators * (validation methods) and the validation rules for a JavaBean. * * @version $Revision: 1227719 $ $Date: 2012-01-05 18:45:51 +0100 (Thu, 05 Jan 2012) $ */ public class Validator implements Serializable { private static final long serialVersionUID = -7119418755208731611L; /** * Resources key the JavaBean is stored to perform validation on. */ public static final String BEAN_PARAM = "java.lang.Object"; /** * Resources key the ValidatorAction is stored under. * This will be automatically passed into a validation method * with the current ValidatorAction if it is * specified in the method signature. */ public static final String VALIDATOR_ACTION_PARAM = "org.apache.commons.validator.ValidatorAction"; /** * Resources key the ValidatorResults is stored under. * This will be automatically passed into a validation method * with the current ValidatorResults if it is * specified in the method signature. */ public static final String VALIDATOR_RESULTS_PARAM = "org.apache.commons.validator.ValidatorResults"; /** * Resources key the Form is stored under. * This will be automatically passed into a validation method * with the current Form if it is * specified in the method signature. */ public static final String FORM_PARAM = "org.apache.commons.validator.Form"; /** * Resources key the Field is stored under. * This will be automatically passed into a validation method * with the current Field if it is * specified in the method signature. */ public static final String FIELD_PARAM = "org.apache.commons.validator.Field"; /** * Resources key the Validator is stored under. * This will be automatically passed into a validation method * with the current Validator if it is * specified in the method signature. */ public static final String VALIDATOR_PARAM = "org.apache.commons.validator.Validator"; /** * Resources key the Locale is stored. * This will be used to retrieve the appropriate * FormSet and Form to be * processed. */ public static final String LOCALE_PARAM = "java.util.Locale"; /** * The Validator Resources. */ protected ValidatorResources resources = null; /** * The name of the form to validate */ protected String formName = null; /** * The name of the field on the form to validate * @since 1.2.0 */ protected String fieldName = null; /** * Maps validation method parameter class names to the objects to be passed * into the method. */ protected Map parameters = new HashMap(); /** * The current page number to validate. */ protected int page = 0; /** * The class loader to use for instantiating application objects. * If not specified, the context class loader, or the class loader * used to load Digester itself, is used, based on the value of the * useContextClassLoader variable. */ protected transient ClassLoader classLoader = null; /** * Whether or not to use the Context ClassLoader when loading classes * for instantiating new objects. Default is false. */ protected boolean useContextClassLoader = false; /** * Set this to true to not return Fields that pass validation. Only return failures. */ protected boolean onlyReturnErrors = false; /** * Construct a Validator that will * use the ValidatorResources * passed in to retrieve pluggable validators * the different sets of validation rules. * * @param resources ValidatorResources to use during validation. */ public Validator(ValidatorResources resources) { this(resources, null); } /** * Construct a Validator that will * use the ValidatorResources * passed in to retrieve pluggable validators * the different sets of validation rules. * * @param resources ValidatorResources to use during validation. * @param formName Key used for retrieving the set of validation rules. */ public Validator(ValidatorResources resources, String formName) { if (resources == null) { throw new IllegalArgumentException("Resources cannot be null."); } this.resources = resources; this.formName = formName; } /** * Construct a Validator that will * use the ValidatorResources * passed in to retrieve pluggable validators * the different sets of validation rules. * * @param resources ValidatorResources to use during validation. * @param formName Key used for retrieving the set of validation rules. * @param fieldName Key used for retrieving the set of validation rules for a field * @since 1.2.0 */ public Validator(ValidatorResources resources, String formName, String fieldName) { if (resources == null) { throw new IllegalArgumentException("Resources cannot be null."); } this.resources = resources; this.formName = formName; this.fieldName = fieldName; } /** * Set a parameter of a pluggable validation method. * * @param parameterClassName The full class name of the parameter of the * validation method that corresponds to the value/instance passed in with it. * * @param parameterValue The instance that will be passed into the * validation method. */ public void setParameter(String parameterClassName, Object parameterValue) { this.parameters.put(parameterClassName, parameterValue); } /** * Returns the value of the specified parameter that will be used during the * processing of validations. * * @param parameterClassName The full class name of the parameter of the * validation method that corresponds to the value/instance passed in with it. * @return value of the specified parameter. */ public Object getParameterValue(String parameterClassName) { return this.parameters.get(parameterClassName); } /** * Gets the form name which is the key to a set of validation rules. * @return the name of the form. */ public String getFormName() { return formName; } /** * Sets the form name which is the key to a set of validation rules. * @param formName the name of the form. */ public void setFormName(String formName) { this.formName = formName; } /** * Sets the name of the field to validate in a form (optional) * * @param fieldName The name of the field in a form set * @since 1.2.0 */ public void setFieldName(String fieldName) { this.fieldName = fieldName; } /** * Gets the page. This in conjunction with the page property of * a Field can control the processing of fields. If the field's * page is less than or equal to this page value, it will be processed. * @return the page number. */ public int getPage() { return page; } /** * Sets the page. This in conjunction with the page property of * a Field can control the processing of fields. If the field's page * is less than or equal to this page value, it will be processed. * @param page the page number. */ public void setPage(int page) { this.page = page; } /** * Clears the form name, resources that were added, and the page that was * set (if any). This can be called to reinitialize the Validator instance * so it can be reused. The form name (key to set of validation rules) and any * resources needed, like the JavaBean being validated, will need to * set and/or added to this instance again. The * ValidatorResources will not be removed since it can be used * again and is thread safe. */ public void clear() { this.formName = null; this.fieldName = null; this.parameters = new HashMap(); this.page = 0; } /** * Return the boolean as to whether the context classloader should be used. * @return whether the context classloader should be used. */ public boolean getUseContextClassLoader() { return this.useContextClassLoader; } /** * Determine whether to use the Context ClassLoader (the one found by * calling Thread.currentThread().getContextClassLoader()) * to resolve/load classes that are defined in various rules. If not * using Context ClassLoader, then the class-loading defaults to * using the calling-class' ClassLoader. * * @param use determines whether to use Context ClassLoader. */ public void setUseContextClassLoader(boolean use) { this.useContextClassLoader = use; } /** * Return the class loader to be used for instantiating application objects * when required. This is determined based upon the following rules: *
      *
    • The class loader set by setClassLoader(), if any
    • *
    • The thread context class loader, if it exists and the * useContextClassLoader property is set to true
    • *
    • The class loader used to load the Digester class itself. *
    * @return the class loader. */ public ClassLoader getClassLoader() { if (this.classLoader != null) { return this.classLoader; } if (this.useContextClassLoader) { ClassLoader contextLoader = Thread.currentThread().getContextClassLoader(); if (contextLoader != null) { return contextLoader; } } return this.getClass().getClassLoader(); } /** * Set the class loader to be used for instantiating application objects * when required. * * @param classLoader The new class loader to use, or null * to revert to the standard rules */ public void setClassLoader(ClassLoader classLoader) { this.classLoader = classLoader; } /** * Performs validations based on the configured resources. * * @return The Map returned uses the property of the * Field for the key and the value is the number of error the * field had. * @throws ValidatorException If an error occurs during validation */ public ValidatorResults validate() throws ValidatorException { Locale locale = (Locale) this.getParameterValue(LOCALE_PARAM); if (locale == null) { locale = Locale.getDefault(); } this.setParameter(VALIDATOR_PARAM, this); Form form = this.resources.getForm(locale, this.formName); if (form != null) { this.setParameter(FORM_PARAM, form); return form.validate( this.parameters, this.resources.getValidatorActions(), this.page, this.fieldName); } return new ValidatorResults(); } /** * Returns true if the Validator is only returning Fields that fail validation. * @return whether only failed fields are returned. */ public boolean getOnlyReturnErrors() { return onlyReturnErrors; } /** * Configures which Fields the Validator returns from the validate() method. Set this * to true to only return Fields that failed validation. By default, validate() returns * all fields. * @param onlyReturnErrors whether only failed fields are returned. */ public void setOnlyReturnErrors(boolean onlyReturnErrors) { this.onlyReturnErrors = onlyReturnErrors; } } commons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/ValidatorAction.java100644 765 0 60777 11711227702 33076 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Serializable; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.commons.validator.util.ValidatorUtils; /** * Contains the information to dynamically create and run a validation * method. This is the class representation of a pluggable validator that can * be defined in an xml file with the <validator> element. * * Note: The validation method is assumed to be thread safe. * * @version $Revision: 1227719 $ $Date: 2012-01-05 18:45:51 +0100 (Thu, 05 Jan 2012) $ */ public class ValidatorAction implements Serializable { private static final long serialVersionUID = 1339713700053204597L; /** * Logger. */ private transient Log log = LogFactory.getLog(ValidatorAction.class); /** * The name of the validation. */ private String name = null; /** * The full class name of the class containing * the validation method associated with this action. */ private String classname = null; /** * The Class object loaded from the classname. */ private Class validationClass = null; /** * The full method name of the validation to be performed. The method * must be thread safe. */ private String method = null; /** * The Method object loaded from the method name. */ private Method validationMethod = null; /** *

    * The method signature of the validation method. This should be a comma * delimited list of the full class names of each parameter in the correct * order that the method takes. *

    *

    * Note: java.lang.Object is reserved for the * JavaBean that is being validated. The ValidatorAction * and Field that are associated with a field's * validation will automatically be populated if they are * specified in the method signature. *

    */ private String methodParams = Validator.BEAN_PARAM + "," + Validator.VALIDATOR_ACTION_PARAM + "," + Validator.FIELD_PARAM; /** * The Class objects for each entry in methodParameterList. */ private Class[] parameterClasses = null; /** * The other ValidatorActions that this one depends on. If * any errors occur in an action that this one depends on, this action will * not be processsed. */ private String depends = null; /** * The default error message associated with this action. */ private String msg = null; /** * An optional field to contain the name to be used if JavaScript is * generated. */ private String jsFunctionName = null; /** * An optional field to contain the class path to be used to retrieve the * JavaScript function. */ private String jsFunction = null; /** * An optional field to containing a JavaScript representation of the * java method assocated with this action. */ private String javascript = null; /** * If the java method matching the correct signature isn't static, the * instance is stored in the action. This assumes the method is thread * safe. */ private Object instance = null; /** * An internal List representation of the other ValidatorActions * this one depends on (if any). This List gets updated * whenever setDepends() gets called. This is synchronized so a call to * setDepends() (which clears the List) won't interfere with a call to * isDependency(). */ private List dependencyList = Collections.synchronizedList(new ArrayList()); /** * An internal List representation of all the validation method's * parameters defined in the methodParams String. */ private List methodParameterList = new ArrayList(); /** * Gets the name of the validator action. * @return Validator Action name. */ public String getName() { return name; } /** * Sets the name of the validator action. * @param name Validator Action name. */ public void setName(String name) { this.name = name; } /** * Gets the class of the validator action. * @return Class name of the validator Action. */ public String getClassname() { return classname; } /** * Sets the class of the validator action. * @param classname Class name of the validator Action. */ public void setClassname(String classname) { this.classname = classname; } /** * Gets the name of method being called for the validator action. * @return The method name. */ public String getMethod() { return method; } /** * Sets the name of method being called for the validator action. * @param method The method name. */ public void setMethod(String method) { this.method = method; } /** * Gets the method parameters for the method. * @return Method's parameters. */ public String getMethodParams() { return methodParams; } /** * Sets the method parameters for the method. * @param methodParams A comma separated list of parameters. */ public void setMethodParams(String methodParams) { this.methodParams = methodParams; this.methodParameterList.clear(); StringTokenizer st = new StringTokenizer(methodParams, ","); while (st.hasMoreTokens()) { String value = st.nextToken().trim(); if (value != null && value.length() > 0) { this.methodParameterList.add(value); } } } /** * Gets the dependencies of the validator action as a comma separated list * of validator names. * @return The validator action's dependencies. */ public String getDepends() { return this.depends; } /** * Sets the dependencies of the validator action. * @param depends A comma separated list of validator names. */ public void setDepends(String depends) { this.depends = depends; this.dependencyList.clear(); StringTokenizer st = new StringTokenizer(depends, ","); while (st.hasMoreTokens()) { String depend = st.nextToken().trim(); if (depend != null && depend.length() > 0) { this.dependencyList.add(depend); } } } /** * Gets the message associated with the validator action. * @return The message for the validator action. */ public String getMsg() { return msg; } /** * Sets the message associated with the validator action. * @param msg The message for the validator action. */ public void setMsg(String msg) { this.msg = msg; } /** * Gets the Javascript function name. This is optional and can * be used instead of validator action name for the name of the * Javascript function/object. * @return The Javascript function name. */ public String getJsFunctionName() { return jsFunctionName; } /** * Sets the Javascript function name. This is optional and can * be used instead of validator action name for the name of the * Javascript function/object. * @param jsFunctionName The Javascript function name. */ public void setJsFunctionName(String jsFunctionName) { this.jsFunctionName = jsFunctionName; } /** * Sets the fully qualified class path of the Javascript function. *

    * This is optional and can be used instead of the setJavascript(). * Attempting to call both setJsFunction and setJavascript * will result in an IllegalStateException being thrown.

    *

    * If neither setJsFunction or setJavascript is set then * validator will attempt to load the default javascript definition. *

    *
         * Examples
         *   If in the validator.xml :
         * #1:
         *      <validator name="tire"
         *            jsFunction="com.yourcompany.project.tireFuncion">
         *     Validator will attempt to load com.yourcompany.project.validateTireFunction.js from
         *     its class path.
         * #2:
         *    <validator name="tire">
         *      Validator will use the name attribute to try and load
         *         org.apache.commons.validator.javascript.validateTire.js
         *      which is the default javascript definition.
         * 
    * @param jsFunction The Javascript function's fully qualified class path. */ public void setJsFunction(String jsFunction) { if (javascript != null) { throw new IllegalStateException("Cannot call setJsFunction() after calling setJavascript()"); } this.jsFunction = jsFunction; } /** * Gets the Javascript equivalent of the java class and method * associated with this action. * @return The Javascript validation. */ public String getJavascript() { return javascript; } /** * Sets the Javascript equivalent of the java class and method * associated with this action. * @param javascript The Javascript validation. */ public void setJavascript(String javascript) { if (jsFunction != null) { throw new IllegalStateException("Cannot call setJavascript() after calling setJsFunction()"); } this.javascript = javascript; } /** * Initialize based on set. */ protected void init() { this.loadJavascriptFunction(); } /** * Load the javascript function specified by the given path. For this * implementation, the jsFunction property should contain a * fully qualified package and script name, separated by periods, to be * loaded from the class loader that created this instance. * * TODO if the path begins with a '/' the path will be intepreted as * absolute, and remain unchanged. If this fails then it will attempt to * treat the path as a file path. It is assumed the script ends with a * '.js'. */ protected synchronized void loadJavascriptFunction() { if (this.javascriptAlreadyLoaded()) { return; } if (getLog().isTraceEnabled()) { getLog().trace(" Loading function begun"); } if (this.jsFunction == null) { this.jsFunction = this.generateJsFunction(); } String javascriptFileName = this.formatJavascriptFileName(); if (getLog().isTraceEnabled()) { getLog().trace(" Loading js function '" + javascriptFileName + "'"); } this.javascript = this.readJavascriptFile(javascriptFileName); if (getLog().isTraceEnabled()) { getLog().trace(" Loading javascript function completed"); } } /** * Read a javascript function from a file. * @param javascriptFileName The file containing the javascript. * @return The javascript function or null if it could not be loaded. */ private String readJavascriptFile(String javascriptFileName) { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); if (classLoader == null) { classLoader = this.getClass().getClassLoader(); } InputStream is = classLoader.getResourceAsStream(javascriptFileName); if (is == null) { is = this.getClass().getResourceAsStream(javascriptFileName); } if (is == null) { getLog().debug(" Unable to read javascript name "+javascriptFileName); return null; } StringBuffer buffer = new StringBuffer(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); try { String line = null; while ((line = reader.readLine()) != null) { buffer.append(line).append("\n"); } } catch(IOException e) { getLog().error("Error reading javascript file.", e); } finally { try { reader.close(); } catch(IOException e) { getLog().error("Error closing stream to javascript file.", e); } } String function = buffer.toString(); return function.equals("") ? null : function; } /** * @return A filename suitable for passing to a * ClassLoader.getResourceAsStream() method. */ private String formatJavascriptFileName() { String name = this.jsFunction.substring(1); if (!this.jsFunction.startsWith("/")) { name = jsFunction.replace('.', '/') + ".js"; } return name; } /** * @return true if the javascript for this action has already been loaded. */ private boolean javascriptAlreadyLoaded() { return (this.javascript != null); } /** * Used to generate the javascript name when it is not specified. */ private String generateJsFunction() { StringBuffer jsName = new StringBuffer("org.apache.commons.validator.javascript"); jsName.append(".validate"); jsName.append(name.substring(0, 1).toUpperCase()); jsName.append(name.substring(1, name.length())); return jsName.toString(); } /** * Checks whether or not the value passed in is in the depends field. * @param validatorName Name of the dependency to check. * @return Whether the named validator is a dependant. */ public boolean isDependency(String validatorName) { return this.dependencyList.contains(validatorName); } /** * Returns the dependent validator names as an unmodifiable * List. * @return List of the validator action's depedents. */ public List getDependencyList() { return Collections.unmodifiableList(this.dependencyList); } /** * Returns a string representation of the object. * @return a string representation. */ public String toString() { StringBuffer results = new StringBuffer("ValidatorAction: "); results.append(name); results.append("\n"); return results.toString(); } /** * Dynamically runs the validation method for this validator and returns * true if the data is valid. * @param field * @param params A Map of class names to parameter values. * @param results * @param pos The index of the list property to validate if it's indexed. * @throws ValidatorException */ boolean executeValidationMethod( Field field, Map params, ValidatorResults results, int pos) throws ValidatorException { params.put(Validator.VALIDATOR_ACTION_PARAM, this); try { if (this.validationMethod == null) { synchronized(this) { ClassLoader loader = this.getClassLoader(params); this.loadValidationClass(loader); this.loadParameterClasses(loader); this.loadValidationMethod(); } } Object[] paramValues = this.getParameterValues(params); if (field.isIndexed()) { this.handleIndexedField(field, pos, paramValues); } Object result = null; try { result = validationMethod.invoke( getValidationClassInstance(), paramValues); } catch (IllegalArgumentException e) { throw new ValidatorException(e.getMessage()); } catch (IllegalAccessException e) { throw new ValidatorException(e.getMessage()); } catch (InvocationTargetException e) { if (e.getTargetException() instanceof Exception) { throw (Exception) e.getTargetException(); } else if (e.getTargetException() instanceof Error) { throw (Error) e.getTargetException(); } } boolean valid = this.isValid(result); if (!valid || (valid && !onlyReturnErrors(params))) { results.add(field, this.name, valid, result); } if (!valid) { return false; } // TODO This catch block remains for backward compatibility. Remove // this for Validator 2.0 when exception scheme changes. } catch (Exception e) { if (e instanceof ValidatorException) { throw (ValidatorException) e; } getLog().error( "Unhandled exception thrown during validation: " + e.getMessage(), e); results.add(field, this.name, false); return false; } return true; } /** * Load the Method object for the configured validation method name. * @throws ValidatorException */ private void loadValidationMethod() throws ValidatorException { if (this.validationMethod != null) { return; } try { this.validationMethod = this.validationClass.getMethod(this.method, this.parameterClasses); } catch (NoSuchMethodException e) { throw new ValidatorException("No such validation method: " + e.getMessage()); } } /** * Load the Class object for the configured validation class name. * @param loader The ClassLoader used to load the Class object. * @throws ValidatorException */ private void loadValidationClass(ClassLoader loader) throws ValidatorException { if (this.validationClass != null) { return; } try { this.validationClass = loader.loadClass(this.classname); } catch (ClassNotFoundException e) { throw new ValidatorException(e.toString()); } } /** * Converts a List of parameter class names into their Class objects. * Stores the output in {@link parameterClasses}. This * array is in the same order as the given List and is suitable for passing * to the validation method. * @throws ValidatorException if a class cannot be loaded. */ private void loadParameterClasses(ClassLoader loader) throws ValidatorException { if (this.parameterClasses != null) { return; } Class[] parameterClasses = new Class[this.methodParameterList.size()]; for (int i = 0; i < this.methodParameterList.size(); i++) { String paramClassName = (String) this.methodParameterList.get(i); try { parameterClasses[i] = loader.loadClass(paramClassName); } catch (ClassNotFoundException e) { throw new ValidatorException(e.getMessage()); } } this.parameterClasses = parameterClasses; } /** * Converts a List of parameter class names into their values contained in * the parameters Map. * @param params A Map of class names to parameter values. * @return An array containing the value object for each parameter. This * array is in the same order as the given List and is suitable for passing * to the validation method. */ private Object[] getParameterValues(Map params) { Object[] paramValue = new Object[this.methodParameterList.size()]; for (int i = 0; i < this.methodParameterList.size(); i++) { String paramClassName = (String) this.methodParameterList.get(i); paramValue[i] = params.get(paramClassName); } return paramValue; } /** * Return an instance of the validation class or null if the validation * method is static so does not require an instance to be executed. */ private Object getValidationClassInstance() throws ValidatorException { if (Modifier.isStatic(this.validationMethod.getModifiers())) { this.instance = null; } else { if (this.instance == null) { try { this.instance = this.validationClass.newInstance(); } catch (InstantiationException e) { String msg = "Couldn't create instance of " + this.classname + ". " + e.getMessage(); throw new ValidatorException(msg); } catch (IllegalAccessException e) { String msg = "Couldn't create instance of " + this.classname + ". " + e.getMessage(); throw new ValidatorException(msg); } } } return this.instance; } /** * Modifies the paramValue array with indexed fields. * * @param field * @param pos * @param paramValues */ private void handleIndexedField(Field field, int pos, Object[] paramValues) throws ValidatorException { int beanIndex = this.methodParameterList.indexOf(Validator.BEAN_PARAM); int fieldIndex = this.methodParameterList.indexOf(Validator.FIELD_PARAM); Object indexedList[] = field.getIndexedProperty(paramValues[beanIndex]); // Set current iteration object to the parameter array paramValues[beanIndex] = indexedList[pos]; // Set field clone with the key modified to represent // the current field Field indexedField = (Field) field.clone(); indexedField.setKey( ValidatorUtils.replace( indexedField.getKey(), Field.TOKEN_INDEXED, "[" + pos + "]")); paramValues[fieldIndex] = indexedField; } /** * If the result object is a Boolean, it will return its * value. If not it will return false if the object is * null and true if it isn't. */ private boolean isValid(Object result) { if (result instanceof Boolean) { Boolean valid = (Boolean) result; return valid.booleanValue(); } else { return (result != null); } } /** * Returns the ClassLoader set in the Validator contained in the parameter * Map. */ private ClassLoader getClassLoader(Map params) { Validator v = (Validator) params.get(Validator.VALIDATOR_PARAM); return v.getClassLoader(); } /** * Returns the onlyReturnErrors setting in the Validator contained in the * parameter Map. */ private boolean onlyReturnErrors(Map params) { Validator v = (Validator) params.get(Validator.VALIDATOR_PARAM); return v.getOnlyReturnErrors(); } /** * Accessor method for Log instance. * * The Log instance variable is transient and * accessing it through this method ensures it * is re-initialized when this instance is * de-serialized. * * @return The Log instance. */ private Log getLog() { if (log == null) { log = LogFactory.getLog(ValidatorAction.class); } return log; } } commons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/ValidatorException.java100644 765 0 3065 11711227702 33562 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator; /** * The base exception for the Validator Framework. All other * Exceptions thrown during calls to * Validator.validate() are considered errors. * * @version $Revision: 1227719 $ $Date: 2012-01-05 18:45:51 +0100 (Thu, 05 Jan 2012) $ */ public class ValidatorException extends Exception { private static final long serialVersionUID = 1025759372615616964L; /** * Constructs an Exception with no specified detail message. */ public ValidatorException() { super(); } /** * Constructs an Exception with the specified detail message. * * @param message The error message. */ public ValidatorException(String message) { super(message); } }commons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/ValidatorResources.java100644 765 0 55060 11711227702 33620 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator; import java.io.IOException; import java.io.InputStream; import java.io.Serializable; import java.net.URL; import java.util.Collections; import java.util.Iterator; import java.util.Locale; import java.util.Map; import org.apache.commons.collections.FastHashMap; import org.apache.commons.digester.Digester; import org.apache.commons.digester.Rule; import org.apache.commons.digester.xmlrules.DigesterLoader; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.xml.sax.SAXException; import org.xml.sax.Attributes; /** *

    * General purpose class for storing FormSet objects based * on their associated Locale. Instances of this class are usually * configured through a validation.xml file that is parsed in a constructor. *

    * *

    Note - Classes that extend this class * must be Serializable so that instances may be used in distributable * application server environments.

    * *

    * The use of FastHashMap is deprecated and will be replaced in a future * release. *

    * * @version $Revision: 1227719 $ $Date: 2012-01-05 18:45:51 +0100 (Thu, 05 Jan 2012) $ */ public class ValidatorResources implements Serializable { private static final long serialVersionUID = -8203745881446239554L; /** Name of the digester validator rules file */ private static final String VALIDATOR_RULES = "digester-rules.xml"; /** * The set of public identifiers, and corresponding resource names, for * the versions of the configuration file DTDs that we know about. There * MUST be an even number of Strings in this list! */ private static final String REGISTRATIONS[] = { "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.0//EN", "/org/apache/commons/validator/resources/validator_1_0.dtd", "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.0.1//EN", "/org/apache/commons/validator/resources/validator_1_0_1.dtd", "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.1//EN", "/org/apache/commons/validator/resources/validator_1_1.dtd", "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.1.3//EN", "/org/apache/commons/validator/resources/validator_1_1_3.dtd", "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.2.0//EN", "/org/apache/commons/validator/resources/validator_1_2_0.dtd", "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.3.0//EN", "/org/apache/commons/validator/resources/validator_1_3_0.dtd", "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.4.0//EN", "/org/apache/commons/validator/resources/validator_1_4_0.dtd" }; private transient Log log = LogFactory.getLog(ValidatorResources.class); /** * Map of FormSets stored under * a Locale key. * @deprecated Subclasses should use getFormSets() instead. */ protected FastHashMap hFormSets = new FastHashMap(); /** * Map of global constant values with * the name of the constant as the key. * @deprecated Subclasses should use getConstants() instead. */ protected FastHashMap hConstants = new FastHashMap(); /** * Map of ValidatorActions with * the name of the ValidatorAction as the key. * @deprecated Subclasses should use getActions() instead. */ protected FastHashMap hActions = new FastHashMap(); /** * The default locale on our server. */ protected static Locale defaultLocale = Locale.getDefault(); /** * Create an empty ValidatorResources object. */ public ValidatorResources() { super(); } /** * This is the default FormSet (without locale). (We probably don't need * the defaultLocale anymore.) */ protected FormSet defaultFormSet; /** * Create a ValidatorResources object from an InputStream. * * @param in InputStream to a validation.xml configuration file. It's the client's * responsibility to close this stream. * @throws IOException * @throws SAXException if the validation XML files are not valid or well * formed. * @throws IOException if an I/O error occurs processing the XML files * @since Validator 1.1 */ public ValidatorResources(InputStream in) throws IOException, SAXException { this(new InputStream[]{in}); } /** * Create a ValidatorResources object from an InputStream. * * @param streams An array of InputStreams to several validation.xml * configuration files that will be read in order and merged into this object. * It's the client's responsibility to close these streams. * @throws IOException * @throws SAXException if the validation XML files are not valid or well * formed. * @throws IOException if an I/O error occurs processing the XML files * @since Validator 1.1 */ public ValidatorResources(InputStream[] streams) throws IOException, SAXException { super(); Digester digester = initDigester(); for (int i = 0; i < streams.length; i++) { if (streams[i] == null) { throw new IllegalArgumentException("Stream[" + i + "] is null"); } digester.push(this); digester.parse(streams[i]); } this.process(); } /** * Create a ValidatorResources object from an uri * * @param uri The location of a validation.xml configuration file. * @throws IOException * @throws SAXException if the validation XML files are not valid or well * formed. * @throws IOException if an I/O error occurs processing the XML files * @since Validator 1.2 */ public ValidatorResources(String uri) throws IOException, SAXException { this(new String[]{uri}); } /** * Create a ValidatorResources object from several uris * * @param uris An array of uris to several validation.xml * configuration files that will be read in order and merged into this object. * @throws IOException * @throws SAXException if the validation XML files are not valid or well * formed. * @throws IOException if an I/O error occurs processing the XML files * @since Validator 1.2 */ public ValidatorResources(String[] uris) throws IOException, SAXException { super(); Digester digester = initDigester(); for (int i = 0; i < uris.length; i++) { digester.push(this); digester.parse(uris[i]); } this.process(); } /** * Create a ValidatorResources object from a URL. * * @param url The URL for the validation.xml * configuration file that will be read into this object. * @throws IOException * @throws SAXException if the validation XML file are not valid or well * formed. * @throws IOException if an I/O error occurs processing the XML files * @since Validator 1.3.1 */ public ValidatorResources(URL url) throws IOException, SAXException { this(new URL[]{url}); } /** * Create a ValidatorResources object from several URL. * * @param urls An array of URL to several validation.xml * configuration files that will be read in order and merged into this object. * @throws IOException * @throws SAXException if the validation XML files are not valid or well * formed. * @throws IOException if an I/O error occurs processing the XML files * @since Validator 1.3.1 */ public ValidatorResources(URL[] urls) throws IOException, SAXException { super(); Digester digester = initDigester(); for (int i = 0; i < urls.length; i++) { digester.push(this); digester.parse(urls[i]); } this.process(); } /** * Initialize the digester. */ private Digester initDigester() { URL rulesUrl = this.getClass().getResource(VALIDATOR_RULES); if (rulesUrl == null) { // Fix for Issue# VALIDATOR-195 rulesUrl = ValidatorResources.class.getResource(VALIDATOR_RULES); } if (getLog().isDebugEnabled()) { getLog().debug("Loading rules from '" + rulesUrl + "'"); } Digester digester = DigesterLoader.createDigester(rulesUrl); digester.setNamespaceAware(true); digester.setValidating(true); digester.setUseContextClassLoader(true); // Add rules for arg0-arg3 elements addOldArgRules(digester); // register DTDs for (int i = 0; i < REGISTRATIONS.length; i += 2) { URL url = this.getClass().getResource(REGISTRATIONS[i + 1]); if (url != null) { digester.register(REGISTRATIONS[i], url.toString()); } } return digester; } private static final String ARGS_PATTERN = "form-validation/formset/form/field/arg"; /** * Create a Rule to handle arg0-arg3 * elements. This will allow validation.xml files that use the * versions of the DTD prior to Validator 1.2.0 to continue * working. */ private void addOldArgRules(Digester digester) { // Create a new rule to process args elements Rule rule = new Rule() { public void begin(String namespace, String name, Attributes attributes) throws Exception { // Create the Arg Arg arg = new Arg(); arg.setKey(attributes.getValue("key")); arg.setName(attributes.getValue("name")); if ("false".equalsIgnoreCase(attributes.getValue("resource"))) { arg.setResource(false); } try { arg.setPosition(Integer.parseInt(name.substring(3))); } catch (Exception ex) { getLog().error("Error parsing Arg position: " + name + " " + arg + " " + ex); } // Add the arg to the parent field ((Field)getDigester().peek(0)).addArg(arg); } }; // Add the rule for each of the arg elements digester.addRule(ARGS_PATTERN + "0", rule); digester.addRule(ARGS_PATTERN + "1", rule); digester.addRule(ARGS_PATTERN + "2", rule); digester.addRule(ARGS_PATTERN + "3", rule); } /** * Add a FormSet to this ValidatorResources * object. It will be associated with the Locale of the * FormSet. * @param fs The form set to add. * @since Validator 1.1 */ public void addFormSet(FormSet fs) { String key = this.buildKey(fs); if (key.length() == 0) {// there can only be one default formset if (getLog().isWarnEnabled() && defaultFormSet != null) { // warn the user he might not get the expected results getLog().warn("Overriding default FormSet definition."); } defaultFormSet = fs; } else { FormSet formset = (FormSet) hFormSets.get(key); if (formset == null) {// it hasn't been included yet if (getLog().isDebugEnabled()) { getLog().debug("Adding FormSet '" + fs.toString() + "'."); } } else if (getLog().isWarnEnabled()) {// warn the user he might not // get the expected results getLog() .warn("Overriding FormSet definition. Duplicate for locale: " + key); } hFormSets.put(key, fs); } } /** * Add a global constant to the resource. * @param name The constant name. * @param value The constant value. */ public void addConstant(String name, String value) { if (getLog().isDebugEnabled()) { getLog().debug("Adding Global Constant: " + name + "," + value); } this.hConstants.put(name, value); } /** * Add a ValidatorAction to the resource. It also creates an * instance of the class based on the ValidatorActions * classname and retrieves the Method instance and sets them * in the ValidatorAction. * @param va The validator action. */ public void addValidatorAction(ValidatorAction va) { va.init(); this.hActions.put(va.getName(), va); if (getLog().isDebugEnabled()) { getLog().debug("Add ValidatorAction: " + va.getName() + "," + va.getClassname()); } } /** * Get a ValidatorAction based on it's name. * @param key The validator action key. * @return The validator action. */ public ValidatorAction getValidatorAction(String key) { return (ValidatorAction) hActions.get(key); } /** * Get an unmodifiable Map of the ValidatorActions. * @return Map of validator actions. */ public Map getValidatorActions() { return Collections.unmodifiableMap(hActions); } /** * Builds a key to store the FormSet under based on it's * language, country, and variant values. * @param fs The Form Set. * @return generated key for a formset. */ protected String buildKey(FormSet fs) { return this.buildLocale(fs.getLanguage(), fs.getCountry(), fs.getVariant()); } /** * Assembles a Locale code from the given parts. */ private String buildLocale(String lang, String country, String variant) { String key = ((lang != null && lang.length() > 0) ? lang : ""); key += ((country != null && country.length() > 0) ? "_" + country : ""); key += ((variant != null && variant.length() > 0) ? "_" + variant : ""); return key; } /** *

    Gets a Form based on the name of the form and the * Locale that most closely matches the Locale * passed in. The order of Locale matching is:

    *
      *
    1. language + country + variant
    2. *
    3. language + country
    4. *
    5. language
    6. *
    7. default locale
    8. *
    * @param locale The Locale. * @param formKey The key for the Form. * @return The validator Form. * @since Validator 1.1 */ public Form getForm(Locale locale, String formKey) { return this.getForm(locale.getLanguage(), locale.getCountry(), locale .getVariant(), formKey); } /** *

    Gets a Form based on the name of the form and the * Locale that most closely matches the Locale * passed in. The order of Locale matching is:

    *
      *
    1. language + country + variant
    2. *
    3. language + country
    4. *
    5. language
    6. *
    7. default locale
    8. *
    * @param language The locale's language. * @param country The locale's country. * @param variant The locale's language variant. * @param formKey The key for the Form. * @return The validator Form. * @since Validator 1.1 */ public Form getForm(String language, String country, String variant, String formKey) { Form form = null; // Try language/country/variant String key = this.buildLocale(language, country, variant); if (key.length() > 0) { FormSet formSet = (FormSet)hFormSets.get(key); if (formSet != null) { form = formSet.getForm(formKey); } } String localeKey = key; // Try language/country if (form == null) { key = buildLocale(language, country, null); if (key.length() > 0) { FormSet formSet = (FormSet)hFormSets.get(key); if (formSet != null) { form = formSet.getForm(formKey); } } } // Try language if (form == null) { key = buildLocale(language, null, null); if (key.length() > 0) { FormSet formSet = (FormSet)hFormSets.get(key); if (formSet != null) { form = formSet.getForm(formKey); } } } // Try default formset if (form == null) { form = defaultFormSet.getForm(formKey); key = "default"; } if (form == null) { if (getLog().isWarnEnabled()) { getLog().warn("Form '" + formKey + "' not found for locale '" + localeKey + "'"); } } else { if (getLog().isDebugEnabled()) { getLog().debug("Form '" + formKey + "' found in formset '" + key + "' for locale '" + localeKey + "'"); } } return form; } /** * Process the ValidatorResources object. Currently sets the * FastHashMap s to the 'fast' mode and call the processes * all other resources. Note : The framework calls this * automatically when ValidatorResources is created from an XML file. If you * create an instance of this class by hand you must call * this method when finished. */ public void process() { hFormSets.setFast(true); hConstants.setFast(true); hActions.setFast(true); this.processForms(); } /** *

    Process the Form objects. This clones the Fields * that don't exist in a FormSet compared to its parent * FormSet.

    */ private void processForms() { if (defaultFormSet == null) {// it isn't mandatory to have a // default formset defaultFormSet = new FormSet(); } defaultFormSet.process(hConstants); // Loop through FormSets and merge if necessary for (Iterator i = hFormSets.keySet().iterator(); i.hasNext();) { String key = (String) i.next(); FormSet fs = (FormSet) hFormSets.get(key); fs.merge(getParent(fs)); } // Process Fully Constructed FormSets for (Iterator i = hFormSets.values().iterator(); i.hasNext();) { FormSet fs = (FormSet) i.next(); if (!fs.isProcessed()) { fs.process(hConstants); } } } /** * Finds the given formSet's parent. ex: A formSet with locale en_UK_TEST1 * has a direct parent in the formSet with locale en_UK. If it doesn't * exist, find the formSet with locale en, if no found get the * defaultFormSet. * * @param fs * the formSet we want to get the parent from * @return fs's parent */ private FormSet getParent(FormSet fs) { FormSet parent = null; if (fs.getType() == FormSet.LANGUAGE_FORMSET) { parent = defaultFormSet; } else if (fs.getType() == FormSet.COUNTRY_FORMSET) { parent = (FormSet) hFormSets.get(buildLocale(fs.getLanguage(), null, null)); if (parent == null) { parent = defaultFormSet; } } else if (fs.getType() == FormSet.VARIANT_FORMSET) { parent = (FormSet) hFormSets.get(buildLocale(fs.getLanguage(), fs .getCountry(), null)); if (parent == null) { parent = (FormSet) hFormSets.get(buildLocale(fs.getLanguage(), null, null)); if (parent == null) { parent = defaultFormSet; } } } return parent; } /** *

    Gets a FormSet based on the language, country * and variant.

    * @param language The locale's language. * @param country The locale's country. * @param variant The locale's language variant. * @return The FormSet for a locale. * @since Validator 1.2 */ FormSet getFormSet(String language, String country, String variant) { String key = buildLocale(language, country, variant); if (key.length() == 0) { return defaultFormSet; } return (FormSet)hFormSets.get(key); } /** * Returns a Map of String locale keys to Lists of their FormSets. * @return Map of Form sets * @since Validator 1.2.0 */ protected Map getFormSets() { return hFormSets; } /** * Returns a Map of String constant names to their String values. * @return Map of Constants * @since Validator 1.2.0 */ protected Map getConstants() { return hConstants; } /** * Returns a Map of String ValidatorAction names to their ValidatorAction. * @return Map of Validator Actions * @since Validator 1.2.0 */ protected Map getActions() { return hActions; } /** * Accessor method for Log instance. * * The Log instance variable is transient and * accessing it through this method ensures it * is re-initialized when this instance is * de-serialized. * * @return The Log instance. */ private Log getLog() { if (log == null) { log = LogFactory.getLog(ValidatorResources.class); } return log; } } commons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/ValidatorResult.java100644 765 0 14376 11711227702 33131 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator; import java.io.Serializable; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Iterator; /** * This contains the results of a set of validation rules processed * on a JavaBean. * * @version $Revision: 1237168 $ $Date: 2012-01-28 22:20:15 +0100 (Sat, 28 Jan 2012) $ */ public class ValidatorResult implements Serializable { private static final long serialVersionUID = -3713364681647250531L; /** * Map of results. The key is the name of the ValidatorAction * and the value is whether or not this field passed or not. */ protected Map hAction = new HashMap(); /** * Field being validated. * TODO This variable is not used. Need to investigate removing it. */ protected Field field = null; /** * Constructs a ValidatorResult with the associated field being * validated. * @param field Field that was validated. */ public ValidatorResult(Field field) { this.field = field; } /** * Add the result of a validator action. * @param validatorName Name of the validator. * @param result Whether the validation passed or failed. */ public void add(String validatorName, boolean result) { this.add(validatorName, result, null); } /** * Add the result of a validator action. * @param validatorName Name of the validator. * @param result Whether the validation passed or failed. * @param value Value returned by the validator. */ public void add(String validatorName, boolean result, Object value) { hAction.put(validatorName, new ResultStatus(result, value)); } /** * Indicate whether a specified validator is in the Result. * @param validatorName Name of the validator. * @return true if the validator is in the result. */ public boolean containsAction(String validatorName) { return hAction.containsKey(validatorName); } /** * Indicate whether a specified validation passed. * @param validatorName Name of the validator. * @return true if the validation passed. */ public boolean isValid(String validatorName) { ResultStatus status = (ResultStatus) hAction.get(validatorName); return (status == null) ? false : status.isValid(); } /** * Return the result of a validation. * @param validatorName Name of the validator. * @return The validation result. */ public Object getResult(String validatorName) { ResultStatus status = (ResultStatus) hAction.get(validatorName); return (status == null) ? null : status.getResult(); } /** * Return an Iterator of the action names contained in this Result. * @return The set of action names. */ public Iterator getActions() { return Collections.unmodifiableMap(hAction).keySet().iterator(); } /** * Return a Map of the validator actions in this Result. * @return Map of validator actions. * @deprecated Use getActions() to return the set of actions * the isValid(name) and getResult(name) methods * to determine the contents of ResultStatus. * */ public Map getActionMap() { return Collections.unmodifiableMap(hAction); } /** * Returns the Field that was validated. * @return The Field associated with this result. */ public Field getField() { return this.field; } /** * Contains the status of the validation. */ protected static class ResultStatus implements Serializable { private static final long serialVersionUID = 4076665918535320007L; private boolean valid = false; private Object result = null; /** * Construct a Result status. * @param valid Whether the validator passed or failed. * @param result Value returned by the validator. */ public ResultStatus(boolean valid, Object result) { this.valid = valid; this.result = result; } /** * Provided for backwards binary compatibility only * @deprecated Use {@link #ValidatorResult(boolean, Object)} instead */ public ResultStatus(ValidatorResult ignored, boolean valid, Object result) { this(valid, result); } /** * Tests whether or not the validation passed. * @return true if the result was good. */ public boolean isValid() { return valid; } /** * Sets whether or not the validation passed. * @param valid Whether the validation passed. */ public void setValid(boolean valid) { this.valid = valid; } /** * Gets the result returned by a validation method. * This can be used to retrieve to the correctly * typed value of a date validation for example. * @return The value returned by the validation. */ public Object getResult() { return result; } /** * Sets the result returned by a validation method. * This can be used to retrieve to the correctly * typed value of a date validation for example. * @param result The value returned by the validation. */ public void setResult(Object result) { this.result = result; } } }commons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/ValidatorResults.java100644 765 0 11171 11711227702 33302 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator; import java.io.Serializable; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; /** * This contains the results of a set of validation rules processed * on a JavaBean. * * @version $Revision: 1227719 $ $Date: 2012-01-05 18:45:51 +0100 (Thu, 05 Jan 2012) $ */ public class ValidatorResults implements Serializable { private static final long serialVersionUID = -2709911078904924839L; /** * Map of validation results. */ protected Map hResults = new HashMap(); /** * Merge another ValidatorResults into mine. * * @param results ValidatorResults to merge. */ public void merge(ValidatorResults results) { this.hResults.putAll(results.hResults); } /** * Add a the result of a validator action. * * @param field The field validated. * @param validatorName The name of the validator. * @param result The result of the validation. */ public void add(Field field, String validatorName, boolean result) { this.add(field, validatorName, result, null); } /** * Add a the result of a validator action. * * @param field The field validated. * @param validatorName The name of the validator. * @param result The result of the validation. * @param value The value returned by the validator. */ public void add( Field field, String validatorName, boolean result, Object value) { ValidatorResult validatorResult = this.getValidatorResult(field.getKey()); if (validatorResult == null) { validatorResult = new ValidatorResult(field); this.hResults.put(field.getKey(), validatorResult); } validatorResult.add(validatorName, result, value); } /** * Clear all results recorded by this object. */ public void clear() { this.hResults.clear(); } /** * Return true if there are no messages recorded * in this collection, or false otherwise. * * @return Whether these results are empty. */ public boolean isEmpty() { return this.hResults.isEmpty(); } /** * Gets the ValidatorResult associated * with the key passed in. The key the ValidatorResult * is stored under is the Field's getKey method. * * @param key The key generated from Field (this is often just * the field name). * * @return The result of a specified key. */ public ValidatorResult getValidatorResult(String key) { return (ValidatorResult) this.hResults.get(key); } /** * Return the set of property names for which at least one message has * been recorded. * @return An unmodifiable Set of the property names. */ public Set getPropertyNames() { return Collections.unmodifiableSet(this.hResults.keySet()); } /** * Get a Map of any Objects returned from * validation routines. * * @return Map of objections returned by validators. */ public Map getResultValueMap() { Map results = new HashMap(); for (Iterator i = hResults.keySet().iterator(); i.hasNext();) { String propertyKey = (String) i.next(); ValidatorResult vr = this.getValidatorResult(propertyKey); for (Iterator x = vr.getActions(); x.hasNext();) { String actionKey = (String)x.next(); Object result = vr.getResult(actionKey); if (result != null && !(result instanceof Boolean)) { results.put(propertyKey, result); } } } return results; } } commons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/Var.java100644 765 0 12763 11711227702 30533 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator; import java.io.Serializable; /** * A variable that can be associated with a Field for * passing in information to a pluggable validator. Instances of this class are * configured with a <var> xml element. * * @version $Revision: 493905 $ $Date: 2007-01-08 03:11:38 +0100 (Mon, 08 Jan 2007) $ */ public class Var implements Cloneable, Serializable { /** * Int Constant for JavaScript type. This can be used * when auto-generating JavaScript. */ public static final String JSTYPE_INT = "int"; /** * String Constant for JavaScript type. This can be used * when auto-generating JavaScript. */ public static final String JSTYPE_STRING = "string"; /** * Regular Expression Constant for JavaScript type. This can be used * when auto-generating JavaScript. */ public static final String JSTYPE_REGEXP = "regexp"; /** * The name of the variable. */ private String name = null; /** * The key or value the variable. */ private String value = null; /** * The optional JavaScript type of the variable. */ private String jsType = null; /** * Whether the variable is a resource [false] */ private boolean resource = false; /** * The bundle for a variable (when resource = 'true'). */ private String bundle = null; /** * Default Constructor. */ public Var() { super(); } /** * Constructs a variable with a specified name, value * and Javascript type. * @param name Variable name. * @param value Variable value. * @param jsType Variable Javascript type. */ public Var(String name, String value, String jsType) { this.name = name; this.value = value; this.jsType = jsType; } /** * Gets the name of the variable. * @return The name of the variable. */ public String getName() { return this.name; } /** * Sets the name of the variable. * @param name The name of the variable. */ public void setName(String name) { this.name = name; } /** * Gets the value of the variable. * @return The value of the variable. */ public String getValue() { return this.value; } /** * Sets the value of the variable. * @param value The value of the variable. */ public void setValue(String value) { this.value = value; } /** * Tests whether or not the value is a resource key or literal value. * @return true if value is a resource key. * @since Validator 1.2.0 */ public boolean isResource() { return this.resource; } /** * Sets whether or not the value is a resource. * @param resource If true indicates the value is a resource. * @since Validator 1.2.0 */ public void setResource(boolean resource) { this.resource = resource; } /** * Returns the resource bundle name. * @return The bundle name. * @since Validator 1.2.0 */ public String getBundle() { return this.bundle; } /** * Sets the resource bundle name. * @param bundle The new bundle name. * @since Validator 1.2.0 */ public void setBundle(String bundle) { this.bundle = bundle; } /** * Gets the JavaScript type of the variable. * @return The Javascript type of the variable. */ public String getJsType() { return this.jsType; } /** * Sets the JavaScript type of the variable. * @param jsType The Javascript type of the variable. */ public void setJsType(String jsType) { this.jsType = jsType; } /** * Creates and returns a copy of this object. * @return A copy of the variable. */ public Object clone() { try { return super.clone(); } catch(CloneNotSupportedException e) { throw new RuntimeException(e.toString()); } } /** * Returns a string representation of the object. * @return A string representation of the variable. */ public String toString() { StringBuffer results = new StringBuffer(); results.append("Var: name="); results.append(name); results.append(" value="); results.append(value); results.append(" resource="); results.append(resource); if (resource) { results.append(" bundle="); results.append(bundle); } results.append(" jsType="); results.append(jsType); results.append("\n"); return results.toString(); } }commons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/package.html100644 765 0 23700 11711227702 31412 0ustarsimonetripodiwheel 0 0 Package Documentation for org.apache.commons.validator The Validator package provides validation for JavaBeans based on an xml file.

    Introduction

    A common issue when receiving data either electronically or from user input is verifying the integrity of the data. This work is repetitive and becomes even more complicated when different sets of validation rules need to be applied to the same set of data based on locale for example. Error messages may also vary by locale. This package attempts to address some of these issues and speed development and maintenance of validation rules.

    In order to use the Validator, the following basic steps are required:

    • Create a new instance of the org.apache.commons.validator.Validator class. Currently Validator instances may be safely reused if the current ValidatorResources are the same, as long as you have completed any previous validation, and you do not try to utilize a particular Validator instance from more than one thread at a time.
    • Add any resources needed to perform the validations. Such as the JavaBean to validate.
    • Call the validate method on org.apache.commons.validator.Validator.

    Overview

    The Commons Validator is a basic validation framework that lets you define validation rules for a JavaBean in an xml file. Validators, the validation definition, can also be defined in the xml file. An example of a validator would be defining what method and class will be called to perform the validation for a required field. Validation rules can be grouped together based on locale and a JavaBean/Form that the rules are associated with. The framework has basic support for user defined constants which can be used in some field attributes.

    Validation rules can be defined in an xml file which keeps them abstracted from JavaBean you are validating. The property reference to a field supports nested properties using the Apache Commons BeanUtils (http://commons.apache.org/beanutils/) package. Error messages and the arguments for error messages can be associated with a fields validation.

    Resources

    After a Validator instance is created, instances of classes can be added to it to be passed into validation methods by calling the setParameter() method. Below is a list of reserved parameters (class names).

    Class Name Validator Contstant Description
    java.lang.Object Validator.BEAN_PARAM JavaBean that is being validated
    java.util.Locale Validator.LOCALE_PARAM Locale to use when retrieving a FormSet. The default locale will be used if one isn't specified.
    org.apache.commons.validator.ValidatorAction Validator.VALIDATOR_ACTION_PARAM This is automatically added to a Validator's resources as a validation is being processed. If this class name is used when defining a method signature for a pluggable validator, the current ValidatorAction will be passed into the validation method.
    org.apache.commons.validator.Field Validator.FIELD_PARAM This is automatically added to a Validator's resources as a validation is being processed. If this class name is used when defining a method signature for a pluggable validator, the current Field will be passed into the validation method.

    Usage Example

    This is a basic example setting up a required validator for a name bean. This example is a working unit test (reference org.apache.commons.validator.RequiredNameTest and validator-name-required.xml located under validator/src/test).

    Create an xml file with your validator and validation rules. Setup your required validator in your xml file.

    XML Example
    Validator Example
    Pluggable Validator Example

    XML Example

    Definition of a 'required' pluggable validator.

    <form-validation>
       <global>
           <validator name="required"
              classname="org.apache.commons.validator.TestValidator"
              method="validateRequired"
              methodParams="java.lang.Object, org.apache.commons.validator.Field"/>
        </global>
        <formset>
        </formset>
    </form-validation>

    Add validation rules to require a first name and a last name.

    <form-validation>
       <global>
           <validator name="required"
              classname="org.apache.commons.validator.TestValidator"
              method="validateRequired"
              methodParams="java.lang.Object, org.apache.commons.validator.Field"/>
        </global>
        <formset>
           <form name="nameForm">
              <field property="firstName" depends="required">
                 <arg0 key="nameForm.firstname.displayname"/>
              </field>
              <field property="lastName" depends="required">
                 <arg0 key="nameForm.lastname.displayname"/>
              </field>
           </form>
        </formset>
    </form-validation>

    Validator Example

    Excerpts from org.apache.commons.validator.RequiredNameTest

    InputStream in = this.getClass().getResourceAsStream("validator-name-required.xml");

    // Create an instance of ValidatorResources to
    // initialize from an xml file.
    ValidatorResources resources = new ValidatorResources(in);

    // Create bean to run test on.
    Name name = new Name();

    // Construct validator based on the loaded resources
    // and the form key
    Validator validator = new Validator(resources, "nameForm");
    // add the name bean to the validator as a resource
    // for the validations to be performed on.
    validator.setParameter(Validator.BEAN_PARAM, name);

    // Get results of the validation.
    Map results = null;

    // throws ValidatorException,
    // but aren't catching for example
    results = validator.validate();

    if (results.get("firstName") == null) {
        // no error
    } else {
        // number of errors for first name     int errors = ((Integer)results.get("firstName")).intValue();
    }

    Pluggable Validator Example

    Validation method defined in the 'required' pluggable validator (excerpt from org.apache.commons.validator.TestValidator).

    public static boolean validateRequired(Object bean, Field field) {
        String value = ValidatorUtil.getValueAsString(bean, field.getProperty());
        return GenericValidator.isBlankOrNull(value);
    }

    ././@LongLink100644 0 0 157 11711231552 10254 Lustar 0 0 commons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/routines/AbstractCalendarValidator.javacommons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/routines/AbstractCalendarVali100644 765 0 37673 11711227701 34752 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines; import java.text.DateFormatSymbols; import java.text.Format; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Locale; import java.util.TimeZone; /** *

    Abstract class for Date/Time/Calendar validation.

    * *

    This is a base class for building Date / Time * Validators using format parsing.

    * * @version $Revision: 1227719 $ $Date: 2012-01-05 18:45:51 +0100 (Thu, 05 Jan 2012) $ * @since Validator 1.3.0 */ public abstract class AbstractCalendarValidator extends AbstractFormatValidator { private static final long serialVersionUID = -1410008585975827379L; private final int dateStyle; private final int timeStyle; /** * Construct an instance with the specified strict, * time and date style parameters. * * @param strict true if strict * Format parsing should be used. * @param dateStyle the date style to use for Locale validation. * @param timeStyle the time style to use for Locale validation. */ public AbstractCalendarValidator(boolean strict, int dateStyle, int timeStyle) { super(strict); this.dateStyle = dateStyle; this.timeStyle = timeStyle; } /** *

    Validate using the specified Locale. * * @param value The value validation is being performed on. * @param pattern The pattern used to format the value. * @param locale The locale to use for the Format, defaults to the default * @return true if the value is valid. */ public boolean isValid(String value, String pattern, Locale locale) { Object parsedValue = parse(value, pattern, locale, (TimeZone)null); return (parsedValue == null ? false : true); } /** *

    Format an object into a String using * the default Locale.

    * * @param value The value validation is being performed on. * @param timeZone The Time Zone used to format the date, * system default if null (unless value is a Calendar. * @return The value formatted as a String. */ public String format(Object value, TimeZone timeZone) { return format(value, (String)null, (Locale)null, timeZone); } /** *

    Format an object into a String using * the specified pattern.

    * * @param value The value validation is being performed on. * @param pattern The pattern used to format the value. * @param timeZone The Time Zone used to format the date, * system default if null (unless value is a Calendar. * @return The value formatted as a String. */ public String format(Object value, String pattern, TimeZone timeZone) { return format(value, pattern, (Locale)null, timeZone); } /** *

    Format an object into a String using * the specified Locale.

    * * @param value The value validation is being performed on. * @param locale The locale to use for the Format. * @param timeZone The Time Zone used to format the date, * system default if null (unless value is a Calendar. * @return The value formatted as a String. */ public String format(Object value, Locale locale, TimeZone timeZone) { return format(value, (String)null, locale, timeZone); } /** *

    Format an object using the specified pattern and/or * Locale. * * @param value The value validation is being performed on. * @param pattern The pattern used to format the value. * @param locale The locale to use for the Format. * @return The value formatted as a String. */ public String format(Object value, String pattern, Locale locale) { return format(value, pattern, locale, (TimeZone)null); } /** *

    Format an object using the specified pattern and/or * Locale. * * @param value The value validation is being performed on. * @param pattern The pattern used to format the value. * @param locale The locale to use for the Format. * @param timeZone The Time Zone used to format the date, * system default if null (unless value is a Calendar. * @return The value formatted as a String. */ public String format(Object value, String pattern, Locale locale, TimeZone timeZone) { DateFormat formatter = (DateFormat)getFormat(pattern, locale); if (timeZone != null) { formatter.setTimeZone(timeZone); } else if (value instanceof Calendar) { formatter.setTimeZone(((Calendar)value).getTimeZone()); } return format(value, formatter); } /** *

    Format a value with the specified DateFormat.

    * * @param value The value to be formatted. * @param formatter The Format to use. * @return The formatted value. */ protected String format(Object value, Format formatter) { if (value == null) { return null; } else if (value instanceof Calendar) { value = ((Calendar)value).getTime(); } return formatter.format(value); } /** *

    Checks if the value is valid against a specified pattern.

    * * @param value The value validation is being performed on. * @param pattern The pattern used to validate the value against, or the * default for the Locale if null. * @param locale The locale to use for the date format, system default if null. * @param timeZone The Time Zone used to parse the date, system default if null. * @return The parsed value if valid or null if invalid. */ protected Object parse(String value, String pattern, Locale locale, TimeZone timeZone) { value = (value == null ? null : value.trim()); if (value == null || value.length() == 0) { return null; } DateFormat formatter = (DateFormat)getFormat(pattern, locale); if (timeZone != null) { formatter.setTimeZone(timeZone); } return parse(value, formatter); } /** *

    Process the parsed value, performing any further validation * and type conversion required.

    * * @param value The parsed object created. * @param formatter The Format used to parse the value with. * @return The parsed value converted to the appropriate type * if valid or null if invalid. */ protected abstract Object processParsedValue(Object value, Format formatter); /** *

    Returns a DateFormat for the specified pattern * and/or Locale.

    * * @param pattern The pattern used to validate the value against or * null to use the default for the Locale. * @param locale The locale to use for the currency format, system default if null. * @return The DateFormat to created. */ protected Format getFormat(String pattern, Locale locale) { DateFormat formatter = null; boolean usePattern = (pattern != null && pattern.length() > 0); if (!usePattern) { formatter = (DateFormat)getFormat(locale); } else if (locale == null) { formatter = new SimpleDateFormat(pattern); } else { DateFormatSymbols symbols = new DateFormatSymbols(locale); formatter = new SimpleDateFormat(pattern, symbols); } formatter.setLenient(false); return formatter; } /** *

    Returns a DateFormat for the specified Locale.

    * * @param locale The locale a DateFormat is required for, * system default if null. * @return The DateFormat to created. */ protected Format getFormat(Locale locale) { DateFormat formatter = null; if (dateStyle >= 0 && timeStyle >= 0) { if (locale == null) { formatter = DateFormat.getDateTimeInstance(dateStyle, timeStyle); } else { formatter = DateFormat.getDateTimeInstance(dateStyle, timeStyle, locale); } } else if (timeStyle >= 0) { if (locale == null) { formatter = DateFormat.getTimeInstance(timeStyle); } else { formatter = DateFormat.getTimeInstance(timeStyle, locale); } } else { int useDateStyle = dateStyle >= 0 ? dateStyle : DateFormat.SHORT; if (locale == null) { formatter = DateFormat.getDateInstance(useDateStyle); } else { formatter = DateFormat.getDateInstance(useDateStyle, locale); } } formatter.setLenient(false); return formatter; } /** *

    Compares a calendar value to another, indicating whether it is * equal, less then or more than at a specified level.

    * * @param value The Calendar value. * @param compare The Calendar to check the value against. * @param field The field level to compare to - e.g. specifying * Calendar.MONTH will compare the year and month * portions of the calendar. * @return Zero if the first value is equal to the second, -1 * if it is less than the second or +1 if it is greater than the second. */ protected int compare(Calendar value, Calendar compare, int field) { int result = 0; // Compare Year result = calculateCompareResult(value, compare, Calendar.YEAR); if (result != 0 || field == Calendar.YEAR) { return result; } // Compare Week of Year if (field == Calendar.WEEK_OF_YEAR) { return calculateCompareResult(value, compare, Calendar.WEEK_OF_YEAR); } // Compare Day of the Year if (field == Calendar.DAY_OF_YEAR) { return calculateCompareResult(value, compare, Calendar.DAY_OF_YEAR); } // Compare Month result = calculateCompareResult(value, compare, Calendar.MONTH); if (result != 0 || field == Calendar.MONTH) { return result; } // Compare Week of Month if (field == Calendar.WEEK_OF_MONTH) { return calculateCompareResult(value, compare, Calendar.WEEK_OF_MONTH); } // Compare Date result = calculateCompareResult(value, compare, Calendar.DATE); if (result != 0 || (field == Calendar.DATE || field == Calendar.DAY_OF_WEEK || field == Calendar.DAY_OF_WEEK_IN_MONTH)) { return result; } // Compare Time fields return compareTime(value, compare, field); } /** *

    Compares a calendar time value to another, indicating whether it is * equal, less then or more than at a specified level.

    * * @param value The Calendar value. * @param compare The Calendar to check the value against. * @param field The field level to compare to - e.g. specifying * Calendar.MINUTE will compare the hours and minutes * portions of the calendar. * @return Zero if the first value is equal to the second, -1 * if it is less than the second or +1 if it is greater than the second. */ protected int compareTime(Calendar value, Calendar compare, int field) { int result = 0; // Compare Hour result = calculateCompareResult(value, compare, Calendar.HOUR_OF_DAY); if (result != 0 || (field == Calendar.HOUR || field == Calendar.HOUR_OF_DAY)) { return result; } // Compare Minute result = calculateCompareResult(value, compare, Calendar.MINUTE); if (result != 0 || field == Calendar.MINUTE) { return result; } // Compare Second result = calculateCompareResult(value, compare, Calendar.SECOND); if (result != 0 || field == Calendar.SECOND) { return result; } // Compare Milliseconds if (field == Calendar.MILLISECOND) { return calculateCompareResult(value, compare, Calendar.MILLISECOND); } throw new IllegalArgumentException("Invalid field: " + field); } /** *

    Compares a calendar's quarter value to another, indicating whether it is * equal, less then or more than the specified quarter.

    * * @param value The Calendar value. * @param compare The Calendar to check the value against. * @param monthOfFirstQuarter The month that the first quarter starts. * @return Zero if the first quarter is equal to the second, -1 * if it is less than the second or +1 if it is greater than the second. */ protected int compareQuarters(Calendar value, Calendar compare, int monthOfFirstQuarter) { int valueQuarter = calculateQuarter(value, monthOfFirstQuarter); int compareQuarter = calculateQuarter(compare, monthOfFirstQuarter); if (valueQuarter < compareQuarter) { return -1; } else if (valueQuarter > compareQuarter) { return 1; } else { return 0; } } /** *

    Calculate the quarter for the specified Calendar.

    * * @param calendar The Calendar value. * @param monthOfFirstQuarter The month that the first quarter starts. * @return The calculated quarter. */ private int calculateQuarter(Calendar calendar, int monthOfFirstQuarter) { // Add Year int year = calendar.get(Calendar.YEAR); int month = (calendar.get(Calendar.MONTH) + 1); int relativeMonth = (month >= monthOfFirstQuarter) ? (month - monthOfFirstQuarter) : (month + (12 - monthOfFirstQuarter)); int quarter = ((relativeMonth / 3) + 1); // adjust the year if the quarter doesn't start in January if (month < monthOfFirstQuarter) { --year; } return (year * 10) + quarter; } /** *

    Compares the field from two calendars indicating whether the field for the * first calendar is equal to, less than or greater than the field from the * second calendar. * * @param value The Calendar value. * @param compare The Calendar to check the value against. * @param field The field to compare for the calendars. * @return Zero if the first calendar's field is equal to the seconds, -1 * if it is less than the seconds or +1 if it is greater than the seconds. */ private int calculateCompareResult(Calendar value, Calendar compare, int field) { int difference = value.get(field) - compare.get(field); if (difference < 0) { return -1; } else if (difference > 0) { return 1; } else { return 0; } } } ././@LongLink100644 0 0 155 11711231552 10252 Lustar 0 0 commons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/routines/AbstractFormatValidator.javacommons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/routines/AbstractFormatValida100644 765 0 17253 11711227701 34766 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines; import java.text.Format; import java.text.ParsePosition; import java.util.Locale; import java.io.Serializable; /** *

    Abstract class for Format based Validation.

    * *

    This is a base class for building Date and Number * Validators using format parsing.

    * * @version $Revision: 1227719 $ $Date: 2012-01-05 18:45:51 +0100 (Thu, 05 Jan 2012) $ * @since Validator 1.3.0 */ public abstract class AbstractFormatValidator implements Serializable { private static final long serialVersionUID = -4690687565200568258L; private final boolean strict; /** * Construct an instance with the specified strict setting. * * @param strict true if strict * Format parsing should be used. */ public AbstractFormatValidator(boolean strict) { this.strict = strict; } /** *

    Indicates whether validated values should adhere * strictly to the Format used.

    * *

    Typically implementations of Format * ignore invalid characters at the end of the value * and just stop parsing. For example parsing a date * value of 01/01/20x0 using a pattern * of dd/MM/yyyy will result in a year * of 20 if strict is set * to false, whereas setting strict * to true will cause this value to fail * validation.

    * * @return true if strict Format * parsing should be used. */ public boolean isStrict() { return strict; } /** *

    Validate using the default Locale. * * @param value The value validation is being performed on. * @return true if the value is valid. */ public boolean isValid(String value) { return isValid(value, (String)null, (Locale)null); } /** *

    Validate using the specified pattern. * * @param value The value validation is being performed on. * @param pattern The pattern used to validate the value against. * @return true if the value is valid. */ public boolean isValid(String value, String pattern) { return isValid(value, pattern, (Locale)null); } /** *

    Validate using the specified Locale. * * @param value The value validation is being performed on. * @param locale The locale to use for the Format, defaults to the default * @return true if the value is valid. */ public boolean isValid(String value, Locale locale) { return isValid(value, (String)null, locale); } /** *

    Validate using the specified pattern and/or Locale. * * @param value The value validation is being performed on. * @param pattern The pattern used to format the value. * @param locale The locale to use for the Format, defaults to the default * @return true if the value is valid. */ public abstract boolean isValid(String value, String pattern, Locale locale); /** *

    Format an object into a String using * the default Locale.

    * * @param value The value validation is being performed on. * @return The value formatted as a String. */ public String format(Object value) { return format(value, (String)null, (Locale)null); } /** *

    Format an object into a String using * the specified pattern.

    * * @param value The value validation is being performed on. * @param pattern The pattern used to format the value. * @return The value formatted as a String. */ public String format(Object value, String pattern) { return format(value, pattern, (Locale)null); } /** *

    Format an object into a String using * the specified Locale.

    * * @param value The value validation is being performed on. * @param locale The locale to use for the Format. * @return The value formatted as a String. */ public String format(Object value, Locale locale) { return format(value, (String)null, locale); } /** *

    Format an object using the specified pattern and/or * Locale. * * @param value The value validation is being performed on. * @param pattern The pattern used to format the value. * @param locale The locale to use for the Format. * @return The value formatted as a String. */ public String format(Object value, String pattern, Locale locale) { Format formatter = getFormat(pattern, locale); return format(value, formatter); } /** *

    Format a value with the specified Format.

    * * @param value The value to be formatted. * @param formatter The Format to use. * @return The formatted value. */ protected String format(Object value, Format formatter) { return formatter.format(value); } /** *

    Parse the value with the specified Format.

    * * @param value The value to be parsed. * @param formatter The Format to parse the value with. * @return The parsed value if valid or null if invalid. */ protected Object parse(String value, Format formatter) { ParsePosition pos = new ParsePosition(0); Object parsedValue = formatter.parseObject(value, pos); if (pos.getErrorIndex() > -1) { return null; } if (isStrict() && pos.getIndex() < value.length()) { return null; } if (parsedValue != null) { parsedValue = processParsedValue(parsedValue, formatter); } return parsedValue; } /** *

    Process the parsed value, performing any further validation * and type conversion required.

    * * @param value The parsed object created. * @param formatter The Format used to parse the value with. * @return The parsed value converted to the appropriate type * if valid or null if invalid. */ protected abstract Object processParsedValue(Object value, Format formatter); /** *

    Returns a Format for the specified pattern * and/or Locale.

    * * @param pattern The pattern used to validate the value against or * null to use the default for the Locale. * @param locale The locale to use for the currency format, system default if null. * @return The NumberFormat to created. */ protected abstract Format getFormat(String pattern, Locale locale); } ././@LongLink100644 0 0 155 11711231552 10252 Lustar 0 0 commons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/routines/AbstractNumberValidator.javacommons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/routines/AbstractNumberValida100644 765 0 23113 11711227701 34756 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines; import java.text.DecimalFormatSymbols; import java.text.Format; import java.text.NumberFormat; import java.text.DecimalFormat; import java.util.Locale; /** *

    Abstract class for Number Validation.

    * *

    This is a base class for building Number * Validators using format parsing.

    * * @version $Revision: 1227719 $ $Date: 2012-01-05 18:45:51 +0100 (Thu, 05 Jan 2012) $ * @since Validator 1.3.0 */ public abstract class AbstractNumberValidator extends AbstractFormatValidator { private static final long serialVersionUID = -3088817875906765463L; /** Standard NumberFormat type */ public static final int STANDARD_FORMAT = 0; /** Currency NumberFormat type */ public static final int CURRENCY_FORMAT = 1; /** Percent NumberFormat type */ public static final int PERCENT_FORMAT = 2; private final boolean allowFractions; private final int formatType; /** * Construct an instance with specified strict * and decimal parameters. * * @param strict true if strict * Format parsing should be used. * @param formatType The NumberFormat type to * create for validation, default is STANDARD_FORMAT. * @param allowFractions true if fractions are * allowed or false if integers only. */ public AbstractNumberValidator(boolean strict, int formatType, boolean allowFractions) { super(strict); this.allowFractions = allowFractions; this.formatType = formatType; } /** *

    Indicates whether the number being validated is * a decimal or integer.

    * * @return true if decimals are allowed * or false if the number is an integer. */ public boolean isAllowFractions() { return allowFractions; } /** *

    Indicates the type of NumberFormat created * by this validator instance.

    * * @return the format type created. */ public int getFormatType() { return formatType; } /** *

    Validate using the specified Locale.

    * * @param value The value validation is being performed on. * @param pattern The pattern used to validate the value against, or the * default for the Locale if null. * @param locale The locale to use for the date format, system default if null. * @return true if the value is valid. */ public boolean isValid(String value, String pattern, Locale locale) { Object parsedValue = parse(value, pattern, locale); return (parsedValue == null ? false : true); } /** * Check if the value is within a specified range. * * @param value The value validation is being performed on. * @param min The minimum value of the range. * @param max The maximum value of the range. * @return true if the value is within the * specified range. */ public boolean isInRange(Number value, Number min, Number max) { return (minValue(value, min) && maxValue(value, max)); } /** * Check if the value is greater than or equal to a minimum. * * @param value The value validation is being performed on. * @param min The minimum value. * @return true if the value is greater than * or equal to the minimum. */ public boolean minValue(Number value, Number min) { if (isAllowFractions()) { return (value.doubleValue() >= min.doubleValue()); } else { return (value.longValue() >= min.longValue()); } } /** * Check if the value is less than or equal to a maximum. * * @param value The value validation is being performed on. * @param max The maximum value. * @return true if the value is less than * or equal to the maximum. */ public boolean maxValue(Number value, Number max) { if (isAllowFractions()) { return (value.doubleValue() <= max.doubleValue()); } else { return (value.longValue() <= max.longValue()); } } /** *

    Parse the value using the specified pattern.

    * * @param value The value validation is being performed on. * @param pattern The pattern used to validate the value against, or the * default for the Locale if null. * @param locale The locale to use for the date format, system default if null. * @return The parsed value if valid or null if invalid. */ protected Object parse(String value, String pattern, Locale locale) { value = (value == null ? null : value.trim()); if (value == null || value.length() == 0) { return null; } Format formatter = getFormat(pattern, locale); return parse(value, formatter); } /** *

    Process the parsed value, performing any further validation * and type conversion required.

    * * @param value The parsed object created. * @param formatter The Format used to parse the value with. * @return The parsed value converted to the appropriate type * if valid or null if invalid. */ protected abstract Object processParsedValue(Object value, Format formatter); /** *

    Returns a NumberFormat for the specified pattern * and/or Locale.

    * * @param pattern The pattern used to validate the value against or * null to use the default for the Locale. * @param locale The locale to use for the currency format, system default if null. * @return The NumberFormat to created. */ protected Format getFormat(String pattern, Locale locale) { NumberFormat formatter = null; boolean usePattern = (pattern != null && pattern.length() > 0); if (!usePattern) { formatter = (NumberFormat)getFormat(locale); } else if (locale == null) { formatter = new DecimalFormat(pattern); } else { DecimalFormatSymbols symbols = new DecimalFormatSymbols(locale); formatter = new DecimalFormat(pattern, symbols); } if (determineScale(formatter) == 0) { formatter.setParseIntegerOnly(true); } return formatter; } /** *

    Returns the multiplier of the NumberFormat.

    * * @param format The NumberFormat to determine the * multiplier of. * @return The multiplying factor for the format.. */ protected int determineScale(NumberFormat format) { if (!isStrict()) { return -1; } if (!isAllowFractions() || format.isParseIntegerOnly()) { return 0; } int minimumFraction = format.getMinimumFractionDigits(); int maximumFraction = format.getMaximumFractionDigits(); if (minimumFraction != maximumFraction) { return -1; } int scale = minimumFraction; if (format instanceof DecimalFormat) { int multiplier = ((DecimalFormat)format).getMultiplier(); if (multiplier == 100) { scale += 2; } else if (multiplier == 1000) { scale += 3; } } else if (formatType == PERCENT_FORMAT) { scale += 2; } return scale; } /** *

    Returns a NumberFormat for the specified Locale.

    * * @param locale The locale a NumberFormat is required for, * system default if null. * @return The NumberFormat to created. */ protected Format getFormat(Locale locale) { NumberFormat formatter = null; switch (formatType) { case CURRENCY_FORMAT: if (locale == null) { formatter = NumberFormat.getCurrencyInstance(); } else { formatter = NumberFormat.getCurrencyInstance(locale); } break; case PERCENT_FORMAT: if (locale == null) { formatter = NumberFormat.getPercentInstance(); } else { formatter = NumberFormat.getPercentInstance(locale); } break; default: if (locale == null) { formatter = NumberFormat.getInstance(); } else { formatter = NumberFormat.getInstance(locale); } break; } return formatter; } } ././@LongLink100644 0 0 151 11711231552 10246 Lustar 0 0 commons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/routines/BigDecimalValidator.javacommons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/routines/BigDecimalValidator.100644 765 0 22441 11711227701 34630 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines; import java.math.BigDecimal; import java.text.Format; import java.text.NumberFormat; import java.util.Locale; /** *

    BigDecimal Validation and Conversion routines (java.math.BigDecimal).

    * *

    This validator provides a number of methods for * validating/converting a String value to * a BigDecimal using java.text.NumberFormat * to parse either:

    *
      *
    • using the default format for the default Locale
    • *
    • using a specified pattern with the default Locale
    • *
    • using the default format for a specified Locale
    • *
    • using a specified pattern with a specified Locale
    • *
    * *

    Use one of the isValid() methods to just validate or * one of the validate() methods to validate and receive a * converted BigDecimal value.

    * *

    Fraction/decimal values are automatically trimmed to the appropriate length.

    * *

    Once a value has been sucessfully converted the following * methods can be used to perform minimum, maximum and range checks:

    *
      *
    • minValue() checks whether the value is greater * than or equal to a specified minimum.
    • *
    • maxValue() checks whether the value is less * than or equal to a specified maximum.
    • *
    • isInRange() checks whether the value is within * a specified range of values.
    • *
    * *

    So that the same mechanism used for parsing an input value * for validation can be used to format output, corresponding * format() methods are also provided. That is you can * format either:

    *
      *
    • using the default format for the default Locale
    • *
    • using a specified pattern with the default Locale
    • *
    • using the default format for a specified Locale
    • *
    • using a specified pattern with a specified Locale
    • *
    * * @version $Revision: 1227719 $ $Date: 2012-01-05 18:45:51 +0100 (Thu, 05 Jan 2012) $ * @since Validator 1.3.0 */ public class BigDecimalValidator extends AbstractNumberValidator { private static final long serialVersionUID = -670320911490506772L; private static final BigDecimalValidator VALIDATOR = new BigDecimalValidator(); /** * Return a singleton instance of this validator. * @return A singleton instance of the BigDecimalValidator. */ public static BigDecimalValidator getInstance() { return VALIDATOR; } /** * Construct a strict instance. */ public BigDecimalValidator() { this(true); } /** *

    Construct an instance with the specified strict setting.

    * * @param strict true if strict * Format parsing should be used. */ public BigDecimalValidator(boolean strict) { this(strict, STANDARD_FORMAT, true); } /** *

    Construct an instance with the specified strict setting * and format type.

    * *

    The formatType specified what type of * NumberFormat is created - valid types * are:

    *
      *
    • AbstractNumberValidator.STANDARD_FORMAT -to create * standard number formats (the default).
    • *
    • AbstractNumberValidator.CURRENCY_FORMAT -to create * currency number formats.
    • *
    • AbstractNumberValidator.PERCENT_FORMAT -to create * percent number formats (the default).
    • *
    * * @param strict true if strict * Format parsing should be used. * @param formatType The NumberFormat type to * create for validation, default is STANDARD_FORMAT. * @param allowFractions true if fractions are * allowed or false if integers only. */ protected BigDecimalValidator(boolean strict, int formatType, boolean allowFractions) { super(strict, formatType, allowFractions); } /** *

    Validate/convert a BigDecimal using the default * Locale. * * @param value The value validation is being performed on. * @return The parsed BigDecimal if valid or null * if invalid. */ public BigDecimal validate(String value) { return (BigDecimal)parse(value, (String)null, (Locale)null); } /** *

    Validate/convert a BigDecimal using the * specified pattern. * * @param value The value validation is being performed on. * @param pattern The pattern used to validate the value against, or the * default for the Locale if null. * @return The parsed BigDecimal if valid or null if invalid. */ public BigDecimal validate(String value, String pattern) { return (BigDecimal)parse(value, pattern, (Locale)null); } /** *

    Validate/convert a BigDecimal using the * specified Locale. * * @param value The value validation is being performed on. * @param locale The locale to use for the number format, system default if null. * @return The parsed BigDecimal if valid or null if invalid. */ public BigDecimal validate(String value, Locale locale) { return (BigDecimal)parse(value, (String)null, locale); } /** *

    Validate/convert a BigDecimal using the * specified pattern and/ or Locale. * * @param value The value validation is being performed on. * @param pattern The pattern used to validate the value against, or the * default for the Locale if null. * @param locale The locale to use for the date format, system default if null. * @return The parsed BigDecimal if valid or null if invalid. */ public BigDecimal validate(String value, String pattern, Locale locale) { return (BigDecimal)parse(value, pattern, locale); } /** * Check if the value is within a specified range. * * @param value The Number value to check. * @param min The minimum value of the range. * @param max The maximum value of the range. * @return true if the value is within the * specified range. */ public boolean isInRange(BigDecimal value, double min, double max) { return (value.doubleValue() >= min && value.doubleValue() <= max); } /** * Check if the value is greater than or equal to a minimum. * * @param value The value validation is being performed on. * @param min The minimum value. * @return true if the value is greater than * or equal to the minimum. */ public boolean minValue(BigDecimal value, double min) { return (value.doubleValue() >= min); } /** * Check if the value is less than or equal to a maximum. * * @param value The value validation is being performed on. * @param max The maximum value. * @return true if the value is less than * or equal to the maximum. */ public boolean maxValue(BigDecimal value, double max) { return (value.doubleValue() <= max); } /** * Convert the parsed value to a BigDecimal. * * @param value The parsed Number object created. * @param formatter The Format used to parse the value with. * @return The parsed Number converted to a * BigDecimal. */ protected Object processParsedValue(Object value, Format formatter) { BigDecimal decimal = null; if (value instanceof Long) { decimal = BigDecimal.valueOf(((Long)value).longValue()); } else { decimal = new BigDecimal(value.toString()); } int scale = determineScale((NumberFormat)formatter); if (scale >= 0) { decimal = decimal.setScale(scale, BigDecimal.ROUND_DOWN); } return decimal; } } ././@LongLink100644 0 0 151 11711231552 10246 Lustar 0 0 commons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/routines/BigIntegerValidator.javacommons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/routines/BigIntegerValidator.100644 765 0 20435 11711227701 34670 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines; import java.math.BigInteger; import java.text.Format; import java.util.Locale; /** *

    BigInteger Validation and Conversion routines (java.math.BigInteger).

    * *

    This validator provides a number of methods for * validating/converting a String value to * a BigInteger using java.text.NumberFormat * to parse either:

    *
      *
    • using the default format for the default Locale
    • *
    • using a specified pattern with the default Locale
    • *
    • using the default format for a specified Locale
    • *
    • using a specified pattern with a specified Locale
    • *
    * *

    Use one of the isValid() methods to just validate or * one of the validate() methods to validate and receive a * converted BigInteger value.

    * *

    Once a value has been sucessfully converted the following * methods can be used to perform minimum, maximum and range checks:

    *
      *
    • minValue() checks whether the value is greater * than or equal to a specified minimum.
    • *
    • maxValue() checks whether the value is less * than or equal to a specified maximum.
    • *
    • isInRange() checks whether the value is within * a specified range of values.
    • *
    * *

    So that the same mechanism used for parsing an input value * for validation can be used to format output, corresponding * format() methods are also provided. That is you can * format either:

    *
      *
    • using the default format for the default Locale
    • *
    • using a specified pattern with the default Locale
    • *
    • using the default format for a specified Locale
    • *
    • using a specified pattern with a specified Locale
    • *
    * * @version $Revision: 1227719 $ $Date: 2012-01-05 18:45:51 +0100 (Thu, 05 Jan 2012) $ * @since Validator 1.3.0 */ public class BigIntegerValidator extends AbstractNumberValidator { private static final long serialVersionUID = 6713144356347139988L; private static final BigIntegerValidator VALIDATOR = new BigIntegerValidator(); /** * Return a singleton instance of this validator. * @return A singleton instance of the BigIntegerValidator. */ public static BigIntegerValidator getInstance() { return VALIDATOR; } /** * Construct a strict instance. */ public BigIntegerValidator() { this(true, STANDARD_FORMAT); } /** *

    Construct an instance with the specified strict setting * and format type.

    * *

    The formatType specified what type of * NumberFormat is created - valid types * are:

    *
      *
    • AbstractNumberValidator.STANDARD_FORMAT -to create * standard number formats (the default).
    • *
    • AbstractNumberValidator.CURRENCY_FORMAT -to create * currency number formats.
    • *
    • AbstractNumberValidator.PERCENT_FORMAT -to create * percent number formats (the default).
    • *
    * * @param strict true if strict * Format parsing should be used. * @param formatType The NumberFormat type to * create for validation, default is STANDARD_FORMAT. */ public BigIntegerValidator(boolean strict, int formatType) { super(strict, formatType, false); } /** *

    Validate/convert a BigInteger using the default * Locale. * * @param value The value validation is being performed on. * @return The parsed BigInteger if valid or null * if invalid. */ public BigInteger validate(String value) { return (BigInteger)parse(value, (String)null, (Locale)null); } /** *

    Validate/convert a BigInteger using the * specified pattern. * * @param value The value validation is being performed on. * @param pattern The pattern used to validate the value against. * @return The parsed BigInteger if valid or null if invalid. */ public BigInteger validate(String value, String pattern) { return (BigInteger)parse(value, pattern, (Locale)null); } /** *

    Validate/convert a BigInteger using the * specified Locale. * * @param value The value validation is being performed on. * @param locale The locale to use for the number format, system default if null. * @return The parsed BigInteger if valid or null if invalid. */ public BigInteger validate(String value, Locale locale) { return (BigInteger)parse(value, (String)null, locale); } /** *

    Validate/convert a BigInteger using the * specified pattern and/ or Locale. * * @param value The value validation is being performed on. * @param pattern The pattern used to validate the value against, or the * default for the Locale if null. * @param locale The locale to use for the date format, system default if null. * @return The parsed BigInteger if valid or null if invalid. */ public BigInteger validate(String value, String pattern, Locale locale) { return (BigInteger)parse(value, pattern, locale); } /** * Check if the value is within a specified range. * * @param value The Number value to check. * @param min The minimum value of the range. * @param max The maximum value of the range. * @return true if the value is within the * specified range. */ public boolean isInRange(BigInteger value, long min, long max) { return (value.longValue() >= min && value.longValue() <= max); } /** * Check if the value is greater than or equal to a minimum. * * @param value The value validation is being performed on. * @param min The minimum value. * @return true if the value is greater than * or equal to the minimum. */ public boolean minValue(BigInteger value, long min) { return (value.longValue() >= min); } /** * Check if the value is less than or equal to a maximum. * * @param value The value validation is being performed on. * @param max The maximum value. * @return true if the value is less than * or equal to the maximum. */ public boolean maxValue(BigInteger value, long max) { return (value.longValue() <= max); } /** * Convert the parsed value to a BigInteger. * * @param value The parsed Number object created. * @param formatter The Format used to parse the value with. * @return The parsed Number converted to a * BigInteger. */ protected Object processParsedValue(Object value, Format formatter) { return BigInteger.valueOf(((Number)value).longValue()); } } commons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/routines/ByteValidator.java100644 765 0 22765 11711227701 34426 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines; import java.text.Format; import java.util.Locale; /** *

    Byte Validation and Conversion routines (java.lang.Byte).

    * *

    This validator provides a number of methods for * validating/converting a String value to * a Byte using java.text.NumberFormat * to parse either:

    *
      *
    • using the default format for the default Locale
    • *
    • using a specified pattern with the default Locale
    • *
    • using the default format for a specified Locale
    • *
    • using a specified pattern with a specified Locale
    • *
    * *

    Use one of the isValid() methods to just validate or * one of the validate() methods to validate and receive a * converted Byte value.

    * *

    Once a value has been sucessfully converted the following * methods can be used to perform minimum, maximum and range checks:

    *
      *
    • minValue() checks whether the value is greater * than or equal to a specified minimum.
    • *
    • maxValue() checks whether the value is less * than or equal to a specified maximum.
    • *
    • isInRange() checks whether the value is within * a specified range of values.
    • *
    * *

    So that the same mechanism used for parsing an input value * for validation can be used to format output, corresponding * format() methods are also provided. That is you can * format either:

    *
      *
    • using the default format for the default Locale
    • *
    • using a specified pattern with the default Locale
    • *
    • using the default format for a specified Locale
    • *
    • using a specified pattern with a specified Locale
    • *
    * * @version $Revision: 1227719 $ $Date: 2012-01-05 18:45:51 +0100 (Thu, 05 Jan 2012) $ * @since Validator 1.3.0 */ public class ByteValidator extends AbstractNumberValidator { private static final long serialVersionUID = 7001640945881854649L; private static final ByteValidator VALIDATOR = new ByteValidator(); /** * Return a singleton instance of this validator. * @return A singleton instance of the ByteValidator. */ public static ByteValidator getInstance() { return VALIDATOR; } /** * Construct a strict instance. */ public ByteValidator() { this(true, STANDARD_FORMAT); } /** *

    Construct an instance with the specified strict setting * and format type.

    * *

    The formatType specified what type of * NumberFormat is created - valid types * are:

    *
      *
    • AbstractNumberValidator.STANDARD_FORMAT -to create * standard number formats (the default).
    • *
    • AbstractNumberValidator.CURRENCY_FORMAT -to create * currency number formats.
    • *
    • AbstractNumberValidator.PERCENT_FORMAT -to create * percent number formats (the default).
    • *
    * * @param strict true if strict * Format parsing should be used. * @param formatType The NumberFormat type to * create for validation, default is STANDARD_FORMAT. */ public ByteValidator(boolean strict, int formatType) { super(strict, formatType, false); } /** *

    Validate/convert a Byte using the default * Locale. * * @param value The value validation is being performed on. * @return The parsed Byte if valid or null * if invalid. */ public Byte validate(String value) { return (Byte)parse(value, (String)null, (Locale)null); } /** *

    Validate/convert a Byte using the * specified pattern. * * @param value The value validation is being performed on. * @param pattern The pattern used to validate the value against. * @return The parsed Byte if valid or null if invalid. */ public Byte validate(String value, String pattern) { return (Byte)parse(value, pattern, (Locale)null); } /** *

    Validate/convert a Byte using the * specified Locale. * * @param value The value validation is being performed on. * @param locale The locale to use for the number format, system default if null. * @return The parsed Byte if valid or null if invalid. */ public Byte validate(String value, Locale locale) { return (Byte)parse(value, (String)null, locale); } /** *

    Validate/convert a Byte using the * specified pattern and/ or Locale. * * @param value The value validation is being performed on. * @param pattern The pattern used to validate the value against, or the * default for the Locale if null. * @param locale The locale to use for the date format, system default if null. * @return The parsed Byte if valid or null if invalid. */ public Byte validate(String value, String pattern, Locale locale) { return (Byte)parse(value, pattern, locale); } /** * Check if the value is within a specified range. * * @param value The Number value to check. * @param min The minimum value of the range. * @param max The maximum value of the range. * @return true if the value is within the * specified range. */ public boolean isInRange(byte value, byte min, byte max) { return (value >= min && value <= max); } /** * Check if the value is within a specified range. * * @param value The Number value to check. * @param min The minimum value of the range. * @param max The maximum value of the range. * @return true if the value is within the * specified range. */ public boolean isInRange(Byte value, byte min, byte max) { return isInRange(value.byteValue(), min, max); } /** * Check if the value is greater than or equal to a minimum. * * @param value The value validation is being performed on. * @param min The minimum value. * @return true if the value is greater than * or equal to the minimum. */ public boolean minValue(byte value, byte min) { return (value >= min); } /** * Check if the value is greater than or equal to a minimum. * * @param value The value validation is being performed on. * @param min The minimum value. * @return true if the value is greater than * or equal to the minimum. */ public boolean minValue(Byte value, byte min) { return minValue(value.byteValue(), min); } /** * Check if the value is less than or equal to a maximum. * * @param value The value validation is being performed on. * @param max The maximum value. * @return true if the value is less than * or equal to the maximum. */ public boolean maxValue(byte value, byte max) { return (value <= max); } /** * Check if the value is less than or equal to a maximum. * * @param value The value validation is being performed on. * @param max The maximum value. * @return true if the value is less than * or equal to the maximum. */ public boolean maxValue(Byte value, byte max) { return maxValue(value.byteValue(), max); } /** *

    Perform further validation and convert the Number to * a Byte.

    * * @param value The parsed Number object created. * @param formatter The Format used to parse the value with. * @return The parsed Number converted to a * Byte if valid or null if invalid. */ protected Object processParsedValue(Object value, Format formatter) { long longValue = ((Number)value).longValue(); if (longValue < Byte.MIN_VALUE || longValue > Byte.MAX_VALUE) { return null; } else { return new Byte((byte)longValue); } } } ././@LongLink100644 0 0 147 11711231552 10253 Lustar 0 0 commons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/routines/CalendarValidator.javacommons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/routines/CalendarValidator.ja100644 765 0 34245 11711227701 34701 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines; import java.text.DateFormat; import java.text.Format; import java.util.Calendar; import java.util.Locale; import java.util.TimeZone; /** *

    Calendar Validation and Conversion routines (java.util.Calendar).

    * *

    This validator provides a number of methods for validating/converting * a String date value to a java.util.Calendar using * java.text.DateFormat to parse either:

    *
      *
    • using the default format for the default Locale
    • *
    • using a specified pattern with the default Locale
    • *
    • using the default format for a specified Locale
    • *
    • using a specified pattern with a specified Locale
    • *
    * *

    For each of the above mechanisms, conversion method (i.e the * validate methods) implementations are provided which * either use the default TimeZone or allow the * TimeZone to be specified.

    * *

    Use one of the isValid() methods to just validate or * one of the validate() methods to validate and receive a * converted Calendar value.

    * *

    Implementations of the validate() method are provided * to create Calendar objects for different time zones * if the system default is not appropriate.

    * *

    Alternatively the CalendarValidator's adjustToTimeZone() method * can be used to adjust the TimeZone of the Calendar * object afterwards.

    * *

    Once a value has been sucessfully converted the following * methods can be used to perform various date comparison checks:

    *
      *
    • compareDates() compares the day, month and * year of two calendars, returing 0, -1 or +1 indicating * whether the first date is equal, before or after the second.
    • *
    • compareWeeks() compares the week and * year of two calendars, returing 0, -1 or +1 indicating * whether the first week is equal, before or after the second.
    • *
    • compareMonths() compares the month and * year of two calendars, returing 0, -1 or +1 indicating * whether the first month is equal, before or after the second.
    • *
    • compareQuarters() compares the quarter and * year of two calendars, returing 0, -1 or +1 indicating * whether the first quarter is equal, before or after the second.
    • *
    • compareYears() compares the * year of two calendars, returing 0, -1 or +1 indicating * whether the first year is equal, before or after the second.
    • *
    * *

    So that the same mechanism used for parsing an input value * for validation can be used to format output, corresponding * format() methods are also provided. That is you can * format either:

    *
      *
    • using a specified pattern
    • *
    • using the format for a specified Locale
    • *
    • using the format for the default Locale
    • *
    * * @version $Revision: 1227719 $ $Date: 2012-01-05 18:45:51 +0100 (Thu, 05 Jan 2012) $ * @since Validator 1.3.0 */ public class CalendarValidator extends AbstractCalendarValidator { private static final long serialVersionUID = 9109652318762134167L; private static final CalendarValidator VALIDATOR = new CalendarValidator(); /** * Return a singleton instance of this validator. * @return A singleton instance of the CalendarValidator. */ public static CalendarValidator getInstance() { return VALIDATOR; } /** * Construct a strict instance with short * date style. */ public CalendarValidator() { this(true, DateFormat.SHORT); } /** * Construct an instance with the specified strict * and date style parameters. * * @param strict true if strict * Format parsing should be used. * @param dateStyle the date style to use for Locale validation. */ public CalendarValidator(boolean strict, int dateStyle) { super(strict, dateStyle, -1); } /** *

    Validate/convert a Calendar using the default * Locale and TimeZone. * * @param value The value validation is being performed on. * @return The parsed Calendar if valid or null * if invalid. */ public Calendar validate(String value) { return (Calendar)parse(value, (String)null, (Locale)null, (TimeZone)null); } /** *

    Validate/convert a Calendar using the specified * TimeZone and default Locale. * * @param value The value validation is being performed on. * @param timeZone The Time Zone used to parse the date, system default if null. * @return The parsed Calendar if valid or null * if invalid. */ public Calendar validate(String value, TimeZone timeZone) { return (Calendar)parse(value, (String)null, (Locale)null, timeZone); } /** *

    Validate/convert a Calendar using the specified * pattern and default TimeZone. * * @param value The value validation is being performed on. * @param pattern The pattern used to validate the value against. * @return The parsed Calendar if valid or null if invalid. */ public Calendar validate(String value, String pattern) { return (Calendar)parse(value, pattern, (Locale)null, (TimeZone)null); } /** *

    Validate/convert a Calendar using the specified * pattern and TimeZone. * * @param value The value validation is being performed on. * @param pattern The pattern used to validate the value against. * @param timeZone The Time Zone used to parse the date, system default if null. * @return The parsed Calendar if valid or null if invalid. */ public Calendar validate(String value, String pattern, TimeZone timeZone) { return (Calendar)parse(value, pattern, (Locale)null, timeZone); } /** *

    Validate/convert a Calendar using the specified * Locale and default TimeZone. * * @param value The value validation is being performed on. * @param locale The locale to use for the date format, system default if null. * @return The parsed Calendar if valid or null if invalid. */ public Calendar validate(String value, Locale locale) { return (Calendar)parse(value, (String)null, locale, (TimeZone)null); } /** *

    Validate/convert a Calendar using the specified * Locale and TimeZone. * * @param value The value validation is being performed on. * @param locale The locale to use for the date format, system default if null. * @param timeZone The Time Zone used to parse the date, system default if null. * @return The parsed Calendar if valid or null if invalid. */ public Calendar validate(String value, Locale locale, TimeZone timeZone) { return (Calendar)parse(value, (String)null, locale, timeZone); } /** *

    Validate/convert a Calendar using the specified pattern * and Locale and the default TimeZone. * * @param value The value validation is being performed on. * @param pattern The pattern used to validate the value against, or the * default for the Locale if null. * @param locale The locale to use for the date format, system default if null. * @return The parsed Calendar if valid or null if invalid. */ public Calendar validate(String value, String pattern, Locale locale) { return (Calendar)parse(value, pattern, locale, (TimeZone)null); } /** *

    Validate/convert a Calendar using the specified * pattern, and Locale and TimeZone. * * @param value The value validation is being performed on. * @param pattern The pattern used to validate the value against, or the * default for the Locale if null. * @param locale The locale to use for the date format, system default if null. * @param timeZone The Time Zone used to parse the date, system default if null. * @return The parsed Calendar if valid or null if invalid. */ public Calendar validate(String value, String pattern, Locale locale, TimeZone timeZone) { return (Calendar)parse(value, pattern, locale, timeZone); } /** *

    Adjusts a Calendar's value to a different TimeZone.

    * * @param value The value to adjust. * @param timeZone The new time zone to use to adjust the Calendar to. */ public static void adjustToTimeZone(Calendar value, TimeZone timeZone) { if (value.getTimeZone().hasSameRules(timeZone)) { value.setTimeZone(timeZone); } else { int year = value.get(Calendar.YEAR); int month = value.get(Calendar.MONTH); int date = value.get(Calendar.DATE); int hour = value.get(Calendar.HOUR_OF_DAY); int minute = value.get(Calendar.MINUTE); value.setTimeZone(timeZone); value.set(year, month, date, hour, minute); } } /** *

    Compare Dates (day, month and year - not time).

    * * @param value The Calendar value to check. * @param compare The Calendar to compare the value to. * @return Zero if the dates are equal, -1 if first * date is less than the seconds and +1 if the first * date is greater than. */ public int compareDates(Calendar value, Calendar compare) { return compare(value, compare, Calendar.DATE); } /** *

    Compare Weeks (week and year).

    * * @param value The Calendar value to check. * @param compare The Calendar to compare the value to. * @return Zero if the weeks are equal, -1 if first * parameter's week is less than the seconds and +1 if the first * parameter's week is greater than. */ public int compareWeeks(Calendar value, Calendar compare) { return compare(value, compare, Calendar.WEEK_OF_YEAR); } /** *

    Compare Months (month and year).

    * * @param value The Calendar value to check. * @param compare The Calendar to compare the value to. * @return Zero if the months are equal, -1 if first * parameter's month is less than the seconds and +1 if the first * parameter's month is greater than. */ public int compareMonths(Calendar value, Calendar compare) { return compare(value, compare, Calendar.MONTH); } /** *

    Compare Quarters (quarter and year).

    * * @param value The Calendar value to check. * @param compare The Calendar to check the value against. * @return Zero if the quarters are equal, -1 if first * parameter's quarter is less than the seconds and +1 if the first * parameter's quarter is greater than. */ public int compareQuarters(Calendar value, Calendar compare) { return compareQuarters(value, compare, 1); } /** *

    Compare Quarters (quarter and year).

    * * @param value The Calendar value to check. * @param compare The Calendar to compare the value to. * @param monthOfFirstQuarter The month that the first quarter starts. * @return Zero if the quarters are equal, -1 if first * parameter's quarter is less than the seconds and +1 if the first * parameter's quarter is greater than. */ public int compareQuarters(Calendar value, Calendar compare, int monthOfFirstQuarter) { return super.compareQuarters(value, compare, monthOfFirstQuarter); } /** *

    Compare Years.

    * * @param value The Calendar value to check. * @param compare The Calendar to compare the value to. * @return Zero if the years are equal, -1 if first * parameter's year is less than the seconds and +1 if the first * parameter's year is greater than. */ public int compareYears(Calendar value, Calendar compare) { return compare(value, compare, Calendar.YEAR); } /** *

    Convert the parsed Date to a Calendar.

    * * @param value The parsed Date object created. * @param formatter The Format used to parse the value with. * @return The parsed value converted to a Calendar. */ protected Object processParsedValue(Object value, Format formatter) { return ((DateFormat)formatter).getCalendar(); } } commons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/routines/CodeValidator.java100644 765 0 20436 11711227701 34366 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines; import java.io.Serializable; import org.apache.commons.validator.routines.checkdigit.CheckDigit; /** * Generic Code Validation providing format, minimum/maximum * length and {@link CheckDigit} validations. *

    * Performs the following validations on a code: *

      *
    • Check the format of the code using a regular expression. (if specified)
    • *
    • Check the minimum and maximum length (if specified) of the parsed code * (i.e. parsed by the regular expression).
    • *
    • Performs {@link CheckDigit} validation on the parsed code (if specified).
    • *
    *

    * Configure the validator with the appropriate regular expression, minimum/maximum length * and {@link CheckDigit} validator and then call one of the two validation * methods provided:

    *
      *
    • boolean isValid(code)
    • *
    • String validate(code)
    • *
    *

    * Codes often include format characters - such as hyphens - to make them * more easily human readable. These can be removed prior to length and check digit * validation by specifying them as a non-capturing group in the regular * expression (i.e. use the (?: ) notation). * * @version $Revision: 1227719 $ $Date: 2012-01-05 18:45:51 +0100 (Thu, 05 Jan 2012) $ * @since Validator 1.4 */ public final class CodeValidator implements Serializable { private static final long serialVersionUID = 446960910870938233L; private final RegexValidator regexValidator; private final int minLength; private final int maxLength; private final CheckDigit checkdigit; /** * Construct a code validator with a specified regular * expression and {@link CheckDigit}. * * @param regex The format regular expression * @param checkdigit The check digit validation routine */ public CodeValidator(String regex, CheckDigit checkdigit) { this(regex, -1, -1, checkdigit); } /** * Construct a code validator with a specified regular * expression, length and {@link CheckDigit}. * * @param regex The format regular expression. * @param length The length of the code * (sets the mimimum/maximum to the same) * @param checkdigit The check digit validation routine */ public CodeValidator(String regex, int length, CheckDigit checkdigit) { this(regex, length, length, checkdigit); } /** * Construct a code validator with a specified regular * expression, minimum/maximum length and {@link CheckDigit} validation. * * @param regex The regular expression validator * @param minLength The minimum length of the code * @param maxLength The maximum length of the code * @param checkdigit The check digit validation routine */ public CodeValidator(String regex, int minLength, int maxLength, CheckDigit checkdigit) { if (regex != null && regex.length() > 0) { this.regexValidator = new RegexValidator(regex); } else { this.regexValidator = null; } this.minLength = minLength; this.maxLength = maxLength; this.checkdigit = checkdigit; } /** * Construct a code validator with a specified regular expression, * validator and {@link CheckDigit} validation. * * @param regexValidator The format regular expression validator * @param checkdigit The check digit validation routine. */ public CodeValidator(RegexValidator regexValidator, CheckDigit checkdigit) { this(regexValidator, -1, -1, checkdigit); } /** * Construct a code validator with a specified regular expression, * validator, length and {@link CheckDigit} validation. * * @param regexValidator The format regular expression validator * @param length The length of the code * (sets the mimimum/maximum to the same value) * @param checkdigit The check digit validation routine */ public CodeValidator(RegexValidator regexValidator, int length, CheckDigit checkdigit) { this(regexValidator, length, length, checkdigit); } /** * Construct a code validator with a specified regular expression * validator, minimum/maximum length and {@link CheckDigit} validation. * * @param regexValidator The format regular expression validator * @param minLength The minimum length of the code * @param maxLength The maximum length of the code * @param checkdigit The check digit validation routine */ public CodeValidator(RegexValidator regexValidator, int minLength, int maxLength, CheckDigit checkdigit) { this.regexValidator = regexValidator; this.minLength = minLength; this.maxLength = maxLength; this.checkdigit = checkdigit; } /** * Return the check digit validation routine. *

    * N.B. Optional, if not set no Check Digit * validation will be performed on the code. * * @return The check digit validation routine */ public CheckDigit getCheckDigit() { return checkdigit; } /** * Return the minimum length of the code. *

    * N.B. Optional, if less than zero the * minimum length will not be checked. * * @return The minimum length of the code or * -1 if the code has no minimum length */ public int getMinLength() { return minLength; } /** * Return the maximum length of the code. *

    * N.B. Optional, if less than zero the * maximum length will not be checked. * * @return The maximum length of the code or * -1 if the code has no maximum length */ public int getMaxLength() { return maxLength; } /** * Return the regular expression validator. *

    * N.B. Optional, if not set no regular * expression validation will be performed on the code. * * @return The regular expression validator */ public RegexValidator getRegexValidator() { return regexValidator; } /** * Validate the code returning either true * or false. * * @param input The code to validate * @return true if valid, otherwise * false */ public boolean isValid(String input) { return (validate(input) != null); } /** * Validate the code returning either the valid code or * null if invalid. * * @param input The code to validate * @return The code if valid, otherwise null * if invalid */ public Object validate(String input) { if (input == null) { return null; } String code = input.trim(); if (code.length() == 0) { return null; } // validate/reformat using regular expression if (regexValidator != null) { code = regexValidator.validate(code); if (code == null) { return null; } } // check the length if ((minLength >= 0 && code.length() < minLength) || (maxLength >= 0 && code.length() > maxLength)) { return null; } // validate the check digit if (checkdigit != null && !checkdigit.isValid(code)) { return null; } return code; } } ././@LongLink100644 0 0 151 11711231552 10246 Lustar 0 0 commons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/routines/CreditCardValidator.javacommons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/routines/CreditCardValidator.100644 765 0 16600 11711227701 34654 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines; import org.apache.commons.validator.routines.checkdigit.CheckDigit; import org.apache.commons.validator.routines.checkdigit.LuhnCheckDigit; import java.io.Serializable; import java.util.List; import java.util.ArrayList; /** *

    Perform credit card validations.

    *

    * By default, all supported card types are allowed. You can specify which * cards should pass validation by configuring the validation options. For * example,
    CreditCardValidator ccv = new CreditCardValidator(CreditCardValidator.AMEX + CreditCardValidator.VISA); * configures the validator to only pass American Express and Visa cards. * If a card type is not directly supported by this class, you can implement * the CreditCardType interface and pass an instance into the * addAllowedCardType method. *

    * For a similar implementation in Perl, reference Sean M. Burke's * script. * More information is also available * here. * * @version $Revision: 1227719 $ $Date: 2012-01-05 18:45:51 +0100 (Thu, 05 Jan 2012) $ * @since Validator 1.4 */ public class CreditCardValidator implements Serializable { private static final long serialVersionUID = 5955978921148959496L; /** * Option specifying that no cards are allowed. This is useful if * you want only custom card types to validate so you turn off the * default cards with this option. *
    *
         * CreditCardValidator v = new CreditCardValidator(CreditCardValidator.NONE);
         * v.addAllowedCardType(customType);
         * v.isValid(aCardNumber);
         * 
    */ public static final long NONE = 0; /** * Option specifying that American Express cards are allowed. */ public static final long AMEX = 1 << 0; /** * Option specifying that Visa cards are allowed. */ public static final long VISA = 1 << 1; /** * Option specifying that Mastercard cards are allowed. */ public static final long MASTERCARD = 1 << 2; /** * Option specifying that Discover cards are allowed. */ public static final long DISCOVER = 1 << 3; /** * Option specifying that Diners cards are allowed. */ public static final long DINERS = 1 << 4; /** * The CreditCardTypes that are allowed to pass validation. */ private final List cardTypes = new ArrayList(); /** * Luhn checkdigit validator for the card numbers. */ private static final CheckDigit LUHN_VALIDATOR = LuhnCheckDigit.LUHN_CHECK_DIGIT; /** American Express (Amex) Card Validator */ public static final CodeValidator AMEX_VALIDATOR = new CodeValidator("^(3[47]\\d{13})$", LUHN_VALIDATOR); /** Diners Card Validator */ public static final CodeValidator DINERS_VALIDATOR = new CodeValidator("^(30[0-5]\\d{11}|3095\\d{10}|36\\d{12}|3[8-9]\\d{12})$", LUHN_VALIDATOR); /** Discover Card regular expressions */ private static final RegexValidator DISCOVER_REGEX = new RegexValidator(new String[] {"^(6011\\d{12})$", "^(64[4-9]\\d{13})$", "^(65\\d{14})$"}); /** Discover Card Validator */ public static final CodeValidator DISCOVER_VALIDATOR = new CodeValidator(DISCOVER_REGEX, LUHN_VALIDATOR); /** Mastercard Card Validator */ public static final CodeValidator MASTERCARD_VALIDATOR = new CodeValidator("^(5[1-5]\\d{14})$", LUHN_VALIDATOR); /** Visa Card Validator */ public static final CodeValidator VISA_VALIDATOR = new CodeValidator("^(4)(\\d{12}|\\d{15})$", LUHN_VALIDATOR); /** * Create a new CreditCardValidator with default options. */ public CreditCardValidator() { this(AMEX + VISA + MASTERCARD + DISCOVER); } /** * Create a new CreditCardValidator with the specified options. * @param options Pass in * CreditCardValidator.VISA + CreditCardValidator.AMEX to specify that * those are the only valid card types. */ public CreditCardValidator(long options) { super(); if (isOn(options, VISA)) { this.cardTypes.add(VISA_VALIDATOR); } if (isOn(options, AMEX)) { this.cardTypes.add(AMEX_VALIDATOR); } if (isOn(options, MASTERCARD)) { this.cardTypes.add(MASTERCARD_VALIDATOR); } if (isOn(options, DISCOVER)) { this.cardTypes.add(DISCOVER_VALIDATOR); } if (isOn(options, DINERS)) { this.cardTypes.add(DINERS_VALIDATOR); } } /** * Create a new CreditCardValidator with the specified {@link CodeValidator}s. * @param creditCardValidators Set of valid code validators */ public CreditCardValidator(CodeValidator[] creditCardValidators) { if (creditCardValidators == null) { throw new IllegalArgumentException("Card validators are missing"); } for (int i = 0; i < creditCardValidators.length; i++) { cardTypes.add(creditCardValidators[i]); } } /** * Checks if the field is a valid credit card number. * @param card The card number to validate. * @return Whether the card number is valid. */ public boolean isValid(String card) { if (card == null || card.length() == 0) { return false; } for (int i = 0; i < cardTypes.size(); i++) { CodeValidator type = (CodeValidator)cardTypes.get(i); if (type.isValid(card)) { return true; } } return false; } /** * Checks if the field is a valid credit card number. * @param card The card number to validate. * @return The card number if valid or null * if invalid. */ public Object validate(String card) { if (card == null || card.length() == 0) { return null; } Object result = null; for (int i = 0; i < cardTypes.size(); i++) { CodeValidator type = (CodeValidator)cardTypes.get(i); result = type.validate(card); if (result != null) { return result ; } } return null; } /** * Tests whether the given flag is on. If the flag is not a power of 2 * (ie. 3) this tests whether the combination of flags is on. * * @param options The options specified. * @param flag Flag value to check. * * @return whether the specified flag value is on. */ private boolean isOn(long options, long flag) { return (options & flag) > 0; } } ././@LongLink100644 0 0 147 11711231552 10253 Lustar 0 0 commons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/routines/CurrencyValidator.javacommons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/routines/CurrencyValidator.ja100644 765 0 11275 11711227701 34760 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines; import java.text.DecimalFormat; import java.text.Format; /** *

    Currency Validation and Conversion routines (java.math.BigDecimal).

    * *

    This is one implementation of a currency validator that has the following features:

    *
      *
    • It is lenient about the the presence of the currency symbol
    • *
    • It converts the currency to a java.math.BigDecimal
    • *
    * *

    However any of the number validators can be used for currency validation. * For example, if you wanted a currency validator that converts to a * java.lang.Integer then you can simply instantiate an * IntegerValidator with the appropriate format type:

    * *

    ... = new IntegerValidator(false, IntegerValidator.CURRENCY_FORMAT);

    * *

    Pick the appropriate validator, depending on the type (e.g Float, Double, Integer, Long etc) * you want the currency converted to. One thing to note - only the CurrencyValidator * implements lenient behaviour regarding the currency symbol.

    * * @version $Revision: 1227719 $ $Date: 2012-01-05 18:45:51 +0100 (Thu, 05 Jan 2012) $ * @since Validator 1.3.0 */ public class CurrencyValidator extends BigDecimalValidator { private static final long serialVersionUID = -4201640771171486514L; private static final CurrencyValidator VALIDATOR = new CurrencyValidator(); /** DecimalFormat's currency symbol */ private static final char CURRENCY_SYMBOL = '\u00A4'; /** * Return a singleton instance of this validator. * @return A singleton instance of the CurrencyValidator. */ public static BigDecimalValidator getInstance() { return VALIDATOR; } /** * Construct a strict instance. */ public CurrencyValidator() { this(true, true); } /** * Construct an instance with the specified strict setting. * * @param strict true if strict * Format parsing should be used. * @param allowFractions true if fractions are * allowed or false if integers only. */ public CurrencyValidator(boolean strict, boolean allowFractions) { super(strict, CURRENCY_FORMAT, allowFractions); } /** *

    Parse the value with the specified Format.

    * *

    This implementation is lenient whether the currency symbol * is present or not. The default NumberFormat * behaviour is for the parsing to "fail" if the currency * symbol is missing. This method re-parses with a format * without the currency symbol if it fails initially.

    * * @param value The value to be parsed. * @param formatter The Format to parse the value with. * @return The parsed value if valid or null if invalid. */ protected Object parse(String value, Format formatter) { // Initial parse of the value Object parsedValue = super.parse(value, formatter); if (parsedValue != null || !(formatter instanceof DecimalFormat)) { return parsedValue; } // Re-parse using a pattern without the currency symbol DecimalFormat decimalFormat = (DecimalFormat)formatter; String pattern = decimalFormat.toPattern(); if (pattern.indexOf(CURRENCY_SYMBOL) >= 0) { StringBuffer buffer = new StringBuffer(pattern.length()); for (int i = 0; i < pattern.length(); i++) { if (pattern.charAt(i) != CURRENCY_SYMBOL) { buffer.append(pattern.charAt(i)); } } decimalFormat.applyPattern(buffer.toString()); parsedValue = super.parse(value, decimalFormat); } return parsedValue; } } commons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/routines/DateValidator.java100644 765 0 35657 11711227701 34404 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines; import java.text.DateFormat; import java.text.Format; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.TimeZone; /** *

    Date Validation and Conversion routines (java.util.Date).

    * *

    This validator provides a number of methods for validating/converting * a String date value to a java.util.Date using * java.text.DateFormat to parse either:

    *
      *
    • using the default format for the default Locale
    • *
    • using a specified pattern with the default Locale
    • *
    • using the default format for a specified Locale
    • *
    • using a specified pattern with a specified Locale
    • *
    * *

    For each of the above mechanisms, conversion method (i.e the * validate methods) implementations are provided which * either use the default TimeZone or allow the * TimeZone to be specified.

    * *

    Use one of the isValid() methods to just validate or * one of the validate() methods to validate and receive a * converted Date value.

    * *

    Implementations of the validate() method are provided * to create Date objects for different time zones * if the system default is not appropriate.

    * *

    Once a value has been sucessfully converted the following * methods can be used to perform various date comparison checks:

    *
      *
    • compareDates() compares the day, month and * year of two dates, returing 0, -1 or +1 indicating * whether the first date is equal, before or after the second.
    • *
    • compareWeeks() compares the week and * year of two dates, returing 0, -1 or +1 indicating * whether the first week is equal, before or after the second.
    • *
    • compareMonths() compares the month and * year of two dates, returing 0, -1 or +1 indicating * whether the first month is equal, before or after the second.
    • *
    • compareQuarters() compares the quarter and * year of two dates, returing 0, -1 or +1 indicating * whether the first quarter is equal, before or after the second.
    • *
    • compareYears() compares the * year of two dates, returing 0, -1 or +1 indicating * whether the first year is equal, before or after the second.
    • *
    * *

    So that the same mechanism used for parsing an input value * for validation can be used to format output, corresponding * format() methods are also provided. That is you can * format either:

    *
      *
    • using a specified pattern
    • *
    • using the format for a specified Locale
    • *
    • using the format for the default Locale
    • *
    * * @version $Revision: 1227719 $ $Date: 2012-01-05 18:45:51 +0100 (Thu, 05 Jan 2012) $ * @since Validator 1.3.0 */ public class DateValidator extends AbstractCalendarValidator { private static final long serialVersionUID = -3966328400469953190L; private static final DateValidator VALIDATOR = new DateValidator(); /** * Return a singleton instance of this validator. * @return A singleton instance of the DateValidator. */ public static DateValidator getInstance() { return VALIDATOR; } /** * Construct a strict instance with short * date style. */ public DateValidator() { this(true, DateFormat.SHORT); } /** * Construct an instance with the specified strict * and date style parameters. * * @param strict true if strict * Format parsing should be used. * @param dateStyle the date style to use for Locale validation. */ public DateValidator(boolean strict, int dateStyle) { super(strict, dateStyle, -1); } /** *

    Validate/convert a Date using the default * Locale and TimeZone. * * @param value The value validation is being performed on. * @return The parsed Date if valid or null * if invalid. */ public Date validate(String value) { return (Date)parse(value, (String)null, (Locale)null, (TimeZone)null); } /** *

    Validate/convert a Date using the specified * TimeZone and default Locale. * * @param value The value validation is being performed on. * @param timeZone The Time Zone used to parse the date, system default if null. * @return The parsed Date if valid or null if invalid. */ public Date validate(String value, TimeZone timeZone) { return (Date)parse(value, (String)null, (Locale)null, timeZone); } /** *

    Validate/convert a Date using the specified * pattern and default TimeZone. * * @param value The value validation is being performed on. * @param pattern The pattern used to validate the value against, or the * default for the Locale if null. * @return The parsed Date if valid or null if invalid. */ public Date validate(String value, String pattern) { return (Date)parse(value, pattern, (Locale)null, (TimeZone)null); } /** *

    Validate/convert a Date using the specified * pattern and TimeZone. * * @param value The value validation is being performed on. * @param pattern The pattern used to validate the value against, or the * default for the Locale if null. * @param timeZone The Time Zone used to parse the date, system default if null. * @return The parsed Date if valid or null if invalid. */ public Date validate(String value, String pattern, TimeZone timeZone) { return (Date)parse(value, pattern, (Locale)null, timeZone); } /** *

    Validate/convert a Date using the specified * Locale and default TimeZone. * * @param value The value validation is being performed on. * @param locale The locale to use for the date format, system default if null. * @return The parsed Date if valid or null if invalid. */ public Date validate(String value, Locale locale) { return (Date)parse(value, (String)null, locale, (TimeZone)null); } /** *

    Validate/convert a Date using the specified * Locale and TimeZone. * * @param value The value validation is being performed on. * @param locale The locale to use for the date format, system default if null. * @param timeZone The Time Zone used to parse the date, system default if null. * @return The parsed Date if valid or null if invalid. */ public Date validate(String value, Locale locale, TimeZone timeZone) { return (Date)parse(value, (String)null, locale, timeZone); } /** *

    Validate/convert a Date using the specified pattern * and Locale and the default TimeZone. * * @param value The value validation is being performed on. * @param pattern The pattern used to validate the value against, or the * default for the Locale if null. * @param locale The locale to use for the date format, system default if null. * @return The parsed Date if valid or null if invalid. */ public Date validate(String value, String pattern, Locale locale) { return (Date)parse(value, pattern, locale, (TimeZone)null); } /** *

    Validate/convert a Date using the specified * pattern, and Locale and TimeZone. * * @param value The value validation is being performed on. * @param pattern The pattern used to validate the value against, or the * default for the Locale if null. * @param locale The locale to use for the date format, system default if null. * @param timeZone The Time Zone used to parse the date, system default if null. * @return The parsed Date if valid or null if invalid. */ public Date validate(String value, String pattern, Locale locale, TimeZone timeZone) { return (Date)parse(value, pattern, locale, timeZone); } /** *

    Compare Dates (day, month and year - not time).

    * * @param value The Calendar value to check. * @param compare The Calendar to compare the value to. * @param timeZone The Time Zone used to compare the dates, system default if null. * @return Zero if the dates are equal, -1 if first * date is less than the seconds and +1 if the first * date is greater than. */ public int compareDates(Date value, Date compare, TimeZone timeZone) { Calendar calendarValue = getCalendar(value, timeZone); Calendar calendarCompare = getCalendar(compare, timeZone); return compare(calendarValue, calendarCompare, Calendar.DATE); } /** *

    Compare Weeks (week and year).

    * * @param value The Date value to check. * @param compare The Date to compare the value to. * @param timeZone The Time Zone used to compare the dates, system default if null. * @return Zero if the weeks are equal, -1 if first * parameter's week is less than the seconds and +1 if the first * parameter's week is greater than. */ public int compareWeeks(Date value, Date compare, TimeZone timeZone) { Calendar calendarValue = getCalendar(value, timeZone); Calendar calendarCompare = getCalendar(compare, timeZone); return compare(calendarValue, calendarCompare, Calendar.WEEK_OF_YEAR); } /** *

    Compare Months (month and year).

    * * @param value The Date value to check. * @param compare The Date to compare the value to. * @param timeZone The Time Zone used to compare the dates, system default if null. * @return Zero if the months are equal, -1 if first * parameter's month is less than the seconds and +1 if the first * parameter's month is greater than. */ public int compareMonths(Date value, Date compare, TimeZone timeZone) { Calendar calendarValue = getCalendar(value, timeZone); Calendar calendarCompare = getCalendar(compare, timeZone); return compare(calendarValue, calendarCompare, Calendar.MONTH); } /** *

    Compare Quarters (quarter and year).

    * * @param value The Date value to check. * @param compare The Date to compare the value to. * @param timeZone The Time Zone used to compare the dates, system default if null. * @return Zero if the months are equal, -1 if first * parameter's quarter is less than the seconds and +1 if the first * parameter's quarter is greater than. */ public int compareQuarters(Date value, Date compare, TimeZone timeZone) { return compareQuarters(value, compare, timeZone, 1); } /** *

    Compare Quarters (quarter and year).

    * * @param value The Date value to check. * @param compare The Date to compare the value to. * @param timeZone The Time Zone used to compare the dates, system default if null. * @param monthOfFirstQuarter The month that the first quarter starts. * @return Zero if the quarters are equal, -1 if first * parameter's quarter is less than the seconds and +1 if the first * parameter's quarter is greater than. */ public int compareQuarters(Date value, Date compare, TimeZone timeZone, int monthOfFirstQuarter) { Calendar calendarValue = getCalendar(value, timeZone); Calendar calendarCompare = getCalendar(compare, timeZone); return super.compareQuarters(calendarValue, calendarCompare, monthOfFirstQuarter); } /** *

    Compare Years.

    * * @param value The Date value to check. * @param compare The Date to compare the value to. * @param timeZone The Time Zone used to compare the dates, system default if null. * @return Zero if the years are equal, -1 if first * parameter's year is less than the seconds and +1 if the first * parameter's year is greater than. */ public int compareYears(Date value, Date compare, TimeZone timeZone) { Calendar calendarValue = getCalendar(value, timeZone); Calendar calendarCompare = getCalendar(compare, timeZone); return compare(calendarValue, calendarCompare, Calendar.YEAR); } /** *

    Returns the parsed Date unchanged.

    * * @param value The parsed Date object created. * @param formatter The Format used to parse the value with. * @return The parsed value converted to a Calendar. */ protected Object processParsedValue(Object value, Format formatter) { return value; } /** *

    Convert a Date to a Calendar.

    * * @param value The date value to be converted. * @return The converted Calendar. */ private Calendar getCalendar(Date value, TimeZone timeZone) { Calendar calendar = null; if (timeZone != null) { calendar = Calendar.getInstance(timeZone); } else { calendar = Calendar.getInstance(); } calendar.setTime(value); return calendar; } } ././@LongLink100644 0 0 145 11711231552 10251 Lustar 0 0 commons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/routines/DomainValidator.javacommons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/routines/DomainValidator.java100644 765 0 52304 11711227701 34722 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines; import java.io.Serializable; import java.util.Arrays; import java.util.List; /** *

    Domain name validation routines.

    * *

    * This validator provides methods for validating Internet domain names * and top-level domains. *

    * *

    Domain names are evaluated according * to the standards RFC1034, * section 3, and RFC1123, * section 2.1. No accomodation is provided for the specialized needs of * other applications; if the domain name has been URL-encoded, for example, * validation will fail even though the equivalent plaintext version of the * same name would have passed. *

    * *

    * Validation is also provided for top-level domains (TLDs) as defined and * maintained by the Internet Assigned Numbers Authority (IANA): *

    * *
      *
    • {@link #isValidInfrastructureTld} - validates infrastructure TLDs * (.arpa, etc.)
    • *
    • {@link #isValidGenericTld} - validates generic TLDs * (.com, .org, etc.)
    • *
    • {@link #isValidCountryCodeTld} - validates country code TLDs * (.us, .uk, .cn, etc.)
    • *
    * *

    * (NOTE: This class does not provide IP address lookup for domain names or * methods to ensure that a given domain name matches a specific IP; see * {@link java.net.InetAddress} for that functionality.) *

    * * @version $Revision: 1227719 $ $Date: 2012-01-05 18:45:51 +0100 (Thu, 05 Jan 2012) $ * @since Validator 1.4 */ public class DomainValidator implements Serializable { private static final long serialVersionUID = -4407125112880174009L; // Regular expression strings for hostnames (derived from RFC2396 and RFC 1123) private static final String DOMAIN_LABEL_REGEX = "\\p{Alnum}(?>[\\p{Alnum}-]*\\p{Alnum})*"; private static final String TOP_LABEL_REGEX = "\\p{Alpha}{2,}"; private static final String DOMAIN_NAME_REGEX = "^(?:" + DOMAIN_LABEL_REGEX + "\\.)+" + "(" + TOP_LABEL_REGEX + ")$"; private final boolean allowLocal; /** * Singleton instance of this validator, which * doesn't consider local addresses as valid. */ private static final DomainValidator DOMAIN_VALIDATOR = new DomainValidator(false); /** * Singleton instance of this validator, which does * consider local addresses valid. */ private static final DomainValidator DOMAIN_VALIDATOR_WITH_LOCAL = new DomainValidator(true); /** * RegexValidator for matching domains. */ private final RegexValidator domainRegex = new RegexValidator(DOMAIN_NAME_REGEX); /** * RegexValidator for matching the a local hostname */ private final RegexValidator hostnameRegex = new RegexValidator(DOMAIN_LABEL_REGEX); /** * Returns the singleton instance of this validator. It * will not consider local addresses as valid. * @return the singleton instance of this validator */ public static DomainValidator getInstance() { return DOMAIN_VALIDATOR; } /** * Returns the singleton instance of this validator, * with local validation as required. * @param allowLocal Should local addresses be considered valid? * @return the singleton instance of this validator */ public static DomainValidator getInstance(boolean allowLocal) { if(allowLocal) { return DOMAIN_VALIDATOR_WITH_LOCAL; } return DOMAIN_VALIDATOR; } /** Private constructor. */ private DomainValidator(boolean allowLocal) { this.allowLocal = allowLocal; } /** * Returns true if the specified String parses * as a valid domain name with a recognized top-level domain. * The parsing is case-sensitive. * @param domain the parameter to check for domain name syntax * @return true if the parameter is a valid domain name */ public boolean isValid(String domain) { String[] groups = domainRegex.match(domain); if (groups != null && groups.length > 0) { return isValidTld(groups[0]); } else if(allowLocal) { if (hostnameRegex.isValid(domain)) { return true; } } return false; } /** * Returns true if the specified String matches any * IANA-defined top-level domain. Leading dots are ignored if present. * The search is case-sensitive. * @param tld the parameter to check for TLD status * @return true if the parameter is a TLD */ public boolean isValidTld(String tld) { if(allowLocal && isValidLocalTld(tld)) { return true; } return isValidInfrastructureTld(tld) || isValidGenericTld(tld) || isValidCountryCodeTld(tld); } /** * Returns true if the specified String matches any * IANA-defined infrastructure top-level domain. Leading dots are * ignored if present. The search is case-sensitive. * @param iTld the parameter to check for infrastructure TLD status * @return true if the parameter is an infrastructure TLD */ public boolean isValidInfrastructureTld(String iTld) { return INFRASTRUCTURE_TLD_LIST.contains(chompLeadingDot(iTld.toLowerCase())); } /** * Returns true if the specified String matches any * IANA-defined generic top-level domain. Leading dots are ignored * if present. The search is case-sensitive. * @param gTld the parameter to check for generic TLD status * @return true if the parameter is a generic TLD */ public boolean isValidGenericTld(String gTld) { return GENERIC_TLD_LIST.contains(chompLeadingDot(gTld.toLowerCase())); } /** * Returns true if the specified String matches any * IANA-defined country code top-level domain. Leading dots are * ignored if present. The search is case-sensitive. * @param ccTld the parameter to check for country code TLD status * @return true if the parameter is a country code TLD */ public boolean isValidCountryCodeTld(String ccTld) { return COUNTRY_CODE_TLD_LIST.contains(chompLeadingDot(ccTld.toLowerCase())); } /** * Returns true if the specified String matches any * widely used "local" domains (localhost or localdomain). Leading dots are * ignored if present. The search is case-sensitive. * @param iTld the parameter to check for local TLD status * @return true if the parameter is an local TLD */ public boolean isValidLocalTld(String iTld) { return LOCAL_TLD_LIST.contains(chompLeadingDot(iTld.toLowerCase())); } private String chompLeadingDot(String str) { if (str.startsWith(".")) { return str.substring(1); } else { return str; } } // --------------------------------------------- // ----- TLDs defined by IANA // ----- Authoritative and comprehensive list at: // ----- http://data.iana.org/TLD/tlds-alpha-by-domain.txt private static final String[] INFRASTRUCTURE_TLDS = new String[] { "arpa", // internet infrastructure "root" // diagnostic marker for non-truncated root zone }; private static final String[] GENERIC_TLDS = new String[] { "aero", // air transport industry "asia", // Pan-Asia/Asia Pacific "biz", // businesses "cat", // Catalan linguistic/cultural community "com", // commercial enterprises "coop", // cooperative associations "info", // informational sites "jobs", // Human Resource managers "mobi", // mobile products and services "museum", // museums, surprisingly enough "name", // individuals' sites "net", // internet support infrastructure/business "org", // noncommercial organizations "pro", // credentialed professionals and entities "tel", // contact data for businesses and individuals "travel", // entities in the travel industry "gov", // United States Government "edu", // accredited postsecondary US education entities "mil", // United States Military "int" // organizations established by international treaty }; private static final String[] COUNTRY_CODE_TLDS = new String[] { "ac", // Ascension Island "ad", // Andorra "ae", // United Arab Emirates "af", // Afghanistan "ag", // Antigua and Barbuda "ai", // Anguilla "al", // Albania "am", // Armenia "an", // Netherlands Antilles "ao", // Angola "aq", // Antarctica "ar", // Argentina "as", // American Samoa "at", // Austria "au", // Australia (includes Ashmore and Cartier Islands and Coral Sea Islands) "aw", // Aruba "ax", // Åland "az", // Azerbaijan "ba", // Bosnia and Herzegovina "bb", // Barbados "bd", // Bangladesh "be", // Belgium "bf", // Burkina Faso "bg", // Bulgaria "bh", // Bahrain "bi", // Burundi "bj", // Benin "bm", // Bermuda "bn", // Brunei Darussalam "bo", // Bolivia "br", // Brazil "bs", // Bahamas "bt", // Bhutan "bv", // Bouvet Island "bw", // Botswana "by", // Belarus "bz", // Belize "ca", // Canada "cc", // Cocos (Keeling) Islands "cd", // Democratic Republic of the Congo (formerly Zaire) "cf", // Central African Republic "cg", // Republic of the Congo "ch", // Switzerland "ci", // Côte d'Ivoire "ck", // Cook Islands "cl", // Chile "cm", // Cameroon "cn", // China, mainland "co", // Colombia "cr", // Costa Rica "cu", // Cuba "cv", // Cape Verde "cx", // Christmas Island "cy", // Cyprus "cz", // Czech Republic "de", // Germany "dj", // Djibouti "dk", // Denmark "dm", // Dominica "do", // Dominican Republic "dz", // Algeria "ec", // Ecuador "ee", // Estonia "eg", // Egypt "er", // Eritrea "es", // Spain "et", // Ethiopia "eu", // European Union "fi", // Finland "fj", // Fiji "fk", // Falkland Islands "fm", // Federated States of Micronesia "fo", // Faroe Islands "fr", // France "ga", // Gabon "gb", // Great Britain (United Kingdom) "gd", // Grenada "ge", // Georgia "gf", // French Guiana "gg", // Guernsey "gh", // Ghana "gi", // Gibraltar "gl", // Greenland "gm", // The Gambia "gn", // Guinea "gp", // Guadeloupe "gq", // Equatorial Guinea "gr", // Greece "gs", // South Georgia and the South Sandwich Islands "gt", // Guatemala "gu", // Guam "gw", // Guinea-Bissau "gy", // Guyana "hk", // Hong Kong "hm", // Heard Island and McDonald Islands "hn", // Honduras "hr", // Croatia (Hrvatska) "ht", // Haiti "hu", // Hungary "id", // Indonesia "ie", // Ireland (Éire) "il", // Israel "im", // Isle of Man "in", // India "io", // British Indian Ocean Territory "iq", // Iraq "ir", // Iran "is", // Iceland "it", // Italy "je", // Jersey "jm", // Jamaica "jo", // Jordan "jp", // Japan "ke", // Kenya "kg", // Kyrgyzstan "kh", // Cambodia (Khmer) "ki", // Kiribati "km", // Comoros "kn", // Saint Kitts and Nevis "kp", // North Korea "kr", // South Korea "kw", // Kuwait "ky", // Cayman Islands "kz", // Kazakhstan "la", // Laos (currently being marketed as the official domain for Los Angeles) "lb", // Lebanon "lc", // Saint Lucia "li", // Liechtenstein "lk", // Sri Lanka "lr", // Liberia "ls", // Lesotho "lt", // Lithuania "lu", // Luxembourg "lv", // Latvia "ly", // Libya "ma", // Morocco "mc", // Monaco "md", // Moldova "me", // Montenegro "mg", // Madagascar "mh", // Marshall Islands "mk", // Republic of Macedonia "ml", // Mali "mm", // Myanmar "mn", // Mongolia "mo", // Macau "mp", // Northern Mariana Islands "mq", // Martinique "mr", // Mauritania "ms", // Montserrat "mt", // Malta "mu", // Mauritius "mv", // Maldives "mw", // Malawi "mx", // Mexico "my", // Malaysia "mz", // Mozambique "na", // Namibia "nc", // New Caledonia "ne", // Niger "nf", // Norfolk Island "ng", // Nigeria "ni", // Nicaragua "nl", // Netherlands "no", // Norway "np", // Nepal "nr", // Nauru "nu", // Niue "nz", // New Zealand "om", // Oman "pa", // Panama "pe", // Peru "pf", // French Polynesia With Clipperton Island "pg", // Papua New Guinea "ph", // Philippines "pk", // Pakistan "pl", // Poland "pm", // Saint-Pierre and Miquelon "pn", // Pitcairn Islands "pr", // Puerto Rico "ps", // Palestinian territories (PA-controlled West Bank and Gaza Strip) "pt", // Portugal "pw", // Palau "py", // Paraguay "qa", // Qatar "re", // Réunion "ro", // Romania "rs", // Serbia "ru", // Russia "rw", // Rwanda "sa", // Saudi Arabia "sb", // Solomon Islands "sc", // Seychelles "sd", // Sudan "se", // Sweden "sg", // Singapore "sh", // Saint Helena "si", // Slovenia "sj", // Svalbard and Jan Mayen Islands Not in use (Norwegian dependencies; see .no) "sk", // Slovakia "sl", // Sierra Leone "sm", // San Marino "sn", // Senegal "so", // Somalia "sr", // Suriname "st", // São Tomé and Príncipe "su", // Soviet Union (deprecated) "sv", // El Salvador "sy", // Syria "sz", // Swaziland "tc", // Turks and Caicos Islands "td", // Chad "tf", // French Southern and Antarctic Lands "tg", // Togo "th", // Thailand "tj", // Tajikistan "tk", // Tokelau "tl", // East Timor (deprecated old code) "tm", // Turkmenistan "tn", // Tunisia "to", // Tonga "tp", // East Timor "tr", // Turkey "tt", // Trinidad and Tobago "tv", // Tuvalu "tw", // Taiwan, Republic of China "tz", // Tanzania "ua", // Ukraine "ug", // Uganda "uk", // United Kingdom "um", // United States Minor Outlying Islands "us", // United States of America "uy", // Uruguay "uz", // Uzbekistan "va", // Vatican City State "vc", // Saint Vincent and the Grenadines "ve", // Venezuela "vg", // British Virgin Islands "vi", // U.S. Virgin Islands "vn", // Vietnam "vu", // Vanuatu "wf", // Wallis and Futuna "ws", // Samoa (formerly Western Samoa) "ye", // Yemen "yt", // Mayotte "yu", // Serbia and Montenegro (originally Yugoslavia) "za", // South Africa "zm", // Zambia "zw", // Zimbabwe }; private static final String[] LOCAL_TLDS = new String[] { "localhost", // RFC2606 defined "localdomain" // Also widely used as localhost.localdomain }; private static final List INFRASTRUCTURE_TLD_LIST = Arrays.asList(INFRASTRUCTURE_TLDS); private static final List GENERIC_TLD_LIST = Arrays.asList(GENERIC_TLDS); private static final List COUNTRY_CODE_TLD_LIST = Arrays.asList(COUNTRY_CODE_TLDS); private static final List LOCAL_TLD_LIST = Arrays.asList(LOCAL_TLDS); } ././@LongLink100644 0 0 145 11711231552 10251 Lustar 0 0 commons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/routines/DoubleValidator.javacommons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/routines/DoubleValidator.java100644 765 0 22673 11711227701 34733 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines; import java.text.Format; import java.util.Locale; /** *

    Double Validation and Conversion routines (java.lang.Double).

    * *

    This validator provides a number of methods for * validating/converting a String value to * a Double using java.text.NumberFormat * to parse either:

    *
      *
    • using the default format for the default Locale
    • *
    • using a specified pattern with the default Locale
    • *
    • using the default format for a specified Locale
    • *
    • using a specified pattern with a specified Locale
    • *
    * *

    Use one of the isValid() methods to just validate or * one of the validate() methods to validate and receive a * converted Double value.

    * *

    Once a value has been sucessfully converted the following * methods can be used to perform minimum, maximum and range checks:

    *
      *
    • minValue() checks whether the value is greater * than or equal to a specified minimum.
    • *
    • maxValue() checks whether the value is less * than or equal to a specified maximum.
    • *
    • isInRange() checks whether the value is within * a specified range of values.
    • *
    * *

    So that the same mechanism used for parsing an input value * for validation can be used to format output, corresponding * format() methods are also provided. That is you can * format either:

    *
      *
    • using the default format for the default Locale
    • *
    • using a specified pattern with the default Locale
    • *
    • using the default format for a specified Locale
    • *
    • using a specified pattern with a specified Locale
    • *
    * * @version $Revision: 1227719 $ $Date: 2012-01-05 18:45:51 +0100 (Thu, 05 Jan 2012) $ * @since Validator 1.3.0 */ public class DoubleValidator extends AbstractNumberValidator { private static final long serialVersionUID = 5867946581318211330L; private static final DoubleValidator VALIDATOR = new DoubleValidator(); /** * Return a singleton instance of this validator. * @return A singleton instance of the DoubleValidator. */ public static DoubleValidator getInstance() { return VALIDATOR; } /** * Construct a strict instance. */ public DoubleValidator() { this(true, STANDARD_FORMAT); } /** *

    Construct an instance with the specified strict setting * and format type.

    * *

    The formatType specified what type of * NumberFormat is created - valid types * are:

    *
      *
    • AbstractNumberValidator.STANDARD_FORMAT -to create * standard number formats (the default).
    • *
    • AbstractNumberValidator.CURRENCY_FORMAT -to create * currency number formats.
    • *
    • AbstractNumberValidator.PERCENT_FORMAT -to create * percent number formats (the default).
    • *
    * * @param strict true if strict * Format parsing should be used. * @param formatType The NumberFormat type to * create for validation, default is STANDARD_FORMAT. */ public DoubleValidator(boolean strict, int formatType) { super(strict, formatType, true); } /** *

    Validate/convert a Double using the default * Locale. * * @param value The value validation is being performed on. * @return The parsed Double if valid or null * if invalid. */ public Double validate(String value) { return (Double)parse(value, (String)null, (Locale)null); } /** *

    Validate/convert a Double using the * specified pattern. * * @param value The value validation is being performed on. * @param pattern The pattern used to validate the value against. * @return The parsed BigDecimal if valid or null if invalid. */ public Double validate(String value, String pattern) { return (Double)parse(value, pattern, (Locale)null); } /** *

    Validate/convert a Double using the * specified Locale. * * @param value The value validation is being performed on. * @param locale The locale to use for the number format, system default if null. * @return The parsed Double if valid or null if invalid. */ public Double validate(String value, Locale locale) { return (Double)parse(value, (String)null, locale); } /** *

    Validate/convert a Double using the * specified pattern and/ or Locale. * * @param value The value validation is being performed on. * @param pattern The pattern used to validate the value against, or the * default for the Locale if null. * @param locale The locale to use for the date format, system default if null. * @return The parsed Double if valid or null if invalid. */ public Double validate(String value, String pattern, Locale locale) { return (Double)parse(value, pattern, locale); } /** * Check if the value is within a specified range. * * @param value The Number value to check. * @param min The minimum value of the range. * @param max The maximum value of the range. * @return true if the value is within the * specified range. */ public boolean isInRange(double value, double min, double max) { return (value >= min && value <= max); } /** * Check if the value is within a specified range. * * @param value The Number value to check. * @param min The minimum value of the range. * @param max The maximum value of the range. * @return true if the value is within the * specified range. */ public boolean isInRange(Double value, double min, double max) { return isInRange(value.doubleValue(), min, max); } /** * Check if the value is greater than or equal to a minimum. * * @param value The value validation is being performed on. * @param min The minimum value. * @return true if the value is greater than * or equal to the minimum. */ public boolean minValue(double value, double min) { return (value >= min); } /** * Check if the value is greater than or equal to a minimum. * * @param value The value validation is being performed on. * @param min The minimum value. * @return true if the value is greater than * or equal to the minimum. */ public boolean minValue(Double value, double min) { return minValue(value.doubleValue(), min); } /** * Check if the value is less than or equal to a maximum. * * @param value The value validation is being performed on. * @param max The maximum value. * @return true if the value is less than * or equal to the maximum. */ public boolean maxValue(double value, double max) { return (value <= max); } /** * Check if the value is less than or equal to a maximum. * * @param value The value validation is being performed on. * @param max The maximum value. * @return true if the value is less than * or equal to the maximum. */ public boolean maxValue(Double value, double max) { return maxValue(value.doubleValue(), max); } /** * Convert the parsed value to a Double. * * @param value The parsed Number object created. * @param formatter The Format used to parse the value with. * @return The validated/converted Double value if valid * or null if invalid. */ protected Object processParsedValue(Object value, Format formatter) { if (value instanceof Double) { return value; } else { return new Double(((Number)value).doubleValue()); } } } commons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/routines/EmailValidator.java100644 765 0 13730 11711227701 34542 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines; import java.io.Serializable; import java.util.regex.Matcher; import java.util.regex.Pattern; /** *

    Perform email validations.

    *

    * This class is a Singleton; you can retrieve the instance via the getInstance() method. *

    *

    * Based on a script by Sandeep V. Tamhankar * http://javascript.internet.com *

    *

    * This implementation is not guaranteed to catch all possible errors in an email address. * For example, an address like nobody@noplace.somedog will pass validator, even though there * is no TLD "somedog" *

    . * * @version $Revision: 1227719 $ $Date: 2012-01-05 18:45:51 +0100 (Thu, 05 Jan 2012) $ * @since Validator 1.4 */ public class EmailValidator implements Serializable { private static final long serialVersionUID = 1705927040799295880L; private static final String SPECIAL_CHARS = "\\p{Cntrl}\\(\\)<>@,;:'\\\\\\\"\\.\\[\\]"; private static final String VALID_CHARS = "[^\\s" + SPECIAL_CHARS + "]"; private static final String QUOTED_USER = "(\"[^\"]*\")"; private static final String WORD = "((" + VALID_CHARS + "|')+|" + QUOTED_USER + ")"; private static final String LEGAL_ASCII_REGEX = "^\\p{ASCII}+$"; private static final String EMAIL_REGEX = "^\\s*?(.+)@(.+?)\\s*$"; private static final String IP_DOMAIN_REGEX = "^\\[(.*)\\]$"; private static final String USER_REGEX = "^\\s*" + WORD + "(\\." + WORD + ")*$"; private static final Pattern MATCH_ASCII_PATTERN = Pattern.compile(LEGAL_ASCII_REGEX); private static final Pattern EMAIL_PATTERN = Pattern.compile(EMAIL_REGEX); private static final Pattern IP_DOMAIN_PATTERN = Pattern.compile(IP_DOMAIN_REGEX); private static final Pattern USER_PATTERN = Pattern.compile(USER_REGEX); private final boolean allowLocal; /** * Singleton instance of this class, which * doesn't consider local addresses as valid. */ private static final EmailValidator EMAIL_VALIDATOR = new EmailValidator(false); /** * Singleton instance of this class, which does * consider local addresses valid. */ private static final EmailValidator EMAIL_VALIDATOR_WITH_LOCAL = new EmailValidator(true); /** * Returns the Singleton instance of this validator. * * @return singleton instance of this validator. */ public static EmailValidator getInstance() { return EMAIL_VALIDATOR; } /** * Returns the Singleton instance of this validator, * with local validation as required. * * @param allowLocal Should local addresses be considered valid? * @return singleton instance of this validator */ public static EmailValidator getInstance(boolean allowLocal) { if(allowLocal) { return EMAIL_VALIDATOR_WITH_LOCAL; } return EMAIL_VALIDATOR; } /** * Protected constructor for subclasses to use. * * @param allowLocal Should local addresses be considered valid? */ protected EmailValidator(boolean allowLocal) { super(); this.allowLocal = allowLocal; } /** *

    Checks if a field has a valid e-mail address.

    * * @param email The value validation is being performed on. A null * value is considered invalid. * @return true if the email address is valid. */ public boolean isValid(String email) { if (email == null) { return false; } Matcher asciiMatcher = MATCH_ASCII_PATTERN.matcher(email); if (!asciiMatcher.matches()) { return false; } // Check the whole email address structure Matcher emailMatcher = EMAIL_PATTERN.matcher(email); if (!emailMatcher.matches()) { return false; } if (email.endsWith(".")) { return false; } if (!isValidUser(emailMatcher.group(1))) { return false; } if (!isValidDomain(emailMatcher.group(2))) { return false; } return true; } /** * Returns true if the domain component of an email address is valid. * * @param domain being validated. * @return true if the email address's domain is valid. */ protected boolean isValidDomain(String domain) { // see if domain is an IP address in brackets Matcher ipDomainMatcher = IP_DOMAIN_PATTERN.matcher(domain); if (ipDomainMatcher.matches()) { InetAddressValidator inetAddressValidator = InetAddressValidator.getInstance(); return inetAddressValidator.isValid(ipDomainMatcher.group(1)); } else { // Domain is symbolic name DomainValidator domainValidator = DomainValidator.getInstance(allowLocal); return domainValidator.isValid(domain); } } /** * Returns true if the user component of an email address is valid. * * @param user being validated * @return true if the user name is valid. */ protected boolean isValidUser(String user) { return USER_PATTERN.matcher(user).matches(); } } commons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/routines/FloatValidator.java100644 765 0 23617 11711227701 34565 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines; import java.text.Format; import java.util.Locale; /** *

    Float Validation and Conversion routines (java.lang.Float).

    * *

    This validator provides a number of methods for * validating/converting a String value to * a Float using java.text.NumberFormat * to parse either:

    *
      *
    • using the default format for the default Locale
    • *
    • using a specified pattern with the default Locale
    • *
    • using the default format for a specified Locale
    • *
    • using a specified pattern with a specified Locale
    • *
    * *

    Use one of the isValid() methods to just validate or * one of the validate() methods to validate and receive a * converted Float value.

    * *

    Once a value has been sucessfully converted the following * methods can be used to perform minimum, maximum and range checks:

    *
      *
    • minValue() checks whether the value is greater * than or equal to a specified minimum.
    • *
    • maxValue() checks whether the value is less * than or equal to a specified maximum.
    • *
    • isInRange() checks whether the value is within * a specified range of values.
    • *
    * *

    So that the same mechanism used for parsing an input value * for validation can be used to format output, corresponding * format() methods are also provided. That is you can * format either:

    *
      *
    • using the default format for the default Locale
    • *
    • using a specified pattern with the default Locale
    • *
    • using the default format for a specified Locale
    • *
    • using a specified pattern with a specified Locale
    • *
    * * @version $Revision: 1227719 $ $Date: 2012-01-05 18:45:51 +0100 (Thu, 05 Jan 2012) $ * @since Validator 1.3.0 */ public class FloatValidator extends AbstractNumberValidator { private static final long serialVersionUID = -4513245432806414267L; private static final FloatValidator VALIDATOR = new FloatValidator(); /** * Return a singleton instance of this validator. * @return A singleton instance of the FloatValidator. */ public static FloatValidator getInstance() { return VALIDATOR; } /** * Construct a strict instance. */ public FloatValidator() { this(true, STANDARD_FORMAT); } /** *

    Construct an instance with the specified strict setting * and format type.

    * *

    The formatType specified what type of * NumberFormat is created - valid types * are:

    *
      *
    • AbstractNumberValidator.STANDARD_FORMAT -to create * standard number formats (the default).
    • *
    • AbstractNumberValidator.CURRENCY_FORMAT -to create * currency number formats.
    • *
    • AbstractNumberValidator.PERCENT_FORMAT -to create * percent number formats (the default).
    • *
    * * @param strict true if strict * Format parsing should be used. * @param formatType The NumberFormat type to * create for validation, default is STANDARD_FORMAT. */ public FloatValidator(boolean strict, int formatType) { super(strict, formatType, true); } /** *

    Validate/convert a Float using the default * Locale. * * @param value The value validation is being performed on. * @return The parsed Float if valid or null * if invalid. */ public Float validate(String value) { return (Float)parse(value, (String)null, (Locale)null); } /** *

    Validate/convert a Float using the * specified pattern. * * @param value The value validation is being performed on. * @param pattern The pattern used to validate the value against. * @return The parsed Float if valid or null if invalid. */ public Float validate(String value, String pattern) { return (Float)parse(value, pattern, (Locale)null); } /** *

    Validate/convert a Float using the * specified Locale. * * @param value The value validation is being performed on. * @param locale The locale to use for the number format, system default if null. * @return The parsed Float if valid or null if invalid. */ public Float validate(String value, Locale locale) { return (Float)parse(value, (String)null, locale); } /** *

    Validate/convert a Float using the * specified pattern and/ or Locale. * * @param value The value validation is being performed on. * @param pattern The pattern used to validate the value against, or the * default for the Locale if null. * @param locale The locale to use for the date format, system default if null. * @return The parsed Float if valid or null if invalid. */ public Float validate(String value, String pattern, Locale locale) { return (Float)parse(value, pattern, locale); } /** * Check if the value is within a specified range. * * @param value The Number value to check. * @param min The minimum value of the range. * @param max The maximum value of the range. * @return true if the value is within the * specified range. */ public boolean isInRange(float value, float min, float max) { return (value >= min && value <= max); } /** * Check if the value is within a specified range. * * @param value The Number value to check. * @param min The minimum value of the range. * @param max The maximum value of the range. * @return true if the value is within the * specified range. */ public boolean isInRange(Float value, float min, float max) { return isInRange(value.floatValue(), min, max); } /** * Check if the value is greater than or equal to a minimum. * * @param value The value validation is being performed on. * @param min The minimum value. * @return true if the value is greater than * or equal to the minimum. */ public boolean minValue(float value, float min) { return (value >= min); } /** * Check if the value is greater than or equal to a minimum. * * @param value The value validation is being performed on. * @param min The minimum value. * @return true if the value is greater than * or equal to the minimum. */ public boolean minValue(Float value, float min) { return minValue(value.floatValue(), min); } /** * Check if the value is less than or equal to a maximum. * * @param value The value validation is being performed on. * @param max The maximum value. * @return true if the value is less than * or equal to the maximum. */ public boolean maxValue(float value, float max) { return (value <= max); } /** * Check if the value is less than or equal to a maximum. * * @param value The value validation is being performed on. * @param max The maximum value. * @return true if the value is less than * or equal to the maximum. */ public boolean maxValue(Float value, float max) { return maxValue(value.floatValue(), max); } /** *

    Perform further validation and convert the Number to * a Float.

    * * @param value The parsed Number object created. * @param formatter The Format used to parse the value with. * @return The parsed Number converted to a * Float if valid or null if invalid. */ protected Object processParsedValue(Object value, Format formatter) { double doubleValue = ((Number)value).doubleValue(); if (doubleValue > 0) { if (doubleValue < Float.MIN_VALUE) { return null; } if (doubleValue > Float.MAX_VALUE) { return null; } } else if (doubleValue < 0){ double posDouble = doubleValue * -1; if (posDouble < Float.MIN_VALUE) { return null; } if (posDouble > Float.MAX_VALUE) { return null; } } return new Float((float)doubleValue); } } commons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/routines/ISBNValidator.java100644 765 0 22245 11711227701 34247 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines; import java.io.Serializable; import org.apache.commons.validator.routines.checkdigit.EAN13CheckDigit; import org.apache.commons.validator.routines.checkdigit.ISBN10CheckDigit; import org.apache.commons.validator.routines.checkdigit.CheckDigitException; /** * ISBN-10 and ISBN-13 Code Validation. *

    * This validator validates the code is either a valid ISBN-10 * (using a {@link CodeValidator} with the {@link ISBN10CheckDigit}) * or a valid ISBN-13 code (using a {@link CodeValidator} with the * the {@link EAN13CheckDigit} routine). *

    * The validate() methods return the ISBN code with formatting * characters removed if valid or null if invalid. *

    * This validator also provides the facility to convert ISBN-10 codes to * ISBN-13 if the convert property is true. *

    * From 1st January 2007 the book industry will start to use a new 13 digit * ISBN number (rather than this 10 digit ISBN number). ISBN-13 codes are * EAN * codes, for more information see:

    * * * * @version $Revision: 1227719 $ $Date: 2012-01-05 18:45:51 +0100 (Thu, 05 Jan 2012) $ * @since Validator 1.4 */ public class ISBNValidator implements Serializable { private static final long serialVersionUID = 4319515687976420405L; private static final String SEP = "(?:\\-|\\s)"; private static final String GROUP = "(\\d{1,5})"; private static final String PUBLISHER = "(\\d{1,7})"; private static final String TITLE = "(\\d{1,6})"; /** * ISBN-10 consists of 4 groups of numbers separated by either dashes (-) * or spaces. The first group is 1-5 characters, second 1-7, third 1-6, * and fourth is 1 digit or an X. */ static final String ISBN10_REGEX = "^(?:(\\d{9}[0-9X])|(?:" + GROUP + SEP + PUBLISHER + SEP + TITLE + SEP + "([0-9X])))$"; /** * ISBN-13 consists of 5 groups of numbers separated by either dashes (-) * or spaces. The first group is 978 or 979, the second group is * 1-5 characters, third 1-7, fourth 1-6, and fifth is 1 digit. */ static final String ISBN13_REGEX = "^(978|979)(?:(\\d{10})|(?:" + SEP + GROUP + SEP + PUBLISHER + SEP + TITLE + SEP + "([0-9])))$"; /** ISBN Code Validator (which converts ISBN-10 codes to ISBN-13 */ private static final ISBNValidator ISBN_VALIDATOR = new ISBNValidator(); /** ISBN Code Validator (which converts ISBN-10 codes to ISBN-13 */ private static final ISBNValidator ISBN_VALIDATOR_NO_CONVERT = new ISBNValidator(false); /** ISBN-10 Code Validator */ private CodeValidator isbn10Validator = new CodeValidator(ISBN10_REGEX, 10, ISBN10CheckDigit.ISBN10_CHECK_DIGIT); /** ISBN-13 Code Validator */ private CodeValidator isbn13Validator = new CodeValidator(ISBN13_REGEX, 13, EAN13CheckDigit.EAN13_CHECK_DIGIT); private final boolean convert; /** * Return a singleton instance of the ISBN validator which * converts ISBN-10 codes to ISBN-13. * * @return A singleton instance of the ISBN validator. */ public static ISBNValidator getInstance() { return ISBN_VALIDATOR; } /** * Return a singleton instance of the ISBN validator specifying * whether ISBN-10 codes should be converted to ISBN-13. * * @param convert true if valid ISBN-10 codes * should be converted to ISBN-13 codes or false * if valid ISBN-10 codes should be returned unchanged. * @return A singleton instance of the ISBN validator. */ public static ISBNValidator getInstance(boolean convert) { return (convert ? ISBN_VALIDATOR : ISBN_VALIDATOR_NO_CONVERT); } /** * Construct an ISBN validator which converts ISBN-10 codes * to ISBN-13. */ public ISBNValidator() { this(true); } /** * Construct an ISBN validator indicating whether * ISBN-10 codes should be converted to ISBN-13. * * @param convert true if valid ISBN-10 codes * should be converted to ISBN-13 codes or false * if valid ISBN-10 codes should be returned unchanged. */ public ISBNValidator(boolean convert) { this.convert = convert; } /** * Check the code is either a valid ISBN-10 or ISBN-13 code. * * @param code The code to validate. * @return true if a valid ISBN-10 or * ISBN-13 code, otherwise false. */ public boolean isValid(String code) { return (isValidISBN13(code) || isValidISBN10(code)); } /** * Check the code is a valid ISBN-10 code. * * @param code The code to validate. * @return true if a valid ISBN-10 * code, otherwise false. */ public boolean isValidISBN10(String code) { return isbn10Validator.isValid(code); } /** * Check the code is a valid ISBN-13 code. * * @param code The code to validate. * @return true if a valid ISBN-13 * code, otherwise false. */ public boolean isValidISBN13(String code) { return isbn13Validator.isValid(code); } /** * Check the code is either a valid ISBN-10 or ISBN-13 code. *

    * If valid, this method returns the ISBN code with * formatting characters removed (i.e. space or hyphen). *

    * Converts an ISBN-10 codes to ISBN-13 if * convertToISBN13 is true. * * @param code The code to validate. * @return A valid ISBN code if valid, otherwise null. */ public String validate(String code) { String result = validateISBN13(code); if (result == null) { result = validateISBN10(code); if (result != null && convert) { result = convertToISBN13(result); } } return result; } /** * Check the code is a valid ISBN-10 code. *

    * If valid, this method returns the ISBN-10 code with * formatting characters removed (i.e. space or hyphen). * * @param code The code to validate. * @return A valid ISBN-10 code if valid, * otherwise null. */ public String validateISBN10(String code) { Object result = isbn10Validator.validate(code); return (result == null ? null : result.toString()); } /** * Check the code is a valid ISBN-13 code. *

    * If valid, this method returns the ISBN-13 code with * formatting characters removed (i.e. space or hyphen). * * @param code The code to validate. * @return A valid ISBN-13 code if valid, * otherwise null. */ public String validateISBN13(String code) { Object result = isbn13Validator.validate(code); return (result == null ? null : result.toString()); } /** * Convert an ISBN-10 code to an ISBN-13 code. *

    * This method requires a valid ISBN-10 with NO formatting * characters. * * @param isbn10 The ISBN-10 code to convert * @return A converted ISBN-13 code or null * if the ISBN-10 code is not valid */ public String convertToISBN13(String isbn10) { if (isbn10 == null) { return null; } String input = isbn10.trim(); if (input.length() != 10) { throw new IllegalArgumentException("Invalid length " + input.length() + " for '" + input + "'"); } // Calculate the new ISBN-13 code String isbn13 = "978" + input.substring(0, 9); try { String checkDigit = isbn13Validator.getCheckDigit().calculate(isbn13); isbn13 += checkDigit; return isbn13; } catch (CheckDigitException e) { throw new IllegalArgumentException("Check digit error for '" + input + "' - " + e.getMessage()); } } } ././@LongLink100644 0 0 152 11711231552 10247 Lustar 0 0 commons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/routines/InetAddressValidator.javacommons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/routines/InetAddressValidator100644 765 0 6251 11711227701 34760 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines; import java.io.Serializable; /** *

    InetAddress validation and conversion routines (java.net.InetAddress).

    * *

    This class provides methods to validate a candidate IP address. * *

    * This class is a Singleton; you can retrieve the instance via the {@link #getInstance()} method. *

    * * @version $Revision: 1227719 $ * @since Validator 1.4 */ public class InetAddressValidator implements Serializable { private static final long serialVersionUID = -919201640201914789L; private static final String IPV4_REGEX = "^(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$"; /** * Singleton instance of this class. */ private static final InetAddressValidator VALIDATOR = new InetAddressValidator(); /** IPv4 RegexValidator */ private final RegexValidator ipv4Validator = new RegexValidator(IPV4_REGEX); /** * Returns the singleton instance of this validator. * @return the singleton instance of this validator */ public static InetAddressValidator getInstance() { return VALIDATOR; } /** * Checks if the specified string is a valid IP address. * @param inetAddress the string to validate * @return true if the string validates as an IP address */ public boolean isValid(String inetAddress) { return isValidInet4Address(inetAddress); } /** * Validates an IPv4 address. Returns true if valid. * @param inet4Address the IPv4 address to validate * @return true if the argument contains a valid IPv4 address */ public boolean isValidInet4Address(String inet4Address) { // verify that address conforms to generic IPv4 format String[] groups = ipv4Validator.match(inet4Address); if (groups == null) return false; // verify that address subgroups are legal for (int i = 0; i <= 3; i++) { String ipSegment = groups[i]; if (ipSegment == null || ipSegment.length() <= 0) { return false; } int iIpSegment = 0; try { iIpSegment = Integer.parseInt(ipSegment); } catch(NumberFormatException e) { return false; } if (iIpSegment > 255) { return false; } } return true; } } ././@LongLink100644 0 0 146 11711231552 10252 Lustar 0 0 commons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/routines/IntegerValidator.javacommons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/routines/IntegerValidator.jav100644 765 0 23122 11711227701 34743 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines; import java.text.Format; import java.util.Locale; /** *

    Integer Validation and Conversion routines (java.lang.Integer).

    * *

    This validator provides a number of methods for * validating/converting a String value to * a Integer using java.text.NumberFormat * to parse either:

    *
      *
    • using the default format for the default Locale
    • *
    • using a specified pattern with the default Locale
    • *
    • using the default format for a specified Locale
    • *
    • using a specified pattern with a specified Locale
    • *
    * *

    Use one of the isValid() methods to just validate or * one of the validate() methods to validate and receive a * converted Integer value.

    * *

    Once a value has been sucessfully converted the following * methods can be used to perform minimum, maximum and range checks:

    *
      *
    • minValue() checks whether the value is greater * than or equal to a specified minimum.
    • *
    • maxValue() checks whether the value is less * than or equal to a specified maximum.
    • *
    • isInRange() checks whether the value is within * a specified range of values.
    • *
    * *

    So that the same mechanism used for parsing an input value * for validation can be used to format output, corresponding * format() methods are also provided. That is you can * format either:

    *
      *
    • using the default format for the default Locale
    • *
    • using a specified pattern with the default Locale
    • *
    • using the default format for a specified Locale
    • *
    • using a specified pattern with a specified Locale
    • *
    * * @version $Revision: 1227719 $ $Date: 2012-01-05 18:45:51 +0100 (Thu, 05 Jan 2012) $ * @since Validator 1.3.0 */ public class IntegerValidator extends AbstractNumberValidator { private static final long serialVersionUID = 422081746310306596L; private static final IntegerValidator VALIDATOR = new IntegerValidator(); /** * Return a singleton instance of this validator. * @return A singleton instance of the IntegerValidator. */ public static IntegerValidator getInstance() { return VALIDATOR; } /** * Construct a strict instance. */ public IntegerValidator() { this(true, STANDARD_FORMAT); } /** *

    Construct an instance with the specified strict setting * and format type.

    * *

    The formatType specified what type of * NumberFormat is created - valid types * are:

    *
      *
    • AbstractNumberValidator.STANDARD_FORMAT -to create * standard number formats (the default).
    • *
    • AbstractNumberValidator.CURRENCY_FORMAT -to create * currency number formats.
    • *
    • AbstractNumberValidator.PERCENT_FORMAT -to create * percent number formats (the default).
    • *
    * * @param strict true if strict * Format parsing should be used. * @param formatType The NumberFormat type to * create for validation, default is STANDARD_FORMAT. */ public IntegerValidator(boolean strict, int formatType) { super(strict, formatType, false); } /** *

    Validate/convert an Integer using the default * Locale. * * @param value The value validation is being performed on. * @return The parsed Integer if valid or null * if invalid. */ public Integer validate(String value) { return (Integer)parse(value, (String)null, (Locale)null); } /** *

    Validate/convert an Integer using the * specified pattern. * * @param value The value validation is being performed on. * @param pattern The pattern used to validate the value against. * @return The parsed Integer if valid or null if invalid. */ public Integer validate(String value, String pattern) { return (Integer)parse(value, pattern, (Locale)null); } /** *

    Validate/convert an Integer using the * specified Locale. * * @param value The value validation is being performed on. * @param locale The locale to use for the number format, system default if null. * @return The parsed Integer if valid or null if invalid. */ public Integer validate(String value, Locale locale) { return (Integer)parse(value, (String)null, locale); } /** *

    Validate/convert a Integer using the * specified pattern and/ or Locale. * * @param value The value validation is being performed on. * @param pattern The pattern used to validate the value against, or the * default for the Locale if null. * @param locale The locale to use for the date format, system default if null. * @return The parsed Integer if valid or null if invalid. */ public Integer validate(String value, String pattern, Locale locale) { return (Integer)parse(value, pattern, locale); } /** * Check if the value is within a specified range. * * @param value The Number value to check. * @param min The minimum value of the range. * @param max The maximum value of the range. * @return true if the value is within the * specified range. */ public boolean isInRange(int value, int min, int max) { return (value >= min && value <= max); } /** * Check if the value is within a specified range. * * @param value The Number value to check. * @param min The minimum value of the range. * @param max The maximum value of the range. * @return true if the value is within the * specified range. */ public boolean isInRange(Integer value, int min, int max) { return isInRange(value.intValue(), min, max); } /** * Check if the value is greater than or equal to a minimum. * * @param value The value validation is being performed on. * @param min The minimum value. * @return true if the value is greater than * or equal to the minimum. */ public boolean minValue(int value, int min) { return (value >= min); } /** * Check if the value is greater than or equal to a minimum. * * @param value The value validation is being performed on. * @param min The minimum value. * @return true if the value is greater than * or equal to the minimum. */ public boolean minValue(Integer value, int min) { return minValue(value.intValue(), min); } /** * Check if the value is less than or equal to a maximum. * * @param value The value validation is being performed on. * @param max The maximum value. * @return true if the value is less than * or equal to the maximum. */ public boolean maxValue(int value, int max) { return (value <= max); } /** * Check if the value is less than or equal to a maximum. * * @param value The value validation is being performed on. * @param max The maximum value. * @return true if the value is less than * or equal to the maximum. */ public boolean maxValue(Integer value, int max) { return maxValue(value.intValue(), max); } /** *

    Perform further validation and convert the Number to * an Integer.

    * * @param value The parsed Number object created. * @param formatter The Format used to parse the value with. * @return The parsed Number converted to an * Integer if valid or null if invalid. */ protected Object processParsedValue(Object value, Format formatter) { long longValue = ((Number)value).longValue(); if (longValue < Integer.MIN_VALUE || longValue > Integer.MAX_VALUE) { return null; } else { return new Integer((int)longValue); } } } commons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/routines/LongValidator.java100644 765 0 22307 11711227701 34412 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines; import java.text.Format; import java.util.Locale; /** *

    Long Validation and Conversion routines (java.lang.Long).

    * *

    This validator provides a number of methods for * validating/converting a String value to * a Long using java.text.NumberFormat * to parse either:

    *
      *
    • using the default format for the default Locale
    • *
    • using a specified pattern with the default Locale
    • *
    • using the default format for a specified Locale
    • *
    • using a specified pattern with a specified Locale
    • *
    * *

    Use one of the isValid() methods to just validate or * one of the validate() methods to validate and receive a * converted Long value.

    * *

    Once a value has been sucessfully converted the following * methods can be used to perform minimum, maximum and range checks:

    *
      *
    • minValue() checks whether the value is greater * than or equal to a specified minimum.
    • *
    • maxValue() checks whether the value is less * than or equal to a specified maximum.
    • *
    • isInRange() checks whether the value is within * a specified range of values.
    • *
    * *

    So that the same mechanism used for parsing an input value * for validation can be used to format output, corresponding * format() methods are also provided. That is you can * format either:

    *
      *
    • using a specified pattern
    • *
    • using the format for a specified Locale
    • *
    • using the format for the default Locale
    • *
    * * @version $Revision: 1227719 $ $Date: 2012-01-05 18:45:51 +0100 (Thu, 05 Jan 2012) $ * @since Validator 1.3.0 */ public class LongValidator extends AbstractNumberValidator { private static final long serialVersionUID = -5117231731027866098L; private static final LongValidator VALIDATOR = new LongValidator(); /** * Return a singleton instance of this validator. * @return A singleton instance of the LongValidator. */ public static LongValidator getInstance() { return VALIDATOR; } /** * Construct a strict instance. */ public LongValidator() { this(true, STANDARD_FORMAT); } /** *

    Construct an instance with the specified strict setting * and format type.

    * *

    The formatType specified what type of * NumberFormat is created - valid types * are:

    *
      *
    • AbstractNumberValidator.STANDARD_FORMAT -to create * standard number formats (the default).
    • *
    • AbstractNumberValidator.CURRENCY_FORMAT -to create * currency number formats.
    • *
    • AbstractNumberValidator.PERCENT_FORMAT -to create * percent number formats (the default).
    • *
    * * @param strict true if strict * Format parsing should be used. * @param formatType The NumberFormat type to * create for validation, default is STANDARD_FORMAT. */ public LongValidator(boolean strict, int formatType) { super(strict, formatType, false); } /** *

    Validate/convert a Long using the default * Locale. * * @param value The value validation is being performed on. * @return The parsed Long if valid or null * if invalid. */ public Long validate(String value) { return (Long)parse(value, (String)null, (Locale)null); } /** *

    Validate/convert a Long using the * specified pattern. * * @param value The value validation is being performed on. * @param pattern The pattern used to validate the value against. * @return The parsed Long if valid or null if invalid. */ public Long validate(String value, String pattern) { return (Long)parse(value, pattern, (Locale)null); } /** *

    Validate/convert a Long using the * specified Locale. * * @param value The value validation is being performed on. * @param locale The locale to use for the number format, system default if null. * @return The parsed Long if valid or null if invalid. */ public Long validate(String value, Locale locale) { return (Long)parse(value, (String)null, locale); } /** *

    Validate/convert a Long using the * specified pattern and/ or Locale. * * @param value The value validation is being performed on. * @param pattern The pattern used to validate the value against, or the * default for the Locale if null. * @param locale The locale to use for the date format, system default if null. * @return The parsed Long if valid or null if invalid. */ public Long validate(String value, String pattern, Locale locale) { return (Long)parse(value, pattern, locale); } /** * Check if the value is within a specified range. * * @param value The Number value to check. * @param min The minimum value of the range. * @param max The maximum value of the range. * @return true if the value is within the * specified range. */ public boolean isInRange(long value, long min, long max) { return (value >= min && value <= max); } /** * Check if the value is within a specified range. * * @param value The Number value to check. * @param min The minimum value of the range. * @param max The maximum value of the range. * @return true if the value is within the * specified range. */ public boolean isInRange(Long value, long min, long max) { return isInRange(value.longValue(), min, max); } /** * Check if the value is greater than or equal to a minimum. * * @param value The value validation is being performed on. * @param min The minimum value. * @return true if the value is greater than * or equal to the minimum. */ public boolean minValue(long value, long min) { return (value >= min); } /** * Check if the value is greater than or equal to a minimum. * * @param value The value validation is being performed on. * @param min The minimum value. * @return true if the value is greater than * or equal to the minimum. */ public boolean minValue(Long value, long min) { return minValue(value.longValue(), min); } /** * Check if the value is less than or equal to a maximum. * * @param value The value validation is being performed on. * @param max The maximum value. * @return true if the value is less than * or equal to the maximum. */ public boolean maxValue(long value, long max) { return (value <= max); } /** * Check if the value is less than or equal to a maximum. * * @param value The value validation is being performed on. * @param max The maximum value. * @return true if the value is less than * or equal to the maximum. */ public boolean maxValue(Long value, long max) { return maxValue(value.longValue(), max); } /** * Convert the parsed value to a Long. * * @param value The parsed Number object created. * @param formatter The Format used to parse the value with. * @return The parsed Number converted to a * Long. */ protected Object processParsedValue(Object value, Format formatter) { if (value instanceof Long) { return value; } else { return new Long(((Number)value).longValue()); } } } ././@LongLink100644 0 0 146 11711231552 10252 Lustar 0 0 commons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/routines/PercentValidator.javacommons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/routines/PercentValidator.jav100644 765 0 11721 11711227701 34750 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines; import java.text.DecimalFormat; import java.text.Format; import java.math.BigDecimal; /** *

    Percentage Validation and Conversion routines (java.math.BigDecimal).

    * *

    This is one implementation of a percent validator that has the following features:

    *
      *
    • It is lenient about the the presence of the percent symbol
    • *
    • It converts the percent to a java.math.BigDecimal
    • *
    * *

    However any of the number validators can be used for percent validation. * For example, if you wanted a percent validator that converts to a * java.lang.Float then you can simply instantiate an * FloatValidator with the appropriate format type:

    * *

    ... = new FloatValidator(false, FloatValidator.PERCENT_FORMAT);

    * *

    Pick the appropriate validator, depending on the type (i.e Float, Double or BigDecimal) * you want the percent converted to. Please note, it makes no sense to use * one of the validators that doesn't handle fractions (i.e. byte, short, integer, long * and BigInteger) since percentages are converted to fractions (i.e 50% is * converted to 0.5).

    * * @version $Revision: 1227719 $ $Date: 2012-01-05 18:45:51 +0100 (Thu, 05 Jan 2012) $ * @since Validator 1.3.0 */ public class PercentValidator extends BigDecimalValidator { private static final long serialVersionUID = -3508241924961535772L; private static final PercentValidator VALIDATOR = new PercentValidator(); /** DecimalFormat's percent (thousand multiplier) symbol */ private static final char PERCENT_SYMBOL = '%'; private static final BigDecimal POINT_ZERO_ONE = new BigDecimal("0.01"); /** * Return a singleton instance of this validator. * @return A singleton instance of the PercentValidator. */ public static BigDecimalValidator getInstance() { return VALIDATOR; } /** * Construct a strict instance. */ public PercentValidator() { this(true); } /** * Construct an instance with the specified strict setting. * * @param strict true if strict * Format parsing should be used. */ public PercentValidator(boolean strict) { super(strict, PERCENT_FORMAT, true); } /** *

    Parse the value with the specified Format.

    * *

    This implementation is lenient whether the currency symbol * is present or not. The default NumberFormat * behaviour is for the parsing to "fail" if the currency * symbol is missing. This method re-parses with a format * without the currency symbol if it fails initially.

    * * @param value The value to be parsed. * @param formatter The Format to parse the value with. * @return The parsed value if valid or null if invalid. */ protected Object parse(String value, Format formatter) { // Initial parse of the value BigDecimal parsedValue = (BigDecimal)super.parse(value, formatter); if (parsedValue != null || !(formatter instanceof DecimalFormat)) { return parsedValue; } // Re-parse using a pattern without the percent symbol DecimalFormat decimalFormat = (DecimalFormat)formatter; String pattern = decimalFormat.toPattern(); if (pattern.indexOf(PERCENT_SYMBOL) >= 0) { StringBuffer buffer = new StringBuffer(pattern.length()); for (int i = 0; i < pattern.length(); i++) { if (pattern.charAt(i) != PERCENT_SYMBOL) { buffer.append(pattern.charAt(i)); } } decimalFormat.applyPattern(buffer.toString()); parsedValue = (BigDecimal)super.parse(value, decimalFormat); // If parsed OK, divide by 100 to get percent if (parsedValue != null) { parsedValue = parsedValue.multiply(POINT_ZERO_ONE); } } return parsedValue; } } commons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/routines/RegexValidator.java100644 765 0 16565 11711227701 34576 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines; import java.io.Serializable; import java.util.regex.Pattern; import java.util.regex.Matcher; /** * Regular Expression validation (using JDK 1.4+ regex support). *

    * Construct the validator either for a single regular expression or a set (array) of * regular expressions. By default validation is case sensitive but constructors * are provided to allow case in-sensitive validation. For example to create * a validator which does case in-sensitive validation for a set of regular * expressions: *

     *         String[] regexs = new String[] {...};
     *         RegexValidator validator = new RegexValidator(regexs, false);
     * 
    *

    *

      *
    • Validate true or false:
    • *
        *
      • boolean valid = validator.isValid(value);
      • *
      *
    • Validate returning an aggregated String of the matched groups:
    • *
        *
      • String result = validator.validate(value);
      • *
      *
    • Validate returning the matched groups:
    • *
        *
      • String[] result = validator.match(value);
      • *
      *
    *

    * Cached instances pre-compile and re-use {@link Pattern}(s) - which according * to the {@link Pattern} API are safe to use in a multi-threaded environment. * * @version $Revision: 1227719 $ $Date: 2012-01-05 18:45:51 +0100 (Thu, 05 Jan 2012) $ * @since Validator 1.4 */ public class RegexValidator implements Serializable { private static final long serialVersionUID = -8832409930574867162L; private final Pattern[] patterns; /** * Construct a case sensitive validator for a single * regular expression. * * @param regex The regular expression this validator will * validate against */ public RegexValidator(String regex) { this(regex, true); } /** * Construct a validator for a single regular expression * with the specified case sensitivity. * * @param regex The regular expression this validator will * validate against * @param caseSensitive when true matching is case * sensitive, otherwise matching is case in-sensitive */ public RegexValidator(String regex, boolean caseSensitive) { this(new String[] {regex}, caseSensitive); } /** * Construct a case sensitive validator that matches any one * of the set of regular expressions. * * @param regexs The set of regular expressions this validator will * validate against */ public RegexValidator(String[] regexs) { this(regexs, true); } /** * Construct a validator that matches any one of the set of regular * expressions with the specified case sensitivity. * * @param regexs The set of regular expressions this validator will * validate against * @param caseSensitive when true matching is case * sensitive, otherwise matching is case in-sensitive */ public RegexValidator(String[] regexs, boolean caseSensitive) { if (regexs == null || regexs.length == 0) { throw new IllegalArgumentException("Regular expressions are missing"); } patterns = new Pattern[regexs.length]; int flags = (caseSensitive ? 0: Pattern.CASE_INSENSITIVE); for (int i = 0; i < regexs.length; i++) { if (regexs[i] == null || regexs[i].length() == 0) { throw new IllegalArgumentException("Regular expression[" + i + "] is missing"); } patterns[i] = Pattern.compile(regexs[i], flags); } } /** * Validate a value against the set of regular expressions. * * @param value The value to validate. * @return true if the value is valid * otherwise false. */ public boolean isValid(String value) { if (value == null) { return false; } for (int i = 0; i < patterns.length; i++) { if (patterns[i].matcher(value).matches()) { return true; } } return false; } /** * Validate a value against the set of regular expressions * returning the array of matched groups. * * @param value The value to validate. * @return String array of the groups matched if * valid or null if invalid */ public String[] match(String value) { if (value == null) { return null; } for (int i = 0; i < patterns.length; i++) { Matcher matcher = patterns[i].matcher(value); if (matcher.matches()) { int count = matcher.groupCount(); String[] groups = new String[count]; for (int j = 0; j < count; j++) { groups[j] = matcher.group(j+1); } return groups; } } return null; } /** * Validate a value against the set of regular expressions * returning a String value of the aggregated groups. * * @param value The value to validate. * @return Aggregated String value comprised of the * groups matched if valid or null if invalid */ public String validate(String value) { if (value == null) { return null; } for (int i = 0; i < patterns.length; i++) { Matcher matcher = patterns[i].matcher(value); if (matcher.matches()) { int count = matcher.groupCount(); if (count == 1) { return matcher.group(1); } StringBuffer buffer = new StringBuffer(); for (int j = 0; j < count; j++) { String component = matcher.group(j+1); if (component != null) { buffer.append(component); } } return buffer.toString(); } } return null; } /** * Provide a String representation of this validator. * @return A String representation of this validator */ public String toString() { StringBuffer buffer = new StringBuffer(); buffer.append("RegexValidator{"); for (int i = 0; i < patterns.length; i++) { if (i > 0) { buffer.append(","); } buffer.append(patterns[i].pattern()); } buffer.append("}"); return buffer.toString(); } } commons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/routines/ShortValidator.java100644 765 0 23047 11711227701 34614 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines; import java.text.Format; import java.util.Locale; /** *

    Short Validation and Conversion routines (java.lang.Short).

    * *

    This validator provides a number of methods for * validating/converting a String value to * a Short using java.text.NumberFormat * to parse either:

    *
      *
    • using the default format for the default Locale
    • *
    • using a specified pattern with the default Locale
    • *
    • using the default format for a specified Locale
    • *
    • using a specified pattern with a specified Locale
    • *
    * *

    Use one of the isValid() methods to just validate or * one of the validate() methods to validate and receive a * converted Short value.

    * *

    Once a value has been sucessfully converted the following * methods can be used to perform minimum, maximum and range checks:

    *
      *
    • minValue() checks whether the value is greater * than or equal to a specified minimum.
    • *
    • maxValue() checks whether the value is less * than or equal to a specified maximum.
    • *
    • isInRange() checks whether the value is within * a specified range of values.
    • *
    * *

    So that the same mechanism used for parsing an input value * for validation can be used to format output, corresponding * format() methods are also provided. That is you can * format either:

    *
      *
    • using the default format for the default Locale
    • *
    • using a specified pattern with the default Locale
    • *
    • using the default format for a specified Locale
    • *
    • using a specified pattern with a specified Locale
    • *
    * * @version $Revision: 1227719 $ $Date: 2012-01-05 18:45:51 +0100 (Thu, 05 Jan 2012) $ * @since Validator 1.3.0 */ public class ShortValidator extends AbstractNumberValidator { private static final long serialVersionUID = -5227510699747787066L; private static final ShortValidator VALIDATOR = new ShortValidator(); /** * Return a singleton instance of this validator. * @return A singleton instance of the ShortValidator. */ public static ShortValidator getInstance() { return VALIDATOR; } /** * Construct a strict instance. */ public ShortValidator() { this(true, STANDARD_FORMAT); } /** *

    Construct an instance with the specified strict setting * and format type.

    * *

    The formatType specified what type of * NumberFormat is created - valid types * are:

    *
      *
    • AbstractNumberValidator.STANDARD_FORMAT -to create * standard number formats (the default).
    • *
    • AbstractNumberValidator.CURRENCY_FORMAT -to create * currency number formats.
    • *
    • AbstractNumberValidator.PERCENT_FORMAT -to create * percent number formats (the default).
    • *
    * * @param strict true if strict * Format parsing should be used. * @param formatType The NumberFormat type to * create for validation, default is STANDARD_FORMAT. */ public ShortValidator(boolean strict, int formatType) { super(strict, formatType, false); } /** *

    Validate/convert a Short using the default * Locale. * * @param value The value validation is being performed on. * @return The parsed Short if valid or null * if invalid. */ public Short validate(String value) { return (Short)parse(value, (String)null, (Locale)null); } /** *

    Validate/convert a Short using the * specified pattern. * * @param value The value validation is being performed on. * @param pattern The pattern used to validate the value against. * @return The parsed Short if valid or null if invalid. */ public Short validate(String value, String pattern) { return (Short)parse(value, pattern, (Locale)null); } /** *

    Validate/convert a Short using the * specified Locale. * * @param value The value validation is being performed on. * @param locale The locale to use for the number format, system default if null. * @return The parsed Short if valid or null if invalid. */ public Short validate(String value, Locale locale) { return (Short)parse(value, (String)null, locale); } /** *

    Validate/convert a Short using the * specified pattern and/ or Locale. * * @param value The value validation is being performed on. * @param pattern The pattern used to validate the value against, or the * default for the Locale if null. * @param locale The locale to use for the date format, system default if null. * @return The parsed Short if valid or null if invalid. */ public Short validate(String value, String pattern, Locale locale) { return (Short)parse(value, pattern, locale); } /** * Check if the value is within a specified range. * * @param value The Number value to check. * @param min The minimum value of the range. * @param max The maximum value of the range. * @return true if the value is within the * specified range. */ public boolean isInRange(short value, short min, short max) { return (value >= min && value <= max); } /** * Check if the value is within a specified range. * * @param value The Number value to check. * @param min The minimum value of the range. * @param max The maximum value of the range. * @return true if the value is within the * specified range. */ public boolean isInRange(Short value, short min, short max) { return isInRange(value.shortValue(), min, max); } /** * Check if the value is greater than or equal to a minimum. * * @param value The value validation is being performed on. * @param min The minimum value. * @return true if the value is greater than * or equal to the minimum. */ public boolean minValue(short value, short min) { return (value >= min); } /** * Check if the value is greater than or equal to a minimum. * * @param value The value validation is being performed on. * @param min The minimum value. * @return true if the value is greater than * or equal to the minimum. */ public boolean minValue(Short value, short min) { return minValue(value.shortValue(), min); } /** * Check if the value is less than or equal to a maximum. * * @param value The value validation is being performed on. * @param max The maximum value. * @return true if the value is less than * or equal to the maximum. */ public boolean maxValue(short value, short max) { return (value <= max); } /** * Check if the value is less than or equal to a maximum. * * @param value The value validation is being performed on. * @param max The maximum value. * @return true if the value is less than * or equal to the maximum. */ public boolean maxValue(Short value, short max) { return maxValue(value.shortValue(), max); } /** *

    Perform further validation and convert the Number to * a Short.

    * * @param value The parsed Number object created. * @param formatter The Format used to parse the value with. * @return The parsed Number converted to a * Short if valid or null if invalid. */ protected Object processParsedValue(Object value, Format formatter) { long longValue = ((Number)value).longValue(); if (longValue < Short.MIN_VALUE || longValue > Short.MAX_VALUE) { return null; } else { return new Short((short)longValue); } } } commons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/routines/TimeValidator.java100644 765 0 30003 11711227701 34401 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines; import java.text.DateFormat; import java.text.Format; import java.util.Calendar; import java.util.Locale; import java.util.TimeZone; /** *

    Time Validation and Conversion routines (java.util.Calendar).

    * *

    This validator provides a number of methods for validating/converting * a String time value to a java.util.Calendar using * java.text.DateFormat to parse either:

    *
      *
    • using the default format for the default Locale
    • *
    • using a specified pattern with the default Locale
    • *
    • using the default format for a specified Locale
    • *
    • using a specified pattern with a specified Locale
    • *
    * *

    For each of the above mechanisms, conversion method (i.e the * validate methods) implementations are provided which * either use the default TimeZone or allow the * TimeZone to be specified.

    * *

    Use one of the isValid() methods to just validate or * one of the validate() methods to validate and receive a * converted Calendar value for the time.

    * *

    Implementations of the validate() method are provided * to create Calendar objects for different time zones * if the system default is not appropriate.

    * *

    Alternatively the CalendarValidator's adjustToTimeZone() method * can be used to adjust the TimeZone of the Calendar * object afterwards.

    * *

    Once a value has been sucessfully converted the following * methods can be used to perform various time comparison checks:

    *
      *
    • compareTime() compares the hours, minutes, seconds * and milliseconds of two calendars, returing 0, -1 or +1 indicating * whether the first time is equal, before or after the second.
    • *
    • compareSeconds() compares the hours, minutes and * seconds of two times, returing 0, -1 or +1 indicating * whether the first is equal to, before or after the second.
    • *
    • compareMinutes() compares the hours and minutes * two times, returing 0, -1 or +1 indicating * whether the first is equal to, before or after the second.
    • *
    • compareHours() compares the hours * of two times, returing 0, -1 or +1 indicating * whether the first is equal to, before or after the second.
    • *
    * *

    So that the same mechanism used for parsing an input value * for validation can be used to format output, corresponding * format() methods are also provided. That is you can * format either:

    *
      *
    • using a specified pattern
    • *
    • using the format for a specified Locale
    • *
    • using the format for the default Locale
    • *
    * * @version $Revision: 1227719 $ $Date: 2012-01-05 18:45:51 +0100 (Thu, 05 Jan 2012) $ * @since Validator 1.3.0 */ public class TimeValidator extends AbstractCalendarValidator { private static final long serialVersionUID = 3494007492269691581L; private static final TimeValidator VALIDATOR = new TimeValidator(); /** * Return a singleton instance of this validator. * @return A singleton instance of the TimeValidator. */ public static TimeValidator getInstance() { return VALIDATOR; } /** * Construct a strict instance with short * time style. */ public TimeValidator() { this(true, DateFormat.SHORT); } /** * Construct an instance with the specified strict * and time style parameters. * * @param strict true if strict * Format parsing should be used. * @param timeStyle the time style to use for Locale validation. */ public TimeValidator(boolean strict, int timeStyle) { super(strict, -1, timeStyle); } /** *

    Validate/convert a time using the default Locale * and TimeZone. * * @param value The value validation is being performed on. * @return The parsed Calendar if valid or null * if invalid. */ public Calendar validate(String value) { return (Calendar)parse(value, (String)null, (Locale)null, (TimeZone)null); } /** *

    Validate/convert a time using the specified TimeZone * and default Locale. * * @param value The value validation is being performed on. * @param timeZone The Time Zone used to parse the time, system default if null. * @return The parsed Calendar if valid or null if invalid. */ public Calendar validate(String value, TimeZone timeZone) { return (Calendar)parse(value, (String)null, (Locale)null, timeZone); } /** *

    Validate/convert a time using the specified pattern and * default TimeZone. * * @param value The value validation is being performed on. * @param pattern The pattern used to validate the value against. * @return The parsed Calendar if valid or null if invalid. */ public Calendar validate(String value, String pattern) { return (Calendar)parse(value, pattern, (Locale)null, (TimeZone)null); } /** *

    Validate/convert a time using the specified pattern * and TimeZone. * * @param value The value validation is being performed on. * @param pattern The pattern used to validate the value against. * @param timeZone The Time Zone used to parse the time, system default if null. * @return The parsed Calendar if valid or null if invalid. */ public Calendar validate(String value, String pattern, TimeZone timeZone) { return (Calendar)parse(value, pattern, (Locale)null, timeZone); } /** *

    Validate/convert a time using the specified Locale * default TimeZone. * * @param value The value validation is being performed on. * @param locale The locale to use for the time format, system default if null. * @return The parsed Calendar if valid or null if invalid. */ public Calendar validate(String value, Locale locale) { return (Calendar)parse(value, (String)null, locale, (TimeZone)null); } /** *

    Validate/convert a time using the specified specified Locale * and TimeZone. * * @param value The value validation is being performed on. * @param locale The locale to use for the time format, system default if null. * @param timeZone The Time Zone used to parse the time, system default if null. * @return The parsed Calendar if valid or null if invalid. */ public Calendar validate(String value, Locale locale, TimeZone timeZone) { return (Calendar)parse(value, (String)null, locale, timeZone); } /** *

    Validate/convert a time using the specified pattern and Locale * and the default TimeZone. * * @param value The value validation is being performed on. * @param pattern The pattern used to validate the value against, or the * default for the Locale if null. * @param locale The locale to use for the date format, system default if null. * @return The parsed Calendar if valid or null if invalid. */ public Calendar validate(String value, String pattern, Locale locale) { return (Calendar)parse(value, pattern, locale, (TimeZone)null); } /** *

    Validate/convert a time using the specified pattern, Locale * and TimeZone. * * @param value The value validation is being performed on. * @param pattern The pattern used to validate the value against, or the * default for the Locale if null. * @param locale The locale to use for the date format, system default if null. * @param timeZone The Time Zone used to parse the date, system default if null. * @return The parsed Calendar if valid or null if invalid. */ public Calendar validate(String value, String pattern, Locale locale, TimeZone timeZone) { return (Calendar)parse(value, pattern, locale, timeZone); } /** *

    Compare Times (hour, minute, second and millisecond - not date).

    * * @param value The Calendar value to check. * @param compare The Calendar to compare the value to. * @return Zero if the hours are equal, -1 if first * time is less than the seconds and +1 if the first * time is greater than. */ public int compareTime(Calendar value, Calendar compare) { return compareTime(value, compare, Calendar.MILLISECOND); } /** *

    Compare Seconds (hours, minutes and seconds).

    * * @param value The Calendar value to check. * @param compare The Calendar to compare the value to. * @return Zero if the hours are equal, -1 if first * parameter's seconds are less than the seconds and +1 if the first * parameter's seconds are greater than. */ public int compareSeconds(Calendar value, Calendar compare) { return compareTime(value, compare, Calendar.SECOND); } /** *

    Compare Minutes (hours and minutes).

    * * @param value The Calendar value to check. * @param compare The Calendar to compare the value to. * @return Zero if the hours are equal, -1 if first * parameter's minutes are less than the seconds and +1 if the first * parameter's minutes are greater than. */ public int compareMinutes(Calendar value, Calendar compare) { return compareTime(value, compare, Calendar.MINUTE); } /** *

    Compare Hours.

    * * @param value The Calendar value to check. * @param compare The Calendar to compare the value to. * @return Zero if the hours are equal, -1 if first * parameter's hour is less than the seconds and +1 if the first * parameter's hour is greater than. */ public int compareHours(Calendar value, Calendar compare) { return compareTime(value, compare, Calendar.HOUR_OF_DAY); } /** *

    Convert the parsed Date to a Calendar.

    * * @param value The parsed Date object created. * @param formatter The Format used to parse the value with. * @return The parsed value converted to a Calendar. */ protected Object processParsedValue(Object value, Format formatter) { return ((DateFormat)formatter).getCalendar(); } } commons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/routines/UrlValidator.java100644 765 0 40776 11711227701 34267 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines; import java.io.Serializable; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; /** *

    URL Validation routines.

    * Behavior of validation is modified by passing in options: *
  • ALLOW_2_SLASHES - [FALSE] Allows double '/' characters in the path * component.
  • *
  • NO_FRAGMENT- [FALSE] By default fragments are allowed, if this option is * included then fragments are flagged as illegal.
  • *
  • ALLOW_ALL_SCHEMES - [FALSE] By default only http, https, and ftp are * considered valid schemes. Enabling this option will let any scheme pass validation.
  • * *

    Originally based in on php script by Debbie Dyer, validation.php v1.2b, Date: 03/07/02, * http://javascript.internet.com. However, this validation now bears little resemblance * to the php original.

    *
     *   Example of usage:
     *   Construct a UrlValidator with valid schemes of "http", and "https".
     *
     *    String[] schemes = {"http","https"}.
     *    UrlValidator urlValidator = new UrlValidator(schemes);
     *    if (urlValidator.isValid("ftp://foo.bar.com/")) {
     *       System.out.println("url is valid");
     *    } else {
     *       System.out.println("url is invalid");
     *    }
     *
     *    prints "url is invalid"
     *   If instead the default constructor is used.
     *
     *    UrlValidator urlValidator = new UrlValidator();
     *    if (urlValidator.isValid("ftp://foo.bar.com/")) {
     *       System.out.println("url is valid");
     *    } else {
     *       System.out.println("url is invalid");
     *    }
     *
     *   prints out "url is valid"
     *  
    * * @see * * Uniform Resource Identifiers (URI): Generic Syntax * * * @version $Revision: 1227719 $ $Date: 2012-01-05 18:45:51 +0100 (Thu, 05 Jan 2012) $ * @since Validator 1.4 */ public class UrlValidator implements Serializable { private static final long serialVersionUID = 7557161713937335013L; /** * Allows all validly formatted schemes to pass validation instead of * supplying a set of valid schemes. */ public static final long ALLOW_ALL_SCHEMES = 1 << 0; /** * Allow two slashes in the path component of the URL. */ public static final long ALLOW_2_SLASHES = 1 << 1; /** * Enabling this options disallows any URL fragments. */ public static final long NO_FRAGMENTS = 1 << 2; /** * Allow local URLs, such as http://localhost/ or http://machine/ . * This enables a broad-brush check, for complex local machine name * validation requirements you should create your validator with * a {@link RegexValidator} instead ({@link #UrlValidator(RegexValidator, long)}) */ public static final long ALLOW_LOCAL_URLS = 1 << 3; // Drop numeric, and "+-." for now private static final String AUTHORITY_CHARS_REGEX = "\\p{Alnum}\\-\\."; /** * This expression derived/taken from the BNF for URI (RFC2396). */ private static final String URL_REGEX = "^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?"; // 12 3 4 5 6 7 8 9 private static final Pattern URL_PATTERN = Pattern.compile(URL_REGEX); /** * Schema/Protocol (ie. http:, ftp:, file:, etc). */ private static final int PARSE_URL_SCHEME = 2; /** * Includes hostname/ip and port number. */ private static final int PARSE_URL_AUTHORITY = 4; private static final int PARSE_URL_PATH = 5; private static final int PARSE_URL_QUERY = 7; private static final int PARSE_URL_FRAGMENT = 9; /** * Protocol (ie. http:, ftp:,https:). */ private static final String SCHEME_REGEX = "^\\p{Alpha}[\\p{Alnum}\\+\\-\\.]*"; private static final Pattern SCHEME_PATTERN = Pattern.compile(SCHEME_REGEX); private static final String AUTHORITY_REGEX = "^([" + AUTHORITY_CHARS_REGEX + "]*)(:\\d*)?(.*)?"; // 1 2 3 4 private static final Pattern AUTHORITY_PATTERN = Pattern.compile(AUTHORITY_REGEX); private static final int PARSE_AUTHORITY_HOST_IP = 1; private static final int PARSE_AUTHORITY_PORT = 2; /** * Should always be empty. */ private static final int PARSE_AUTHORITY_EXTRA = 3; private static final String PATH_REGEX = "^(/[-\\w:@&?=+,.!/~*'%$_;\\(\\)]*)?$"; private static final Pattern PATH_PATTERN = Pattern.compile(PATH_REGEX); private static final String QUERY_REGEX = "^(.*)$"; private static final Pattern QUERY_PATTERN = Pattern.compile(QUERY_REGEX); private static final String LEGAL_ASCII_REGEX = "^\\p{ASCII}+$"; private static final Pattern ASCII_PATTERN = Pattern.compile(LEGAL_ASCII_REGEX); private static final String PORT_REGEX = "^:(\\d{1,5})$"; private static final Pattern PORT_PATTERN = Pattern.compile(PORT_REGEX); /** * Holds the set of current validation options. */ private final long options; /** * The set of schemes that are allowed to be in a URL. */ private final Set allowedSchemes; /** * Regular expressions used to manually validate authorities if IANA * domain name validation isn't desired. */ private final RegexValidator authorityValidator; /** * If no schemes are provided, default to this set. */ private static final String[] DEFAULT_SCHEMES = {"http", "https", "ftp"}; /** * Singleton instance of this class with default schemes and options. */ private static final UrlValidator DEFAULT_URL_VALIDATOR = new UrlValidator(); /** * Returns the singleton instance of this class with default schemes and options. * @return singleton instance with default schemes and options */ public static UrlValidator getInstance() { return DEFAULT_URL_VALIDATOR; } /** * Create a UrlValidator with default properties. */ public UrlValidator() { this(null); } /** * Behavior of validation is modified by passing in several strings options: * @param schemes Pass in one or more url schemes to consider valid, passing in * a null will default to "http,https,ftp" being valid. * If a non-null schemes is specified then all valid schemes must * be specified. Setting the ALLOW_ALL_SCHEMES option will * ignore the contents of schemes. */ public UrlValidator(String[] schemes) { this(schemes, 0L); } /** * Initialize a UrlValidator with the given validation options. * @param options The options should be set using the public constants declared in * this class. To set multiple options you simply add them together. For example, * ALLOW_2_SLASHES + NO_FRAGMENTS enables both of those options. */ public UrlValidator(long options) { this(null, null, options); } /** * Behavior of validation is modified by passing in options: * @param schemes The set of valid schemes. * @param options The options should be set using the public constants declared in * this class. To set multiple options you simply add them together. For example, * ALLOW_2_SLASHES + NO_FRAGMENTS enables both of those options. */ public UrlValidator(String[] schemes, long options) { this(schemes, null, options); } /** * Initialize a UrlValidator with the given validation options. * @param authorityValidator Regular expression validator used to validate the authority part * @param options Validation options. Set using the public constants of this class. * To set multiple options, simply add them together: *

    ALLOW_2_SLASHES + NO_FRAGMENTS

    * enables both of those options. */ public UrlValidator(RegexValidator authorityValidator, long options) { this(null, authorityValidator, options); } /** * Customizable constructor. Validation behavior is modifed by passing in options. * @param schemes the set of valid schemes * @param authorityValidator Regular expression validator used to validate the authority part * @param options Validation options. Set using the public constants of this class. * To set multiple options, simply add them together: *

    ALLOW_2_SLASHES + NO_FRAGMENTS

    * enables both of those options. */ public UrlValidator(String[] schemes, RegexValidator authorityValidator, long options) { this.options = options; if (isOn(ALLOW_ALL_SCHEMES)) { this.allowedSchemes = Collections.EMPTY_SET; } else { if (schemes == null) { schemes = DEFAULT_SCHEMES; } this.allowedSchemes = new HashSet(); this.allowedSchemes.addAll(Arrays.asList(schemes)); } this.authorityValidator = authorityValidator; } /** *

    Checks if a field has a valid url address.

    * * @param value The value validation is being performed on. A null * value is considered invalid. * @return true if the url is valid. */ public boolean isValid(String value) { if (value == null) { return false; } if (!ASCII_PATTERN.matcher(value).matches()) { return false; } // Check the whole url address structure Matcher urlMatcher = URL_PATTERN.matcher(value); if (!urlMatcher.matches()) { return false; } String scheme = urlMatcher.group(PARSE_URL_SCHEME); if (!isValidScheme(scheme)) { return false; } String authority = urlMatcher.group(PARSE_URL_AUTHORITY); if ("file".equals(scheme) && "".equals(authority)) { // Special case - file: allows an empty authority } else { // Validate the authority if (!isValidAuthority(authority)) { return false; } } if (!isValidPath(urlMatcher.group(PARSE_URL_PATH))) { return false; } if (!isValidQuery(urlMatcher.group(PARSE_URL_QUERY))) { return false; } if (!isValidFragment(urlMatcher.group(PARSE_URL_FRAGMENT))) { return false; } return true; } /** * Validate scheme. If schemes[] was initialized to a non null, * then only those scheme's are allowed. Note this is slightly different * than for the constructor. * @param scheme The scheme to validate. A null value is considered * invalid. * @return true if valid. */ protected boolean isValidScheme(String scheme) { if (scheme == null) { return false; } if (!SCHEME_PATTERN.matcher(scheme).matches()) { return false; } if (isOff(ALLOW_ALL_SCHEMES)) { if (!this.allowedSchemes.contains(scheme)) { return false; } } return true; } /** * Returns true if the authority is properly formatted. An authority is the combination * of hostname and port. A null authority value is considered invalid. * @param authority Authority value to validate. * @return true if authority (hostname and port) is valid. */ protected boolean isValidAuthority(String authority) { if (authority == null) { return false; } // check manual authority validation if specified if (authorityValidator != null) { if (authorityValidator.isValid(authority)) { return true; } } Matcher authorityMatcher = AUTHORITY_PATTERN.matcher(authority); if (!authorityMatcher.matches()) { return false; } String hostLocation = authorityMatcher.group(PARSE_AUTHORITY_HOST_IP); // check if authority is hostname or IP address: // try a hostname first since that's much more likely DomainValidator domainValidator = DomainValidator.getInstance(isOn(ALLOW_LOCAL_URLS)); if (!domainValidator.isValid(hostLocation)) { // try an IP address InetAddressValidator inetAddressValidator = InetAddressValidator.getInstance(); if (!inetAddressValidator.isValid(hostLocation)) { // isn't either one, so the URL is invalid return false; } } String port = authorityMatcher.group(PARSE_AUTHORITY_PORT); if (port != null) { if (!PORT_PATTERN.matcher(port).matches()) { return false; } } String extra = authorityMatcher.group(PARSE_AUTHORITY_EXTRA); if (extra != null && extra.trim().length() > 0){ return false; } return true; } /** * Returns true if the path is valid. A null value is considered invalid. * @param path Path value to validate. * @return true if path is valid. */ protected boolean isValidPath(String path) { if (path == null) { return false; } if (!PATH_PATTERN.matcher(path).matches()) { return false; } int slash2Count = countToken("//", path); if (isOff(ALLOW_2_SLASHES) && (slash2Count > 0)) { return false; } int slashCount = countToken("/", path); int dot2Count = countToken("..", path); if (dot2Count > 0) { if ((slashCount - slash2Count - 1) <= dot2Count) { return false; } } return true; } /** * Returns true if the query is null or it's a properly formatted query string. * @param query Query value to validate. * @return true if query is valid. */ protected boolean isValidQuery(String query) { if (query == null) { return true; } return QUERY_PATTERN.matcher(query).matches(); } /** * Returns true if the given fragment is null or fragments are allowed. * @param fragment Fragment value to validate. * @return true if fragment is valid. */ protected boolean isValidFragment(String fragment) { if (fragment == null) { return true; } return isOff(NO_FRAGMENTS); } /** * Returns the number of times the token appears in the target. * @param token Token value to be counted. * @param target Target value to count tokens in. * @return the number of tokens. */ protected int countToken(String token, String target) { int tokenIndex = 0; int count = 0; while (tokenIndex != -1) { tokenIndex = target.indexOf(token, tokenIndex); if (tokenIndex > -1) { tokenIndex++; count++; } } return count; } /** * Tests whether the given flag is on. If the flag is not a power of 2 * (ie. 3) this tests whether the combination of flags is on. * * @param flag Flag value to check. * * @return whether the specified flag value is on. */ private boolean isOn(long flag) { return (this.options & flag) > 0; } /** * Tests whether the given flag is off. If the flag is not a power of 2 * (ie. 3) this tests whether the combination of flags is off. * * @param flag Flag value to check. * * @return whether the specified flag value is off. */ private boolean isOff(long flag) { return (this.options & flag) == 0; } } ././@LongLink100644 0 0 164 11711231552 10252 Lustar 0 0 commons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/routines/checkdigit/ABANumberCheckDigit.javacommons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/routines/checkdigit/ABANumber100644 765 0 6137 11711227701 34542 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines.checkdigit; /** * Modulus 10 ABA Number (or Routing Transit Number (RTN)) Check Digit * calculation/validation. *

    * ABA Numbers (or Routing Transit Numbers) are a nine digit numeric code used * to identify American financial institutions for things such as checks or deposits * (ABA stands for the American Bankers Association). *

    * Check digit calculation is based on modulus 10 with digits being weighted * based on their position (from right to left) as follows: *

      *
    • Digits 1, 4 and & 7 are weighted 1 *
    • Digits 2, 5 and & 8 are weighted 7 *
    • Digits 3, 6 and & 9 are weighted 3 *
    *

    * For further information see * Wikipedia - * Routing transit number. * * @version $Revision: 1227719 $ $Date: 2012-01-05 18:45:51 +0100 (Thu, 05 Jan 2012) $ * @since Validator 1.4 */ public final class ABANumberCheckDigit extends ModulusCheckDigit { private static final long serialVersionUID = -8255937433810380145L; /** Singleton Routing Transit Number Check Digit instance */ public static final CheckDigit ABAN_CHECK_DIGIT = new ABANumberCheckDigit(); /** weighting given to digits depending on their right position */ private static final int[] POSITION_WEIGHT = new int[] {3, 1, 7}; /** * Construct a modulus 10 Check Digit routine for ABA Numbers. */ public ABANumberCheckDigit() { super(10); } /** * Calculates the weighted value of a character in the * code at a specified position. *

    * ABA Routing numbers are weighted in the following manner: *

    
         *     left position: 1  2  3  4  5  6  7  8  9
         *            weight: 3  7  1  3  7  1  3  7  1
         * 
    * * @param charValue The numeric value of the character. * @param leftPos The position of the character in the code, counting from left to right * @param rightPos The positionof the character in the code, counting from right to left * @return The weighted value of the character. */ protected int weightedValue(int charValue, int leftPos, int rightPos) { int weight = POSITION_WEIGHT[rightPos % 3]; return (charValue * weight); } } ././@LongLink100644 0 0 160 11711231552 10246 Lustar 0 0 commons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/routines/checkdigit/CUSIPCheckDigit.javacommons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/routines/checkdigit/CUSIPChec100644 765 0 7436 11711227701 34457 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines.checkdigit; /** * Modulus 10 CUSIP (North American Securities) * Check Digit calculation/validation. *

    * CUSIP Numbers are 9 character alphanumeric codes used * to identify North American Securities. *

    * Check digit calculation uses the Modulus 10 Double Add Double technique * with every second digit being weighted by 2. Alphabetic characters are * converted to numbers by their position in the alphabet starting with A being 10. * Weighted numbers greater than ten are treated as two separate numbers. *

    * *

    * See Wikipedia - CUSIP * for more details. * * @version $Revision: 1227719 $ $Date: 2012-01-05 18:45:51 +0100 (Thu, 05 Jan 2012) $ * @since Validator 1.4 */ public final class CUSIPCheckDigit extends ModulusCheckDigit { private static final long serialVersionUID = 666941918490152456L; /** Singleton CUSIP Check Digit instance */ public static final CheckDigit CUSIP_CHECK_DIGIT = new CUSIPCheckDigit(); /** weighting given to digits depending on their right position */ private static final int[] POSITION_WEIGHT = new int[] {2, 1}; /** * Construct an CUSIP Indetifier Check Digit routine. */ public CUSIPCheckDigit() { super(10); } /** * Convert a character at a specified position to an integer value. * * @param character The character to convert * @param leftPos The position of the character in the code, counting from left to right * @param rightPos The positionof the character in the code, counting from right to left * @return The integer value of the character * @throws CheckDigitException if character is not alphanumeric */ protected int toInt(char character, int leftPos, int rightPos) throws CheckDigitException { int charValue = Character.getNumericValue(character); if (charValue < 0 || charValue > 35) { throw new CheckDigitException("Invalid Character[" + leftPos + "] = '" + charValue + "'"); } return charValue; } /** *

    Calculates the weighted value of a charcter in the * code at a specified position.

    * *

    For Luhn (from right to left) odd digits are weighted * with a factor of one and even digits with a factor * of two. Weighted values > 9, have 9 subtracted

    * * @param charValue The numeric value of the character. * @param leftPos The position of the character in the code, counting from left to right * @param rightPos The positionof the character in the code, counting from right to left * @return The weighted value of the character. */ protected int weightedValue(int charValue, int leftPos, int rightPos) { int weight = POSITION_WEIGHT[rightPos % 2]; int weightedValue = (charValue * weight); return ModulusCheckDigit.sumDigits(weightedValue); } } ././@LongLink100644 0 0 153 11711231552 10250 Lustar 0 0 commons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/routines/checkdigit/CheckDigit.javacommons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/routines/checkdigit/CheckDigi100644 765 0 5344 11711227701 34617 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines.checkdigit; /** * Check Digit calculation and validation. *

    * The logic for validating check digits has previously been * embedded within the logic for specific code validation, which * includes other validations such as verifying the format * or length of a code. {@link CheckDigit} provides for separating out * the check digit calculation logic enabling it to be more easily * tested and reused. *

    * Although Commons Validator is primarily concerned with validation, * {@link CheckDigit} also defines behaviour for calculating/generating check * digits, since it makes sense that users will want to (re-)use the * same logic for both. The {@link org.apache.commons.validator.routines.ISBNValidator} * makes specific use of this feature by providing the facility to validate ISBN-10 codes * and then convert them to the new ISBN-13 standard. *

    * {@link CheckDigit} is used by the new generic * CodeValidator implementation. *

    *

    Implementations

    * See the * Package Summary for a full * list of implementations provided within Commons Validator. * * @see org.apache.commons.validator.routines.CodeValidator * @version $Revision: 589328 $ $Date: 2007-10-28 11:43:47 +0100 (Sun, 28 Oct 2007) $ * @since Validator 1.4 */ public interface CheckDigit { /** * Calculate the Check Digit for a code. * * @param code The code to calculate the Check Digit for. * @return The calculated Check Digit * @throws CheckDigitException if an error occurs. */ public String calculate(String code) throws CheckDigitException; /** * Validate the check digit for the code. * * @param code The code to validate. * @return true if the check digit is valid, otherwise * false. */ public boolean isValid(String code); } ././@LongLink100644 0 0 164 11711231552 10252 Lustar 0 0 commons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/routines/checkdigit/CheckDigitException.javacommons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/routines/checkdigit/CheckDigi100644 765 0 3301 11711227701 34606 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines.checkdigit; /** * Check Digit calculation/validation error. * * @version $Revision: 1227719 $ $Date: 2012-01-05 18:45:51 +0100 (Thu, 05 Jan 2012) $ * @since Validator 1.4 */ public class CheckDigitException extends Exception { private static final long serialVersionUID = -3519894732624685477L; /** * Construct an Exception with no message. */ public CheckDigitException() { } /** * Construct an Exception with a message. * * @param msg The error message. */ public CheckDigitException(String msg) { super(msg); } /** * Construct an Exception with a message and * the underlying cause. * * @param msg The error message. * @param cause The underlying cause of the error */ public CheckDigitException(String msg, Throwable cause) { super(msg, cause); } } ././@LongLink100644 0 0 160 11711231552 10246 Lustar 0 0 commons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/routines/checkdigit/EAN13CheckDigit.javacommons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/routines/checkdigit/EAN13Chec100644 765 0 6032 11711227701 34332 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines.checkdigit; /** * Modulus 10 EAN-13 / UPC / ISBN-13 Check Digit * calculation/validation. *

    * Check digit calculation is based on modulus 10 with digits in * an odd position (from right to left) being weighted 1 and even * position digits being weighted 3. *

    * For further information see: *

    * * @version $Revision: 1227719 $ $Date: 2012-01-05 18:45:51 +0100 (Thu, 05 Jan 2012) $ * @since Validator 1.4 */ public final class EAN13CheckDigit extends ModulusCheckDigit { private static final long serialVersionUID = 1726347093230424107L; /** Singleton EAN-13 Check Digit instance */ public static final CheckDigit EAN13_CHECK_DIGIT = new EAN13CheckDigit(); /** weighting given to digits depending on their right position */ private static final int[] POSITION_WEIGHT = new int[] {3, 1}; /** * Construct a modulus 10 Check Digit routine for EAN/UPC. */ public EAN13CheckDigit() { super(10); } /** *

    Calculates the weighted value of a character in the * code at a specified position.

    * *

    For EAN-13 (from right to left) odd digits are weighted * with a factor of one and even digits with a factor * of three.

    * * @param charValue The numeric value of the character. * @param leftPos The position of the character in the code, counting from left to right * @param rightPos The positionof the character in the code, counting from right to left * @return The weighted value of the character. */ protected int weightedValue(int charValue, int leftPos, int rightPos) { int weight = POSITION_WEIGHT[rightPos % 2]; return (charValue * weight); } } ././@LongLink100644 0 0 157 11711231552 10254 Lustar 0 0 commons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/routines/checkdigit/IBANCheckDigit.javacommons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/routines/checkdigit/IBANCheck100644 765 0 11233 11711227701 34466 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines.checkdigit; import java.io.Serializable; /** * IBAN (International Bank Account Number) Check Digit calculation/validation. *

    * This rountine is based on the ISO 7064 Mod 97,10 check digit caluclation routine. *

    * The two check digit characters in a IBAN number are the third and fourth characters * in the code. For check digit calculation/validation the first four characters are moved * to the end of the code. * So CCDDnnnnnnn becomes nnnnnnnCCDD (where * CC is the country code and DD is the check digit). For * check digit calcualtion the check digit value should be set to zero (i.e. * CC00nnnnnnn in this example. *

    * For further information see * Wikipedia - * IBAN number. * * @version $Revision: 1227719 $ $Date: 2012-01-05 18:45:51 +0100 (Thu, 05 Jan 2012) $ * @since Validator 1.4 */ public final class IBANCheckDigit implements CheckDigit, Serializable { private static final long serialVersionUID = -3600191725934382801L; /** Singleton IBAN Number Check Digit instance */ public static final CheckDigit IBAN_CHECK_DIGIT = new IBANCheckDigit(); private static final long MAX = 999999999; private static final long MODULUS = 97; /** * Construct Check Digit routine for IBAN Numbers. */ public IBANCheckDigit() { } /** * Validate the check digit for an the IBAN code. * * @param code The code to validate * @return true if the check digit is valid, otherwise * false */ public boolean isValid(String code) { if (code == null || code.length() < 5) { return false; } try { int modulusResult = calculateModulus(code); return (modulusResult == 1); } catch (CheckDigitException ex) { return false; } } /** * Calculate the Check Digit for an IBAN code. *

    * Note: The check digit is the third and fourth * characters and and should contain value "00". * * @param code The code to calculate the Check Digit for * @return The calculated Check Digit * @throws CheckDigitException if an error occurs calculating * the check digit for the specified code */ public String calculate(String code) throws CheckDigitException { if (code == null || code.length() < 5) { throw new CheckDigitException("Invalid Code length=" + (code == null ? 0 : code.length())); } int modulusResult = calculateModulus(code); int charValue = (98 - modulusResult); String checkDigit = Integer.toString(charValue); return (charValue > 9 ? checkDigit : "0" + checkDigit); } /** * Calculate the modulus for a code. * * @param code The code to calculate the modulus for. * @return The modulus value * @throws CheckDigitException if an error occurs calculating the modulus * for the specified code */ private int calculateModulus(String code) throws CheckDigitException { String reformattedCode = code.substring(4) + code.substring(0, 4); long total = 0; for (int i = 0; i < reformattedCode.length(); i++) { int charValue = Character.getNumericValue(reformattedCode.charAt(i)); if (charValue < 0 || charValue > 35) { throw new CheckDigitException("Invalid Character[" + i + "] = '" + charValue + "'"); } total = (charValue > 9 ? total * 100 : total * 10) + charValue; if (total > MAX) { total = (total % MODULUS); } } return (int)(total % MODULUS); } } ././@LongLink100644 0 0 161 11711231552 10247 Lustar 0 0 commons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/routines/checkdigit/ISBN10CheckDigit.javacommons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/routines/checkdigit/ISBN10Che100644 765 0 10416 11711227701 34335 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines.checkdigit; /** * Modulus 11 ISBN-10 Check Digit calculation/validation. *

    * ISBN-10 Numbers are a numeric code except for the last (check) digit * which can have a value of "X". *

    * Check digit calculation is based on modulus 11 with digits being weighted * based by their position, from right to left with the first digit being weighted * 1, the second 2 and so on. If the check digit is calculated as "10" it is converted * to "X". *

    * N.B. From 1st January 2007 the book industry will start to use a new 13 digit * ISBN number (rather than this 10 digit ISBN number) which uses the EAN-13 / UPC * (see {@link EAN13CheckDigit}) standard. *

    * For further information see: *

    * * @version $Revision: 1227719 $ $Date: 2012-01-05 18:45:51 +0100 (Thu, 05 Jan 2012) $ * @since Validator 1.4 */ public final class ISBN10CheckDigit extends ModulusCheckDigit { private static final long serialVersionUID = 8000855044504864964L; /** Singleton ISBN-10 Check Digit instance */ public static final CheckDigit ISBN10_CHECK_DIGIT = new ISBN10CheckDigit(); /** * Construct a modulus 11 Check Digit routine for ISBN-10. */ public ISBN10CheckDigit() { super(11); } /** * Calculates the weighted value of a charcter in the * code at a specified position. * *

    For ISBN-10 (from right to left) digits are weighted * by their position.

    * * @param charValue The numeric value of the character. * @param leftPos The position of the character in the code, counting from left to right * @param rightPos The positionof the character in the code, counting from right to left * @return The weighted value of the character. */ protected int weightedValue(int charValue, int leftPos, int rightPos) { return (charValue * rightPos); } /** *

    Convert a character at a specified position to an * integer value.

    * *

    Character 'X' check digit converted to 10.

    * * @param character The character to convert. * @param leftPos The position of the character in the code, counting from left to right * @param rightPos The positionof the character in the code, counting from right to left * @return The integer value of the character. * @throws CheckDigitException if an error occurs. */ protected int toInt(char character, int leftPos, int rightPos) throws CheckDigitException { if (rightPos == 1 && character == 'X') { return 10; } else { return super.toInt(character, leftPos, rightPos); } } /** *

    Convert an integer value to a character at a specified position.

    * *

    Value '10' for position 1 (check digit) converted to 'X'.

    * * @param charValue The integer value of the character. * @return The converted character. * @throws CheckDigitException if an error occurs. */ protected String toCheckDigit(int charValue) throws CheckDigitException { if (charValue == 10) { return "X"; } else { return super.toCheckDigit(charValue); } } } ././@LongLink100644 0 0 157 11711231552 10254 Lustar 0 0 commons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/routines/checkdigit/ISBNCheckDigit.javacommons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/routines/checkdigit/ISBNCheck100644 765 0 10233 11711227701 34507 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines.checkdigit; import java.io.Serializable; /** * Combined ISBN-10 / ISBN-13 Check Digit calculation/validation. *

    * This implementation validates/calculates ISBN check digits * based on the length of the code passed to it - delegating * either to the {@link ISBNCheckDigit#ISBN10_CHECK_DIGIT} or the * {@link ISBNCheckDigit#ISBN13_CHECK_DIGIT} routines to perform the actual * validation/calculation. *

    * N.B. From 1st January 2007 the book industry will start to use a new 13 digit * ISBN number (rather than this 10 digit ISBN number) which uses the EAN-13 / UPC * standard. * * @version $Revision: 1227719 $ $Date: 2012-01-05 18:45:51 +0100 (Thu, 05 Jan 2012) $ * @since Validator 1.4 */ public final class ISBNCheckDigit implements CheckDigit, Serializable { private static final long serialVersionUID = 1391849166205184558L; /** Singleton ISBN-10 Check Digit instance */ public static final CheckDigit ISBN10_CHECK_DIGIT = ISBN10CheckDigit.ISBN10_CHECK_DIGIT; /** Singleton ISBN-13 Check Digit instance */ public static final CheckDigit ISBN13_CHECK_DIGIT = EAN13CheckDigit.EAN13_CHECK_DIGIT; /** Singleton combined ISBN-10 / ISBN-13 Check Digit instance */ public static final CheckDigit ISBN_CHECK_DIGIT = new ISBNCheckDigit(); /** * Calculate an ISBN-10 or ISBN-13 check digit, depending * on the length of the code. *

    * If the length of the code is 9, it is treated as an ISBN-10 * code or if the length of the code is 12, it is treated as an ISBN-13 * code. * * @param code The ISBN code to validate (should have a length of * 9 or 12) * @return The ISBN-10 check digit if the length is 9 or an ISBN-13 * check digit if the length is 12. * @throws CheckDigitException if the code is missing, or an invalid * length (i.e. not 9 or 12) or if there is an error calculating the * check digit. */ public String calculate(String code) throws CheckDigitException { if (code == null || code.length() == 0) { throw new CheckDigitException("ISBN Code is missing"); } else if (code.length() == 9) { return ISBN10_CHECK_DIGIT.calculate(code); } else if (code.length() == 12) { return ISBN13_CHECK_DIGIT.calculate(code); } else { throw new CheckDigitException("Invalid ISBN Length = " + code.length()); } } /** *

    Validate an ISBN-10 or ISBN-13 check digit, depending * on the length of the code.

    *

    * If the length of the code is 10, it is treated as an ISBN-10 * code or ff the length of the code is 13, it is treated as an ISBN-13 * code. * * @param code The ISBN code to validate (should have a length of * 10 or 13) * @return true if the code has a length of 10 and is * a valid ISBN-10 check digit or the code has a length of 13 and is * a valid ISBN-13 check digit - otherwise false. */ public boolean isValid(String code) { if (code == null) { return false; } else if (code.length() == 10) { return ISBN10_CHECK_DIGIT.isValid(code); } else if (code.length() == 13) { return ISBN13_CHECK_DIGIT.isValid(code); } else { return false; } } } ././@LongLink100644 0 0 157 11711231552 10254 Lustar 0 0 commons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/routines/checkdigit/ISINCheckDigit.javacommons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/routines/checkdigit/ISINCheck100644 765 0 7657 11711227701 34516 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines.checkdigit; /** * Modulus 10 ISIN (International Securities Identifying Number) * Check Digit calculation/validation. *

    * ISIN Numbers are 12 character alphanumeric codes used * to identify Securities. *

    * Check digit calculation uses the Modulus 10 Double Add Double technique * with every second digit being weighted by 2. Alphabetic characters are * converted to numbers by their position in the alphabet starting with A being 10. * Weighted numbers greater than ten are treated as two separate numbers. *

    * See Wikipedia - ISIN * for more details. * * @version $Revision: 1227719 $ $Date: 2012-01-05 18:45:51 +0100 (Thu, 05 Jan 2012) $ * @since Validator 1.4 */ public final class ISINCheckDigit extends ModulusCheckDigit { private static final long serialVersionUID = -1239211208101323599L; /** Singleton ISIN Check Digit instance */ public static final CheckDigit ISIN_CHECK_DIGIT = new ISINCheckDigit(); /** weighting given to digits depending on their right position */ private static final int[] POSITION_WEIGHT = new int[] {2, 1}; /** * Construct an ISIN Indetifier Check Digit routine. */ public ISINCheckDigit() { super(10); } /** * Calculate the modulus for an ISIN code. * * @param code The code to calculate the modulus for. * @param includesCheckDigit Whether the code includes the Check Digit or not. * @return The modulus value * @throws CheckDigitException if an error occurs calculating the modulus * for the specified code */ protected int calculateModulus(String code, boolean includesCheckDigit) throws CheckDigitException { StringBuffer transformed = new StringBuffer(code.length() * 2); for (int i = 0; i < code.length(); i++) { int charValue = Character.getNumericValue(code.charAt(i)); if (charValue < 0 || charValue > 35) { throw new CheckDigitException("Invalid Character[" + (i + 1) + "] = '" + charValue + "'"); } transformed.append(charValue); } return super.calculateModulus(transformed.toString(), includesCheckDigit); } /** *

    Calculates the weighted value of a charcter in the * code at a specified position.

    * *

    For Luhn (from right to left) odd digits are weighted * with a factor of one and even digits with a factor * of two. Weighted values > 9, have 9 subtracted

    * * @param charValue The numeric value of the character. * @param leftPos The position of the character in the code, counting from left to right * @param rightPos The positionof the character in the code, counting from right to left * @return The weighted value of the character. */ protected int weightedValue(int charValue, int leftPos, int rightPos) { int weight = POSITION_WEIGHT[rightPos % 2]; int weightedValue = (charValue * weight); return ModulusCheckDigit.sumDigits(weightedValue); } } ././@LongLink100644 0 0 157 11711231552 10254 Lustar 0 0 commons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/routines/checkdigit/LuhnCheckDigit.javacommons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/routines/checkdigit/LuhnCheck100644 765 0 6057 11711227701 34653 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines.checkdigit; /** * Modulus 10 Luhn Check Digit calculation/validation. *

    * Luhn check digits are used, for example, by: *

    * Check digit calculation is based on modulus 10 with digits in * an odd position (from right to left) being weighted 1 and even * position digits being weighted 2 (weighted values greater than 9 have 9 subtracted). *

    * See Wikipedia * for more details. * * @version $Revision: 1227719 $ $Date: 2012-01-05 18:45:51 +0100 (Thu, 05 Jan 2012) $ * @since Validator 1.4 */ public final class LuhnCheckDigit extends ModulusCheckDigit { private static final long serialVersionUID = -2976900113942875999L; /** Singleton Luhn Check Digit instance */ public static final CheckDigit LUHN_CHECK_DIGIT = new LuhnCheckDigit(); /** weighting given to digits depending on their right position */ private static final int[] POSITION_WEIGHT = new int[] {2, 1}; /** * Construct a modulus 10 Luhn Check Digit routine. */ public LuhnCheckDigit() { super(10); } /** *

    Calculates the weighted value of a charcter in the * code at a specified position.

    * *

    For Luhn (from right to left) odd digits are weighted * with a factor of one and even digits with a factor * of two. Weighted values > 9, have 9 subtracted

    * * @param charValue The numeric value of the character. * @param leftPos The position of the character in the code, counting from left to right * @param rightPos The positionof the character in the code, counting from right to left * @return The weighted value of the character. */ protected int weightedValue(int charValue, int leftPos, int rightPos) { int weight = POSITION_WEIGHT[rightPos % 2]; int weightedValue = (charValue * weight); return (weightedValue > 9 ? (weightedValue - 9) : weightedValue); } } ././@LongLink100644 0 0 162 11711231552 10250 Lustar 0 0 commons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/routines/checkdigit/ModulusCheckDigit.javacommons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/routines/checkdigit/ModulusCh100644 765 0 16326 11711227701 34732 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines.checkdigit; import java.io.Serializable; /** * Abstract Modulus Check digit calculation/validation. *

    * Provides a base class for building modulus Check * Digit routines. *

    * This implementation only handles numeric codes, such as * EAN-13. For alphanumeric codes such as EAN-128 you * will need to implement/override the toInt() and * toChar() methods. *

    * * @version $Revision: 1227719 $ $Date: 2012-01-05 18:45:51 +0100 (Thu, 05 Jan 2012) $ * @since Validator 1.4 */ public abstract class ModulusCheckDigit implements CheckDigit, Serializable { private static final long serialVersionUID = 2948962251251528941L; private final int modulus; /** * Construct a {@link CheckDigit} routine for a specified modulus. * * @param modulus The modulus value to use for the check digit calculation */ public ModulusCheckDigit(int modulus) { this.modulus = modulus; } /** * Return the modulus value this check digit routine is based on. * * @return The modulus value this check digit routine is based on */ public int getModulus() { return modulus; } /** * Validate a modulus check digit for a code. * * @param code The code to validate * @return true if the check digit is valid, otherwise * false */ public boolean isValid(String code) { if (code == null || code.length() == 0) { return false; } try { int modulusResult = calculateModulus(code, true); return (modulusResult == 0); } catch (CheckDigitException ex) { return false; } } /** * Calculate a modulus Check Digit for a code. * * @param code The code to calculate the Check Digit for * @return The calculated Check Digit * @throws CheckDigitException if an error occurs calculating * the check digit for the specified code */ public String calculate(String code) throws CheckDigitException { if (code == null || code.length() == 0) { throw new CheckDigitException("Code is missing"); } int modulusResult = calculateModulus(code, false); int charValue = (modulus - modulusResult) % modulus; return toCheckDigit(charValue); } /** * Calculate the modulus for a code. * * @param code The code to calculate the modulus for. * @param includesCheckDigit Whether the code includes the Check Digit or not. * @return The modulus value * @throws CheckDigitException if an error occurs calculating the modulus * for the specified code */ protected int calculateModulus(String code, boolean includesCheckDigit) throws CheckDigitException { int total = 0; for (int i = 0; i < code.length(); i++) { int lth = code.length() + (includesCheckDigit ? 0 : 1); int leftPos = i + 1; int rightPos = lth - i; int charValue = toInt(code.charAt(i), leftPos, rightPos); total += weightedValue(charValue, leftPos, rightPos); } if (total == 0) { throw new CheckDigitException("Invalid code, sum is zero"); } return (total % modulus); } /** * Calculates the weighted value of a character in the * code at a specified position. *

    * Some modulus routines weight the value of a character * depending on its position in the code (e.g. ISBN-10), while * others use different weighting factors for odd/even positions * (e.g. EAN or Luhn). Implement the appropriate mechanism * required by overriding this method. * * @param charValue The numeric value of the character * @param leftPos The position of the character in the code, counting from left to right * @param rightPos The positionof the character in the code, counting from right to left * @return The weighted value of the character * @throws CheckDigitException if an error occurs calculating * the weighted value */ protected abstract int weightedValue(int charValue, int leftPos, int rightPos) throws CheckDigitException; /** * Convert a character at a specified position to an integer value. *

    * Note: this implementation only handlers numeric values * For non-numeric characters, override this method to provide * character-->integer conversion. * * @param character The character to convert * @param leftPos The position of the character in the code, counting from left to right * @param rightPos The positionof the character in the code, counting from right to left * @return The integer value of the character * @throws CheckDigitException if character is non-numeric */ protected int toInt(char character, int leftPos, int rightPos) throws CheckDigitException { if (Character.isDigit(character)) { return Character.getNumericValue(character); } else { throw new CheckDigitException("Invalid Character[" + leftPos + "] = '" + character + "'"); } } /** * Convert an integer value to a check digit. *

    * Note: this implementation only handles numeric values * For non-numeric characters, override this method to provide * integer-->character conversion. * * @param charValue The integer value of the character * @return The converted character * @throws CheckDigitException if integer character value * doesn't represent a numeric character */ protected String toCheckDigit(int charValue) throws CheckDigitException { if (charValue >= 0 && charValue <= 9) { return Integer.toString(charValue); } else { throw new CheckDigitException("Invalid Check Digit Value =" + + charValue); } } /** * Add together the individual digits in a number. * * @param number The number whose digits are to be added * @return The sum of the digits */ public static int sumDigits(int number) { int total = 0; int todo = number; while (todo > 0) { total += todo % 10; todo = todo / 10; } return total; } } ././@LongLink100644 0 0 160 11711231552 10246 Lustar 0 0 commons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/routines/checkdigit/SedolCheckDigit.javacommons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/routines/checkdigit/SedolChec100644 765 0 10137 11711227701 34652 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines.checkdigit; /** * Modulus 10 SEDOL (UK Securities) Check Digit calculation/validation. *

    * SEDOL Numbers are 7 character alphanumeric codes used * to identify UK Securities (SEDOL stands for Stock Exchange Daily Official List). *

    * Check digit calculation is based on modulus 10 with digits being weighted * based on their position, from left to right, as follows: *

    *

    
     *      position:  1  2  3  4  5  6  7
     *     weighting:  1  3  1  7  3  9  1
     * 
    *

    * See Wikipedia - SEDOL * for more details. * * @version $Revision: 1227719 $ $Date: 2012-01-05 18:45:51 +0100 (Thu, 05 Jan 2012) $ * @since Validator 1.4 */ public final class SedolCheckDigit extends ModulusCheckDigit { private static final long serialVersionUID = -8976881621148878443L; /** Singleton SEDOL check digit instance */ public static final CheckDigit SEDOL_CHECK_DIGIT = new SedolCheckDigit(); /** weighting given to digits depending on their right position */ private static final int[] POSITION_WEIGHT = new int[] {1, 3, 1, 7, 3, 9, 1}; /** * Construct a modulus 11 Check Digit routine for ISBN-10. */ public SedolCheckDigit() { super(10); } /** * Calculate the modulus for an SEDOL code. * * @param code The code to calculate the modulus for. * @param includesCheckDigit Whether the code includes the Check Digit or not. * @return The modulus value * @throws CheckDigitException if an error occurs calculating the modulus * for the specified code */ protected int calculateModulus(String code, boolean includesCheckDigit) throws CheckDigitException { if (code.length() > 7) { throw new CheckDigitException("Invalid Code Length = " + code.length()); } return super.calculateModulus(code, includesCheckDigit); } /** * Calculates the weighted value of a charcter in the * code at a specified position. * * @param charValue The numeric value of the character. * @param leftPos The position of the character in the code, counting from left to right * @param rightPos The positionof the character in the code, counting from right to left * @return The weighted value of the character. */ protected int weightedValue(int charValue, int leftPos, int rightPos) { return (charValue * POSITION_WEIGHT[leftPos - 1]); } /** * Convert a character at a specified position to an integer value. * * @param character The character to convert * @param leftPos The position of the character in the code, counting from left to right * @param rightPos The positionof the character in the code, counting from right to left * @return The integer value of the character * @throws CheckDigitException if character is not alphanumeric */ protected int toInt(char character, int leftPos, int rightPos) throws CheckDigitException { int charValue = Character.getNumericValue(character); if (charValue < 0 || charValue > 35) { throw new CheckDigitException("Invalid Character[" + leftPos + "] = '" + charValue + "'"); } return charValue; } } ././@LongLink100644 0 0 163 11711231552 10251 Lustar 0 0 commons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/routines/checkdigit/VerhoeffCheckDigit.javacommons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/routines/checkdigit/VerhoeffC100644 765 0 11505 11711227701 34670 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines.checkdigit; import java.io.Serializable; /** * Verhoeff (Dihedral) Check Digit calculation/validation. *

    * Check digit calculation for numeric codes using a * Dihedral Group * of order 10. *

    * See Wikipedia * - Verhoeff algorithm for more details. * * @version $Revision: 1227719 $ $Date: 2012-01-05 18:45:51 +0100 (Thu, 05 Jan 2012) $ * @since Validator 1.4 */ public final class VerhoeffCheckDigit implements CheckDigit, Serializable { private static final long serialVersionUID = 4138993995483695178L; /** Singleton Verhoeff Check Digit instance */ public static final CheckDigit VERHOEFF_CHECK_DIGIT = new VerhoeffCheckDigit(); /** D - multiplication table */ private static final int[][] D_TABLE = new int[][] { {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 2, 3, 4, 0, 6, 7, 8, 9, 5}, {2, 3, 4, 0, 1, 7, 8, 9, 5, 6}, {3, 4, 0, 1, 2, 8, 9, 5, 6, 7}, {4, 0, 1, 2, 3, 9, 5, 6, 7, 8}, {5, 9, 8, 7, 6, 0, 4, 3, 2, 1}, {6, 5, 9, 8, 7, 1, 0, 4, 3, 2}, {7, 6, 5, 9, 8, 2, 1, 0, 4, 3}, {8, 7, 6, 5, 9, 3, 2, 1, 0, 4}, {9, 8, 7, 6, 5, 4, 3, 2, 1, 0}}; /** P - permutation table */ private static final int[][] P_TABLE = new int[][] { {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 5, 7, 6, 2, 8, 3, 0, 9, 4}, {5, 8, 0, 3, 7, 9, 6, 1, 4, 2}, {8, 9, 1, 6, 0, 4, 3, 5, 2, 7}, {9, 4, 5, 3, 1, 2, 6, 8, 7, 0}, {4, 2, 8, 6, 5, 7, 3, 9, 0, 1}, {2, 7, 9, 3, 8, 0, 6, 4, 1, 5}, {7, 0, 4, 6, 9, 1, 3, 2, 5, 8}}; /** inv: inverse table */ private static final int[] INV_TABLE = new int[] {0, 4, 3, 2, 1, 5, 6, 7, 8, 9}; /** * Validate the Verhoeff Check Digit for a code. * * @param code The code to validate * @return true if the check digit is valid, * otherwise false */ public boolean isValid(String code) { if (code == null || code.length() == 0) { return false; } try { return (calculateChecksum(code, true) == 0); } catch (CheckDigitException e) { return false; } } /** * Calculate a Verhoeff Check Digit for a code. * * @param code The code to calculate the Check Digit for * @return The calculated Check Digit * @throws CheckDigitException if an error occurs calculating * the check digit for the specified code */ public String calculate(String code) throws CheckDigitException { if (code == null || code.length() == 0) { throw new CheckDigitException("Code is missing"); } int checksum = calculateChecksum(code, false); return Integer.toString(INV_TABLE[checksum]); } /** * Calculate the checksum. * * @param code The code to calculate the checksum for. * @param includesCheckDigit Whether the code includes the Check Digit or not. * @return The checksum value * @throws CheckDigitException if the code contains an invalid character (i.e. not numeric) */ private int calculateChecksum(String code, boolean includesCheckDigit) throws CheckDigitException { int checksum = 0; for (int i = 0; i < code.length(); i++) { int idx = code.length() - (i + 1); int num = Character.getNumericValue(code.charAt(idx)); if (num < 0 || num > 9) { throw new CheckDigitException("Invalid Character[" + i + "] = '" + ((int)code.charAt(idx)) + "'"); } int pos = includesCheckDigit ? i : i + 1; checksum = D_TABLE[checksum][P_TABLE[pos % 8][num]]; } return checksum; } } ././@LongLink100644 0 0 150 11711231552 10245 Lustar 0 0 commons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/routines/checkdigit/package.htmlcommons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/routines/checkdigit/package.h100644 765 0 1777 11711227701 34634 0ustarsimonetripodiwheel 0 0 Package Documentation for org.apache.commons.validator.routines.checkdigit Package

    This package contains Check Digit validation/calculation routines.

    commons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/routines/package.html100644 765 0 73517 11711227701 33274 0ustarsimonetripodiwheel 0 0 Package Documentation for org.apache.commons.validator.routines Package

    This package contains independant validation routines.

    Table of Contents

    1. Overview

    Commons Validator serves two purposes:

    • To provide standard, independant validation routines/functions.
    • To provide a mini framework for Validation.

    This package has been created, since version 1.3.0, in an attempt to clearly separate these two concerns and is the location for the standard, independant validation routines/functions in Commons Validator.

    The contents of this package have no dependencies on the framework aspect of Commons Validator and can be used on their own.

    2. Date and Time Validators

    2.1 Overview

    The date and time validators either validate according to a specified format or use a standard format for a specified Locale.

    2.2 Validating a Date Value

    You can either use one of the isValid() methods to just determine if a date is valid, or use one of the validate() methods to validate a date and convert it to a java.util.Date...

          // Get the Date validator
          DateValidator validator = DateValidator.getInstance();
    
          // Validate/Convert the date
          Date fooDate = validator.validate(fooString, "dd/MM/yyyy");
          if (fooDate == null) {
              // error...not a valid date
              return;
          }
    

    The following methods are provided to validate a date/time (return a boolean result):

    • isValid(value)
    • isValid(value, pattern)
    • isValid(value, Locale)
    • isValid(value, pattern, Locale)

    The following methods are provided to validate a date/time and convert it to either a java.util.Date or java.util.Calendar:

    • validate(value)
    • validate(value, pattern)
    • validate(value, Locale)
    • validate(value, pattern, Locale)

    2.3 Formatting

    Formatting and validating are two sides of the same coin. Typically input values which are converted from Strings according to a specified format also have to be rendered for output in the same format. These validators provide the mechanism for formatting from date/time objects to Strings. The following methods are provided to format date/time values as Strings:

    • format(date/calendar)
    • format(date/calendar, pattern)
    • format(date/calendar, Locale)
    • format(date/calendar, pattern, Locale)

    2.4 Time Zones

    If the date being parsed relates to a different time zone than the system default, you can specify the TimeZone to use when validating/converting:

          // Get the GMT time zone
          TimeZone GMT = TimeZone.getInstance("GMT");
    
          // Validate/Convert the date using GMT
          Date fooDate = validator.validate(fooString, "dd/MM/yyyy", GMT);
    

    The followng Time Zone flavours of the Validation/Conversion methods are provided:

    • validate(value, TimeZone)
    • validate(value, pattern, TimeZone)
    • validate(value, Locale, TimeZone)
    • validate(value, pattern, Locale, TimeZone)

    2.5 Comparing Dates and Times

    As well as validating that a value is a valid date or time, these validators also provide date comparison functions. The DateValidator and CalendarValidator provide functions for comparing years, quarters, months, weeks and dates and the TimeValidator provides functions for comparing hours, minutes, seconds and milliseconds. For example, to check that a date is in the current month, you could use the compareMonths() method, which compares the year and month components of a date:

          // Check if the date is in the current month 
          int compare = validator.compareMonths(fooDate, new Date(), null); 
          if (compare == 0) { 
              // do current month processing
              return;
          }
    
          // Check if the date is in the previous quarter
          compare = validator.compareQuarters(fooDate, new Date(), null);
          if (compare < 0) {
              // do previous quarter processing
              return;
          }
    
          // Check if the date is in the next year
          compare = validator.compareYears(fooDate, new Date(), null);
          if (compare > 0) {
              // do next year processing
              return;
          }
    

    3 Numeric Validators

    3.1 Overview

    The numeric validators either validate according to a specified format or use a standard format for a specified Locale or use a custom format for a specified Locale.

    3.2 Validating a Numeric Value

    You can either use one of the isValid() methods to just determine if a number is valid, or use one of the validate() methods to validate a number and convert it to an appropriate type.

    The following example validates an integer against a custom pattern for the German locale. Please note the format is specified using the standard symbols for java.text.DecimalFormat so although the decimal separator is indicated as a period (".") in the format, the validator will check using the German decimal separator - which is a comma (",").

          // Get the Integer validator
          IntegerValidator validator = IntegerValidator.getInstance();
    
          // Validate/Convert the number
          Integer fooInteger = validator.validate(fooString, "#,##0.00", Locale.GERMAN);
          if (fooInteger == null) {
              // error...not a valid Integer
              return;
          }
    

    The following methods are provided to validate a number (return a boolean result):

    • isValid(value)
    • isValid(value, pattern)
    • isValid(value, Locale)
    • isValid(value, pattern, Locale)

    The following methods are provided to validate a number and convert it one of the java.lang.Number implementations:

    • validate(value)
    • validate(value, pattern)
    • validate(value, Locale)
    • validate(value, pattern, Locale)

    3.3 Formatting

    Formatting and validating are two sides of the same coin. Typically input values which are converted from Strings according to a specified format also have to be rendered for output in the same format. These validators provide the mechanism for formatting from numeric objects to Strings. The following methods are provided to format numeric values as Strings:

    • format(number)
    • format(number, pattern)
    • format(number, Locale)
    • format(number, pattern, Locale)

    3.4 Comparing Numbers

    As well as validating that a value is a valid number, these validators also provide functions for validating the minimum, maximum and range of a value.

          // Check the number is between 25 and 75
          if (validator.isInRange(fooInteger, 25, 75) {
              // valid...in the specified range
              return;
          }
    

    3.5 Currency Validation

    A default Currency Validator implementation is provided, although all the numeric validators support currency validation. The default implementation converts currency amounts to a java.math.BigDecimal and additionally it provides lenient currency symbol validation. That is, currency amounts are valid with or without the currency symbol.

          BigDecimalValidator validator = CurrencyValidator.getInstance();
    
          BigDecimal fooAmount = validator.validate("$12,500.00", Locale.US);
          if (fooAmount == null) {
              // error...not a valid currency amount
              return;
          }
    
          // Check the amount is a minimum of $1,000
          if (validator.minValue(fooAmount, 1000) {
              // valid...in the specified range
              return;
          }
    

    If, for example, you want to use the Integer Validator to validate a currency, then you can simply create a new instance with the appropriate format style. Note that the other validators do not support the lenient currency symbol validation.

          IntegerValidator validator = 
              new IntegerValidator(true, IntegerValidator.CURRENCY_FORMAT);
    
          String pattern = "#,###" + '\u00A4' + '\u00A4';  // Use international symbol
    
          Integer fooAmount = validator.validate("10.100EUR", pattern, Locale.GERMAN);
          if (fooAmount == null) {
              // error...not a valid currency amount
              return;
          }
    

    3.6 Percent Validation

    A default Percent Validator implementation is provided, although the Float, Double and BigDecimal validators also support percent validation. The default implementation converts percent amounts to a java.math.BigDecimal and additionally it provides lenient percent symbol validation. That is, percent amounts are valid with or without the percent symbol.

          BigDecimalValidator validator = PercentValidator.getInstance();
    
          BigDecimal fooPercent = validator.validate("20%", Locale.US);
          if (fooPercent == null) {
              // error...not a valid percent
              return;
          }
    
          // Check the percent is between 10% and 90%
          if (validator.isInRange(fooPercent, 0.1, 0.9) {
              // valid...in the specified range
              return;
          }
    

    If, for example, you want to use the Float Validator to validate a percent, then you can simply create a new instance with the appropriate format style. Note that the other validators do not support the lenient percent symbol validation.

          FloatValidator validator = 
              new FloatValidator(true, FloatValidator.PERCENT_FORMAT);
    
          Float fooPercent = validator.validate("20%", "###%");
          if (fooPercent == null) {
              // error...not a valid percent
              return;
          }
    
    

    Note: in theory the other numeric validators besides Float, Double and BigDecimal (i.e. Byte, Short, Integer, Long and BigInteger) also support percent validation. However, since they don't allow fractions they will only work with percentages greater than 100%.

    4. Other Validators

    4.1 Overview

    This section lists other available validators.

    4.2 Regular Expression Validation

    Regular expression validation can be done either by using the static methods provied by RegexValidator or by creating a new instance, which caches and re-uses compiled Patterns.

    • Method Flavours - three flavours of validation metods are provided:
      • isValid() methods return true/false to indicate whether validation was successful.
      • validate() methods return a String value of the matched groups aggregated together or null if invalid.
      • match() methods return a String array of the matched groups or null if invalid.
    • Case Sensitivity - matching can be done in either a case sensitive or case in-sensitive way.
    • Multiple Expressions - instances of the RegexValidator can be created to either match against a single regular expression or set (String array) of regular expressions.

    Below is an example of using one of the static methods to validate, matching in a case insensitive manner and returning a String of the matched groups (which doesn't include the hyphen).

          // set up the parameters
          boolean caseSensitive   = false;
          String regex            = "^([A-Z]*)(?:\\-)([A-Z]*)$";
    
          // validate - result should be a String of value "abcdef"
          String result = RegexValidator.validate("abc-def", regex, caseSensitive);
    
    

    The following static methods are provided for regular expression validation:

    • isValid(value, regex)
    • isValid(value, regex, caseSensitive)
    • validate(value, regex)
    • validate(value, regex, caseSensitive)
    • match(value, regex)
    • match(value, regex, caseSensitive)

    Below is an example of creating an instance of RegexValidator matching in a case insensitive manner against a set of regular expressions:

          // set up the parameters
          boolean caseSensitive = false;
          String regex1   = "^([A-Z]*)(?:\\-)([A-Z]*)*$"
          String regex2   = "^([A-Z]*)$";
          String[] regexs = new String[] {regex1, regex1};
    
          // Create the validator
          RegexValidator validator = new RegexValidator(regexs, caseSensitive);
    
          // Validate true/false
          boolean valid = validator.isValid("abc-def");
    
          // Validate and return a String
          String result = validator.validate("abc-def");
    
          // Validate and return a String[]
          String[] groups = validator.match("abc-def");
    
    

    See the RegexValidator javadoc for a full list of the available constructors.

    4.3 Check Digit validation/calculation

    CheckDigit defines a new type for the calculation and validation of check digits with the following methods:

    • isValid(code) - validates the check digit of a code, returning true or false.
    • calculate(code) - calulates the check digit for a code returning the check digit character.

    The following implementations are provided:

    The following examples show validating the check digit of a code:

    
          // Luhn check digit validation
          boolean valid = LuhnCheckDigit.INSTANCE.isValid(code);
    
          // EAN / UPC / ISBN-13 check digit validation
          boolean valid = EAN13CheckDigit.INSTANCE.isValid(code);
    
          // ISBN-10 check digit validation
          boolean valid = ISBNCheckDigit.ISBN10.isValid(code);
          boolean valid = ISBN10CheckDigit.INSTANCE.isValid(code);
    
          // ISBN-13 check digit validation
          boolean valid = ISBNCheckDigit.ISBN13.isValid(code);
    
          // ISBN-10 or ISBN-13 check digit validation
          boolean valid = ISBNCheckDigit.ISBN.isValid(code);
    
    

    The following examples show calulating the check digit of a code:

    
          // Luhn check digit validation
          char checkdigit = LuhnCheckDigit.INSTANCE.calculate(code);
    
          // EAN / UPC / ISBN-13 check digit validation
          char checkdigit = EAN13CheckDigit.INSTANCE.calculate(code);
    
          // ISBN-10 check digit validation
          char checkdigit = ISBNCheckDigit.ISBN10.isValid(code);
          char checkdigit = ISBN10CheckDigit.INSTANCE.calculate(code);
    
          // ISBN-13 check digit validation
          char checkdigit = ISBNCheckDigit.ISBN13.calculate(code);
    
          // ISBN-10 or ISBN-13 check digit validation
          char checkdigit = ISBNCheckDigit.ISBN.calculate(code);
    
    

    4.4 General Code validation

    CodeValidator provides a generic implementation for validating codes. It performs the following validations on a code:

    • Format - the format of the code is validated using a regular expression (see RegexValidator).
    • Length - the minimum/maximum length of the code is checked - after being parsed by the regular expression - with which format characters can be removed with the use of non-capturing groups.
    • Check Digit - a CheckDigit routine checks that code's check digit is valid.

    For example to create a validator to validate EAN-13 codes (numeric, with a length of 13):

    
          // Create an EAN-13 code validator
          CodeValidator validator = new CodeValidator("^[0-9]*$", 13, EAN13CheckDigit.INSTANCE);
    
          // Validate an EAN-13 code
          if (!validator.isValid(code)) {
              ... // invalid
          }
    
    

    4.5 ISBN validation

    ISBNValidator provides ISBN-10 and ISBN-13 validation and can optionally convert ISBN-10 codes to ISBN-13.

    • ISBN-10 - validates using a CodeValidator with the ISBN10CheckDigit routine.
      • isValidISBN10(value) - returns a boolean
      • validateISBN10(value) - returns a reformatted ISBN-10 code
    • ISBN-13 - validates using a CodeValidator with the EAN13CheckDigit routine.
      • isValidISBN13(value) - returns a boolean
      • validateISBN13(value) - returns a reformatted ISBN-13 code
    • ISBN-10 and ISBN-13 - validates codes are either valid ISBN-10 or valid ISBN-13 - optionally can convert ISBN-10 codes to ISBN-13.
      • isValid(value) - returns a boolean
      • validate(value) - returns a reformatted ISBN code (converts ISBN-10 to ISBN-13 if the convert option is true).

    For example to validate

    
          // Validate an ISBN-10 or ISBN-13 code
          if (!ISBNValidator.getInstance().isValid(code)) {
              ... // invalid
          }
    
          // Validate an ISBN-10 or ISBN-13 code (converting to ISBN-13)
          String code = ISBNValidator.getInstance().validate(code);
    
          // Validate an ISBN-10 or ISBN-13 code (not converting)
          String code = ISBNValidator.getInstance(false).validate(code);
    
    

    4.6 IP Address Validation

    InetAddressValidator provides IPv4 address validation.

    For example:

    
          // Get an InetAddressValidator
          InetAddressValidator validator = InetAddressValidator.getInstance();
    
          // Validate an IPv4 address
          if (!validator.isValid(candidateInetAddress)) {
              ... // invalid
          }
    
    

    4.7 Email Address Validation

    EmailValidator provides email address validation according to RFC 822 standards.

    For example:

          // Get an EmailValidator
          EmailValidator validator = EmailValidator.getInstance();
    
          // Validate an email address
          boolean isAddressValid = validator.isValid("user@apache.org");
    
          // Validate a variable containing an email address
          if (!validator.isValid(addressFromUserForm)) {
              webController.sendRedirect(ERROR_REDIRECT, "Email address isn't valid");
              // etc.
          }
    

    4.8 URL Validation

    UrlValidator provides URL validation by checking the scheme, authority, path, query, and fragment in turn. Clients may specify valid schemes to be used in validating in addition to or instead of the default values (HTTP, HTTPS, FTP). The UrlValidator also supports options that change the parsing rules; for example, the ALLOW_2_SLASHES option instructs the Validator to allow consecutive slash characters in the path component, which is considered an error by default. For more information on the available options, see the UrlValidator documentation.

    For example:

          // Get an UrlValidator
          UrlValidator defaultValidator = new UrlValidator(); // default schemes
          if (defaultValidator.isValid("http://www.apache.org")) {
              ... // valid
          }
          if (!defaultValidator.isValid("http//www.oops.com")) {
              ... // invalid
          }
    
          // Get an UrlValidator with custom schemes
          String[] customSchemes = { "sftp", "scp", "https" };
          UrlValidator customValidator = new UrlValidator(customSchemes);
          if (!customValidator.isValid("http://www.apache.org")) {
              ... // invalid due to insecure protocol
          }
    
          // Get an UrlValidator that allows double slashes in the path
          UrlValidator doubleSlashValidator = new UrlValidator(UrlValidator.ALLOW_2_SLASHES);
          if (doubleSlashValidator.isValid("http://www.apache.org//projects")) {
              ... // valid only in this Validator instance
          }
    

    4.9 Domain Name Validation

    DomainValidator provides validation of Internet domain names as specified by RFC1034/RFC1123 and according to the IANA-recognized list of top-level domains (TLDs). Clients may validate an entire domain name, a TLD of any category, or a TLD within a specific category.

    For example:

          // Get a DomainValidator
          DomainValidator validator = DomainValidator.getInstance();
    
          // Validate a domain name
          if (validator.isValid("www.apache.org")) {
              ... // valid
          }
          if (!validator.isValid("www.apache.wrong")) {
              ... // invalid
          }
    
          // Validate a TLD
          if (validator.isValidTld(".com")) {
              ... // valid
          }
          if (validator.isValidTld("org")) {
              ... // valid, the leading dot is optional
          }
          if (validator.isValidTld(".us")) {
              ... // valid, country code TLDs are also accepted
          }
    
          // Validate TLDs in categories
          if (validator.isValidGenericTld(".name")) {
              ... // valid
          }
          if (!validator.isValidGenericTld(".uk")) {
              ... // invalid, .uk is a country code TLD
          }
          if (!validator.isValidCountryCodeTld(".info")) {
              ... // invalid, .info is a generic TLD
          }
    
    commons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/util/Flags.java100644 765 0 12353 11711227702 32007 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.util; import java.io.Serializable; /** * Represents a collection of 64 boolean (on/off) flags. Individual flags * are represented by powers of 2. For example,
    * Flag 1 = 1
    * Flag 2 = 2
    * Flag 3 = 4
    * Flag 4 = 8

    * or using shift operator to make numbering easier:
    * Flag 1 = 1 << 0
    * Flag 2 = 1 << 1
    * Flag 3 = 1 << 2
    * Flag 4 = 1 << 3
    * *

    * There cannot be a flag with a value of 3 because that represents Flag 1 * and Flag 2 both being on/true. *

    * * @version $Revision: 1227719 $ $Date: 2012-01-05 18:45:51 +0100 (Thu, 05 Jan 2012) $ */ public class Flags implements Serializable, Cloneable { private static final long serialVersionUID = 8481587558770237995L; /** * Represents the current flag state. */ private long flags = 0; /** * Create a new Flags object. */ public Flags() { super(); } /** * Initialize a new Flags object with the given flags. * * @param flags collection of boolean flags to represent. */ public Flags(long flags) { super(); this.flags = flags; } /** * Returns the current flags. * * @return collection of boolean flags represented. */ public long getFlags() { return this.flags; } /** * Tests whether the given flag is on. If the flag is not a power of 2 * (ie. 3) this tests whether the combination of flags is on. * * @param flag Flag value to check. * * @return whether the specified flag value is on. */ public boolean isOn(long flag) { return (this.flags & flag) > 0; } /** * Tests whether the given flag is off. If the flag is not a power of 2 * (ie. 3) this tests whether the combination of flags is off. * * @param flag Flag value to check. * * @return whether the specified flag value is off. */ public boolean isOff(long flag) { return (this.flags & flag) == 0; } /** * Turns on the given flag. If the flag is not a power of 2 (ie. 3) this * turns on multiple flags. * * @param flag Flag value to turn on. */ public void turnOn(long flag) { this.flags |= flag; } /** * Turns off the given flag. If the flag is not a power of 2 (ie. 3) this * turns off multiple flags. * * @param flag Flag value to turn off. */ public void turnOff(long flag) { this.flags &= ~flag; } /** * Turn off all flags. */ public void turnOffAll() { this.flags = 0; } /** * Turn off all flags. This is a synonym for turnOffAll(). * @since Validator 1.1.1 */ public void clear() { this.flags = 0; } /** * Turn on all 64 flags. */ public void turnOnAll() { this.flags = Long.MAX_VALUE; } /** * Clone this Flags object. * * @return a copy of this object. * @see java.lang.Object#clone() */ public Object clone() { try { return super.clone(); } catch(CloneNotSupportedException e) { throw new RuntimeException("Couldn't clone Flags object."); } } /** * Tests if two Flags objects are in the same state. * @param obj object being tested * @see java.lang.Object#equals(java.lang.Object) * * @return whether the objects are equal. */ public boolean equals(Object obj) { if (!(obj instanceof Flags)) { return false; } if (obj == this) { return true; } Flags f = (Flags) obj; return this.flags == f.flags; } /** * The hash code is based on the current state of the flags. * @see java.lang.Object#hashCode() * * @return the hash code for this object. */ public int hashCode() { return (int) this.flags; } /** * Returns a 64 length String with the first flag on the right and the * 64th flag on the left. A 1 indicates the flag is on, a 0 means it's * off. * * @return string representation of this object. */ public String toString() { StringBuffer bin = new StringBuffer(Long.toBinaryString(this.flags)); for (int i = 64 - bin.length(); i > 0; i--) { bin.insert(0, "0"); } return bin.toString(); } } commons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/util/ValidatorUtils.java100644 765 0 14736 11711227702 33730 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.util; import java.lang.reflect.InvocationTargetException; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import org.apache.commons.beanutils.PropertyUtils; import org.apache.commons.collections.FastHashMap; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.commons.validator.Arg; import org.apache.commons.validator.Msg; import org.apache.commons.validator.Var; /** * Basic utility methods. *

    * The use of FastHashMap is deprecated and will be replaced in a future * release. *

    * * @version $Revision: 1227703 $ $Date: 2012-01-05 18:15:19 +0100 (Thu, 05 Jan 2012) $ */ public class ValidatorUtils { /** *

    Replace part of a String with another value.

    * * @param value String to perform the replacement on. * @param key The name of the constant. * @param replaceValue The value of the constant. * * @return The modified value. */ public static String replace(String value, String key, String replaceValue) { if (value == null || key == null || replaceValue == null) { return value; } int pos = value.indexOf(key); if (pos < 0) { return value; } int length = value.length(); int start = pos; int end = pos + key.length(); if (length == key.length()) { value = replaceValue; } else if (end == length) { value = value.substring(0, start) + replaceValue; } else { value = value.substring(0, start) + replaceValue + replace(value.substring(end), key, replaceValue); } return value; } /** * Convenience method for getting a value from a bean property as a * String. If the property is a String[] or * Collection and it is empty, an empty String * "" is returned. Otherwise, property.toString() is returned. This method * may return null if there was an error retrieving the * property. * * @param bean The bean object. * @param property The name of the property to access. * * @return The value of the property. */ public static String getValueAsString(Object bean, String property) { Object value = null; try { value = PropertyUtils.getProperty(bean, property); } catch(IllegalAccessException e) { Log log = LogFactory.getLog(ValidatorUtils.class); log.error(e.getMessage(), e); } catch(InvocationTargetException e) { Log log = LogFactory.getLog(ValidatorUtils.class); log.error(e.getMessage(), e); } catch(NoSuchMethodException e) { Log log = LogFactory.getLog(ValidatorUtils.class); log.error(e.getMessage(), e); } if (value == null) { return null; } if (value instanceof String[]) { return ((String[]) value).length > 0 ? value.toString() : ""; } else if (value instanceof Collection) { return ((Collection) value).isEmpty() ? "" : value.toString(); } else { return value.toString(); } } /** * Makes a deep copy of a FastHashMap if the values * are Msg, Arg, * or Var. Otherwise it is a shallow copy. * * @param map FastHashMap to copy. * @return FastHashMap A copy of the FastHashMap that was * passed in. * @deprecated This method is not part of Validator's public API. Validator * will use it internally until FastHashMap references are removed. Use * copyMap() instead. */ public static FastHashMap copyFastHashMap(FastHashMap map) { FastHashMap results = new FastHashMap(); Iterator i = map.entrySet().iterator(); while (i.hasNext()) { Entry entry = (Entry) i.next(); String key = (String) entry.getKey(); Object value = entry.getValue(); if (value instanceof Msg) { results.put(key, ((Msg) value).clone()); } else if (value instanceof Arg) { results.put(key, ((Arg) value).clone()); } else if (value instanceof Var) { results.put(key, ((Var) value).clone()); } else { results.put(key, value); } } results.setFast(true); return results; } /** * Makes a deep copy of a Map if the values are * Msg, Arg, or Var. Otherwise, * it is a shallow copy. * * @param map The source Map to copy. * * @return A copy of the Map that was passed in. */ public static Map copyMap(Map map) { Map results = new HashMap(); Iterator i = map.entrySet().iterator(); while (i.hasNext()) { Entry entry = (Entry) i.next(); String key = (String) entry.getKey(); Object value = entry.getValue(); if (value instanceof Msg) { results.put(key, ((Msg) value).clone()); } else if (value instanceof Arg) { results.put(key, ((Arg) value).clone()); } else if (value instanceof Var) { results.put(key, ((Var) value).clone()); } else { results.put(key, value); } } return results; } } commons-validator-1.4.0-src/src/main/java/org/apache/commons/validator/util/package.html100644 765 0 1743 11711227702 32352 0ustarsimonetripodiwheel 0 0 Package Documentation for org.apache.commons.validator.util Package

    This package contains utility classes used by Commons Validator.

    commons-validator-1.4.0-src/src/main/resources/org/apache/commons/validator/digester-rules.xml100644 765 0 7221 11711227702 33662 0ustarsimonetripodiwheel 0 0 ././@LongLink100644 0 0 150 11711231552 10245 Lustar 0 0 commons-validator-1.4.0-src/src/main/resources/org/apache/commons/validator/resources/validator_1_0.dtdcommons-validator-1.4.0-src/src/main/resources/org/apache/commons/validator/resources/validator_1_0.100644 765 0 22072 11711227702 34662 0ustarsimonetripodiwheel 0 0 ././@LongLink100644 0 0 152 11711231552 10247 Lustar 0 0 commons-validator-1.4.0-src/src/main/resources/org/apache/commons/validator/resources/validator_1_0_1.dtdcommons-validator-1.4.0-src/src/main/resources/org/apache/commons/validator/resources/validator_1_0_100644 765 0 21756 11711227702 34753 0ustarsimonetripodiwheel 0 0 ././@LongLink100644 0 0 150 11711231552 10245 Lustar 0 0 commons-validator-1.4.0-src/src/main/resources/org/apache/commons/validator/resources/validator_1_1.dtdcommons-validator-1.4.0-src/src/main/resources/org/apache/commons/validator/resources/validator_1_1.100644 765 0 24132 11711227702 34662 0ustarsimonetripodiwheel 0 0 ././@LongLink100644 0 0 152 11711231552 10247 Lustar 0 0 commons-validator-1.4.0-src/src/main/resources/org/apache/commons/validator/resources/validator_1_1_3.dtdcommons-validator-1.4.0-src/src/main/resources/org/apache/commons/validator/resources/validator_1_1_100644 765 0 26342 11711227702 34750 0ustarsimonetripodiwheel 0 0 ././@LongLink100644 0 0 152 11711231552 10247 Lustar 0 0 commons-validator-1.4.0-src/src/main/resources/org/apache/commons/validator/resources/validator_1_2_0.dtdcommons-validator-1.4.0-src/src/main/resources/org/apache/commons/validator/resources/validator_1_2_100644 765 0 22141 11711227702 34742 0ustarsimonetripodiwheel 0 0 ././@LongLink100644 0 0 152 11711231552 10247 Lustar 0 0 commons-validator-1.4.0-src/src/main/resources/org/apache/commons/validator/resources/validator_1_3_0.dtdcommons-validator-1.4.0-src/src/main/resources/org/apache/commons/validator/resources/validator_1_3_100644 765 0 22141 11711227702 34743 0ustarsimonetripodiwheel 0 0 ././@LongLink100644 0 0 152 11711231552 10247 Lustar 0 0 commons-validator-1.4.0-src/src/main/resources/org/apache/commons/validator/resources/validator_1_4_0.dtdcommons-validator-1.4.0-src/src/main/resources/org/apache/commons/validator/resources/validator_1_4_100644 765 0 22514 11711227702 34750 0ustarsimonetripodiwheel 0 0 commons-validator-1.4.0-src/src/site/resources/images/logo.png100644 765 0 31437 11711227702 25513 0ustarsimonetripodiwheel 0 0 ‰PNG  IHDR,d³cš— pHYs  šœtIMEÔ:›ö5XtEXtCommentCreated with The GIMPïd%n IDATxÚí=y\”U×Ï,̰Y *à†Úæ#¨¹å– âZijš†iZú~™¿×257´4µ×• °,÷MY”MQÁa€™f†ef¾?ÎçùN÷4¨^yÎþFæÌ¹çÞ{Î=çž{ν"›ÍÆ €ˆ…!@A @PB@PB”P”P%@%@A @A @PB@PB”Pøk@úçI0u"‘¨±HýIjõ6Q/ñBn šnlw`ÿü@5ÑPÿW€èáJ™’’’.]º”””?÷õõU(}úôñññ¤ÿÖKJ©T:t9éÓ§Opp°B¡ H¤^j*•*...88¸OŸ>L‰‰‰À­¯¯ïøñãâ”r\\\rr²R©„~9F¶Ûøøø 60OÉöéÓgüøñu•J¥ºté"7œJÅi?~<Óh½Ô:D‡èÇÇÇ£ Œ?ž¡\/Yøy~~>R@zï½÷6lØÐð©ÿïÛBTT”¯¯o]ÔÆ—““c4Ífsmm­ÕjµZ­u‘Ú¸q£R>>> ,¸sçŽÉd²X,ީůÆFDDÀ¿þúk“Éd6›-ËÅ‹ƒƒƒùÄ Evv¶Ñhâ@¹.~ì"3 äççoܸÛ2›ÍÈC]dßyçšš:VJ¥rÑ¢EvGƒì`ŽíöšNÓùóç‘úöÒ¥K‹-Bæa`M&Snnî»ï¾kwÊbbbjjjè”Ùå»éëëêÍq\xx8¬¡Ð–c x%LLLÄùX¸pá/¿üRYY©×ë322ÆŒC'#::º²²²¦¦¦.‰‰‹‹CR , ¤V¯^íííM©íß¿¿ªªŠ/ùùùQQQ¨{0 •••ï¼óŽA ¬¨¨0 555¿þú«ƒå€ã8oooD¦l$&&.Z´ˆ/ñƒÁ`0dff¢lÙ…U«Vét:èc<ù0oÞ2Ó§OŸ˜˜˜ªª*ƒÁ ÓéöíÛH Ž;¦‰Y\âââ"""øràÀ½^ÿã?‚Y® öíÛ§×ë«««M&“ÝÙ}}}/\¸P]] S¯ÓéÎ;„tôz½Á`pÜßæ¥„qqq8µÙÙÙƒ¡¼¼¼´´´¸¸X«Õj4šÞ½{әؽ{wyyyee%£¢¢íàÁƒz½ž!¥V«GE©=º¢¢‚R³Z­‹-ŠˆˆˆiúêÕ« p>>>ï¼óÎöíÛ7oÞ<sÅŠZ­6::×à˜˜˜ýû÷ïÝ»wîܹmÛ¶å#WTTTUU¡GDDð•P«ÕîÚµ V…Bñé§ŸYf”8Žûí·ßJKKÇŽ‹ÆÿàÁƒÑÑÑ{öìyå•Wì"ëõúšš¾\ÒU2<<Ü`0TTTÜ»w¯¤¤ö?ÿù³¸Ü¼y“Y\"""ììÎ;wîÜ ¿ŠŒŒÜ¿ttô¼yó˜jÛ¶­Z­¾wïÌ£‡¸hž?¥¨„.ÁZ­¶¤¤¤¬¬Ì`0ðé4;%D ôññ©¬¬,///))Ñh4EEE…÷aÅŠt&Ú´iSXXXZZÊŒ ’‚•µ¬¬L«ÕR:*•jĈ”à¨Q£JJJt:—ÚÚZ³Ù¼nÝ:Š9|øpŽãüýý;VRRR¨V«U*Ubb"Ãä_|Jž‘‘ËAIIIQQ‘R©¼téR›6m(rnn®Z­.//¯®®Æµ ¶¶Öd21xxóÍ7ÓÒÒJKK »lÙ2Š9cÆ èéêÕ«Á À˜ܽ{wË–- ²R©Ôjµz½ž‘Ëüü|ÔÀqãÆUTT@¯™-((ؾ};£3W¯^…Ål€Éd7n3\е+W®hµÚââbFSPP——÷ /PÌ-[¶¨T*˜}jqü …N§‹ŠŠÔjµF£ÑjµZ­öĉ€£T*óóóÕjuYYYUUÕ#l %ŒòØ4¼üòËðùòåËr¹=CŽãÄb±D"‘H$mÛ¶ýòË/©?Ö®]»Î;‹D"±X,‹E"%´bÅ Øh1¤yĈ_ýµÁ`üÌÌÌ:téÒEDú°zõjl:++kÈ!;wîlÓ¦Íf=©­­µX,®®®z½þêÕ«Èä‰'† ¶cÇwwwÀÁÍŒ‹‹‹Ífûõ×_Y¡Pxyy‰ À¦Újµººº>|˜ò°qãÆéÓ§»»»sgµZlmmmÏž=ããã±_iiiYYY_|ñÅäÉ“qYAd??¿ .¨Õj@.**š:u*Ž,ÇqݺuËÏÏÇ€‡L&¯Áf³‰D"X±XܵkWN÷Ûo¿¡×§T*aÕ  ÌÐN †õë׿ýöÛîîî0òÀ¤Õjõóó‹GÌÚÚÚÁƒãÔK$ »iÓ&Ðà  áLJЩT ¶mÛ6###33sþüù R©¿}$#4õŸN˜0>ÌŸ?ßÃ㺺ÇN"‘Èd2¹\.—Ë;vìÈl9ž}öÙªª*4\6›mñâÅøíœ9sª««aç`µZa€šó}`|§?þ¸ªªŠn6ìžjôèÑcÕªUƀݢT*urrbÝ=z¬]»øD©Efè…ã¸üüüššjŠip‹b.\¸0,, ¶[Ø} ëää°xñâþýûWWW>HŽm@@bªÕj`X²àᣎ=ºeË–0M(Ät`årùÊ•+©yâĉ‹/ÂOÌf3þØB§`Tq–H$NNNAAAÔkHOOÇîP †L¦¤¤à·6› ˆ“2™ œsºÆñG¸)!Ý#Fàô3c·ÿ~tè×®]ëááA£[‰‰‰Ô Ú•ø;ê3L'|¨Wc)0ȰSBWâórÈДJ¥|²¸  Ap€Œ›F›ÍF7cǵlÙ}<è>ÝPÁÀJ¥Òæ((55 ”Ý#rþ¨âÀ2#€;Fê20³¹víÚ‰'^¾|W4\¶úöí d›ƒ=;Γ`Ô·Ì^W2ê˹¹¹¹¸¸Èår©TZTTD)ƒ=Á­ŸìÛ·/ÃUZZz¹0ÁÌôào!@rìÄ}é”üÊÔ¶Sw´.pi§<Ô¥±ÈÅä#[ïð R©è·t·æ``¥R)³ãMOOg]»ÂQEë á+ ¬àĈâ\½zuìØ±C‡ÍËË£;môP ›©;šœœLHÃdÖHpS]\\ÜÜÜÜÝÝÝÝÝÁ¡JIIá/“àóà2¢Œ™£á¢¢"³ÙŒ[M»ûu*Óh]í¦h1¢‰À燚M¾ò F’¡Éç¡áÈ|’’’ï¼:¶v‡9ŽW«Õà@R;ow¬ø[“ÿvÖ­[7zôh955µ[·nï¿ÿþ;wøÅfm 1çÝ0º‚ʼnf³Ž–ï«à‚ç`">³`ƒÓ]™£ÔX4³ÞD?»QÙº‚ziÒ¢›”l>¸Ër0¶ð&ä¿eœí†tª®Õ­®Ÿ8p`Μ9üo·mÛ6pàÀM›6á†ßî2ÚŒ”™ƒ«W¯Ò8„«Âì¬À]aˆŸ={–Éšw0gü¯ðèÏ%t õþ¥Þ¯¨‡M vÀ±mÈ¢Ã'ˆ[ï÷p‚^­Zµêûï¿oݺ5ómaaá²eËžyæ™ÜÜ\0é\3(ªh¨«­V«RlâÀc±Šx޽¼¼?ç/V†•cz`©ÙlÓ5:88øÒ¥KK—.å£ <866O8%ü?8sæ Íj¸È‹q—P×¶Á±-êÖ­[SËÊ0Ée8°t×êÀ_¨k`›N! Ƕo½õÖO?ýôÚk¯ñMâ‡~˜““G—à>ªÓíH ™£¤¯¾ú ã Ib€€ _¹qã.8X¿©¬ôèÑãöoÍ l]IEvá/[‰cÏÏÏoùòåçÎ4hÛºu+“BðHê¡#%l×®ýïõë×ÓÓÓa?V¯æÄÇÇO˜0®©ŒJ_¿~I9š0‰Œ 4sUd¼ F£Ñh¬êú!Øž={zzz6µNœ8qÓ¦MxÔAé:uÚ²eËúõë)þ‰'0QñöK)¡B¡`VÙÿùŸÿ)(( YÎuÙÀ &|óÍ7T%üý÷ßQ,rÌ!Ø Aƒhð½9ä4Õ AAAÌ4ÁÈ;Ž]1c;dÈf`›hl“’’%ê—º»»·hÑbܸqÓ§O§‘H0¦I­ž1¬gOÈ­j4šuëÖ)•JÌŸäÏ1h`ppp`` M° b0 ^WLœ¦ƒ¼ñÆPÄ€'é‚‚#Iÿòã?BVƒƒ•J…ŒmÚ´yõÕWi¶€ÝÃ÷F‰'ÅÇÇSg δ@Á$Î;—þ„æ Ö%$²ŠD¢ 0ÉMçΛ4iRRRÕC\¢¢¢¢‚ƒƒóóócbbàä—&8p€’úúë¯‹ŠŠ0ÃÐî:‡§mÛ¶…H¦MÁñ£ ‡0M´„E£ÑuF°¨K´öîÝ;lØ0Lʇ±…dz‘HTPPÐpÆh’#ÇqZ­¶.…T©T|ðä©Ò5L1ÜuÀqÜðáçM›æ8¡ªYì a‰ gêkí‚··÷îÝ»‡Š%LšŒòøñã9‚5 gÏž ýâ‹/0…7...$$dâĉ:}ú´§§'­Ê%ÄŒSå‡$€Jf³ÙdF“@e…¦M›máS† Ù¯¾úŠê6e€œêÍøüZAîþ1 ÷Ç“R˜¦öíÛ?~|ذaصüûßÿNLL„5îÒ¥K‹/n×®]~~¾OttôðáÃA?Ñ!ÄÕM$}öÙg ìSN|2êGõðÈ‘##GŽ„M ­N~ï½÷ ÑÑ£GoÛ¶ “Åíý¿¨ÞÜ ¨x¨®®ÎÎΞ3gÞ ÁÀÌ™3gÍš7Jp,9£é£H­²²rûöíûöíûø±ÙO?ýô…^À‚W(`“Ëå?üðCaaá¡C‡˜›c8ŽóòòêÞ½û¨Q£^|ñÅ.]ºÈåò+W®$%%ÙE† ëÈ‘#ýüüœ {yy <800°S§N;wNKK»|ùò¡C‡„ýL¯^½ Åĉ]]]œœ>œœœÌ—W ;dÈ   ÐÐÐÎ;Ëd2ÈÝ»w:thûöíCCC»téwPgXSSSUUuñâÅU«V¥§§ÛXŸùóçÏ;«™- ¸®®®ÎÎÎiii)))èÚðùÄNiµÚ”””C‡1åTÈç°aÃÂÃûvíêìì,•J'Mš¤R©Z·n][[{ìØ1ØêÒb7Ÿ·ß~{Ö¬Yp\mm­““„mœ±¼°y)!è¡Édª®®®ªªºsçNJJÊ™3gÀÊyyyõìÙsèС¸Váê…¥ÜèÞp÷kRaúáöÊ•+ééé×®]âıcÇ*жmÛBh*(x…ÕhN™2™Ä2?,Ï…U`Þ¼y¡¡¡r¹|Û¶m˜< Z.í*Š… 28WˆŒ±¤¬P(BBBvìØý¢<`zºT*Ý»w¯«««L&{õÕWéÒfyÞ¼yaaa2™ “H€23#rdddhh(:Ð)£Ñ«T*ÓÒÒΜ9ƒ)„ …B¡Pâ,@§À… ]™L¶eË:Vv›Þ»w¯‹‹KzzúçŸN儆dAæÎ ú“œœÜºuë'Ÿ|.•JKKÓjµ×¯_/**‚ªŽÀÀÀ1cÆX,XyÍf3ÇqX=}ôÊšê¿Å ôÏm¨¸£þ` +£¸zQj0Ðô¶,QƒÆëÌ0–U¤˜Z]YY ×TÂî‚]]]   ꦭV«D"qvvd\n©Ý®ªª¢È @8±Z­¸NÁá2H6ð€Õ$f!š€Ìq #YD†áBD¦”‘ ÐC¼)«õiĆƒ“X¼3 |BÓÀ'ž°ÓNA÷aaE &‹år9Œ*T´‰D¢ÚÚZè&q÷³ó1v*‘HP–Õš¦úߢÀÒu(3ÇšwùÄÄ\tA©¶Ð£ÔðWô–^º‡¡·…Ö1ä T~‘Xz‰j5,áÀ†d ŒÈhy`ÂâRìQÝ‹Å4‘Úd\ã,^sÄ©!ePQz>K!àe¬ Â¥swœá%È-Ydø¤MŸ0(  ÒìÁ™•é=GyÀð JZÚûo ô ÕÌ‚gjÛñœo¾¨ë¤5戂_h[ïc6 åôz5j„¹?ƒ”p$«˜_JO‘e2¥Ìàõ0‰«Ÿ©aÿC@Œ‡ŒÒi·ZšOˆ3”™urrbr›˜›˜¥Ô(†OìÃ'j¬nðsª?€#•J‘+fsÏÀ#\\ÿÂàêHÓ\h|™Nj½…˜ÜC:4ŒÎ/uçWÓŸKÔÈл襵hj%òÏXZ>2RF“HÝlz¢E‹Ü)ÏÌÝ*”qÈÌMTLÑ“§é)8°tl áO4“vÃošÙå:UDæ×0Çt4êª oŽJˆÆ@,§#î ê×.5¦îe…±™v‹ètòóB¨ÀQ £øvM4³ƒå#ã9òYWYe•äfÞB±‹Ì?L£Ì0?g »yðÔuÌ'ß}µ;ªŒOd÷ôˆþ—aïÑNŠz˜§ÑèxñEóA+êZ BωÝÊcF:ëE¦Æ–/(|d~Gw¡väççß½{>DDD|òÉ'MÚ´` ø§ÀÝ»wýýýŸzê©ÒÒRZ\ÇqÜ|€éDMTÐÜ»wïÚÚZµZ­×ëéß_zé%hš9Å@°„,ÀYùâÅ‹ñ±^‰D’••õä“ObÎ s5ºç©ÓéBCC±ÐññÇÏÎΆlž&mºy‚˜ùGoÿžþyj£är9ä‘3¯”;vÌÛÛÛÛÛûرcô„ýáš¶Ùlnnn={ö¤fÒÓ±iaíÜÑæ¢‡çΣšPSSÙ9˜qÙEsæÌ),,ä8nöìÙyyyÜߢx¸Ö333ñ¿ýû÷¯©©R2‰D"\»,(aóØ'ˆD&“éÌ™3ø—~ýú™L&Èä)) “ÿçØˆÅPp„‰š§‡åååø¨½T*íÛ·¯ÉdGTP?Ám.ÈqÜùóçu:ü¥}ûö:t YÔTµvîÜ îèçŸ}Âc’á”å„„(òä8. ÀÝÝiºIwƒ¯¾úêäÉ“›úB~Á P¿29rÿ;pà@ŽT00®æ!CîܹuÒPõK!ÿ¹ÏzáĉšnR%<~üxLLLtt4Sèô%üç*!Ü‚š@ë6›:8yúôiºåþXÁÔt…EEEE3f̋ŃfÞÃ|„õPPÂ(¤¦¦â͈=öX@@ÞÏÉs¿ÂîiUäƒÊnJJ ^XØ©S§:˜Ífæé¦Ð£Ñ8qâD­VزeK¸­‹6K(À_ G¥!±X wIÐú`j6ñpAÿÌ3Œ/J ÿ›îŽ “É4yòä .€w×jA‹ö¶PPB޳Wÿæó¤°áÄ)0Bz_†]ËÀä²<è•r»JÈ\/â€ìCô7##ãÍ7ß¼xñ"üwРAXÂk©t¨Âþ?Ü4 Jø0PQQ‘——————››{÷îݼ¼<ø÷È‘#ÁÁÁüÜȬ¬¬9sæ\¼x±uëÖóçÏ_¸pa½¯²åååíÚµëôéÓYYYF£100ð£> ‰D‹åúõëIIIÉÉÉ¿ýöÛ¯¿þúØcq¼h§J¥JKKÃøJhh(ÝZ,µZ]PPPPPO ¸¸ø÷ßwww¯7€i±X>üÝwß%&&ªÕjww÷^½zEFFŽ5J£Ñ¤¦¦¢ìïïÊ`7 ôgú rŸššºmÛ¶à•YO=õÔóÏ?o2™¬V+ŠÔÕ N÷í·ßž}rrr˜·ÃZ¶lÙ£G§Ÿ~šikàÀ(&“iÉ’%ø•¯¯/üÐûÂM&››Þ¾}»ªªJ£Ñ|øá‡t<==ïÝ»WQQQYY W¡Â̵jÕŠ¢=õÔSååå:®¯¥|üøqª%K–”””À%œƒ¡´´ôõ×_÷óóÓét]ºtARkÖ¬Ñëõz½2Ѩp:Ñ>øàƒÛ·ogdddgg–——ã ÒÅÅÅ®®®ˆ¹~ýú²²²ŠŠ ƒÁ8Œæä䀵_¹r%ˆTMM Ü•ªÑhà9¤-Z ÁÏ>ûìÖ­[999EEEF£»ü'û êQ[[{çÎ:›7oÎÊÊÊÌÌÌÉÉ)((¸wï^ee%êÝ»w?þøã°FÃ-¦pßieeåÑ£GÁúøøÜ¾}›Þ‘‹£·?nß¾¶»fͽٳgÓ¯$IEE…N§cdCP‡¼z¸ªªêå—_¦c}æÌµZÍÌú¡C‡\\\G.—jµÚòòrX¡a]\±bÄ'wïÞ ×ëõúŠŠŠ²²²²²2FÓ¥KæU‰ÄÄD­V[\\\^^N[Ôëõr¹ÑΞ=›‘‘‘‘‘qçÎF£Óé@‚Íf³Á`€…£š………†v;ûØc‰Åâ½{÷B"hee¥Á`ÅÐétÌÃR©ôÊ•+7oÞ¼uëVnn®V«5 H³Qú 1c†:„’““oܸqóæÍììl•JUZZŠíêõú±cÇæ„ @ñ€y„ŠŠŠˆˆÀ )//Ç% ïƒ˅úé'ÊÞ¥K— Ôj5¼ÀGá‰'žP«Õ0°t šcÆ v~ÆŒôï.\ ®&àŒ;6%%³™===¯•㸠¬X±Âf³­_¿~òäÉæû€K¦““Ó Aƒ>ùäl«C‡ÞÞÞÌ´ð8rˆÖ¡CŒÔ3'„III555€ùÌ3ÏÄf1‰IDAT<õÔSx£9æXÿQQQ“&MÒét”CêY‰D"ÆCó÷÷wuueÎE éFé/““'O"Z=ÜÜÜèÍîТÍf+))8pàáÇ9Ž øòË/áæuæýP‘H4bÄ vñâÅcÇŽÙÍŸÛíÔ©“§§gMMÍ‘#GÖ­[ÇLÇŽá®tÆ 6–@6G%ĸÅK/½D­ÜÕ«WÑïÇ ³Ùl]»výî»ïÀ:˜ÍfºÙX²d ¼Ç0mÚ´9sæÐo1²/•J½½½KJJ°­0ûO»‡ƒ ²{BJHOó¡Ð©®XµjÕâÅ‹m6Û”)SàĤ:Æüª_¿~xU9‹6nFãÏ?ÿŒhaaa´¿Ø®Éd3fLJJ Çq...ðVjí…D"éÔ©Œ§¯ôÑ{²g6›•Jå{ï½çååuêÔ)šµ„Ì;x%^PÂÐ@œcWWW…B_ݺu‹¾XJ¯úõòòGh̘1¹ïôàÁƒ7nä8®]»vk×®EùfÞ3…W(¡¡¡øÜ¹ÕÖÖÒ‚)ª °ç‹Åô0)Ï@0&&v¿íÛ·ß´iåʺT*U*•Œ2Â-‹<¸aÆÆê¯H$:þ|UUEÃÎâÛ‰äí·ßƲÞÿ}oooÐ Ô||‚žpB‚iii˜ÍG+°D"uGaÅYºt©H$Šõ÷÷ïÙ³',Ðb±xÔ¨Q|C*(a#XB>úÊt^^s×5}ý/''ç¹çžëß¿?Ú„ÌÌLŒþmܸQ&“D¢õ /aCnnnþþþôùTŒû_¼x«é!Q`~ý:†4<<<àµ]æ¦Ýôôô™3gΆ CÔzÉüåË—©÷ؾ}{Æߺuë­·Þj¬þ‡tÅà Ž<pâĉýû÷ŽÏìÙ³ÑRd\,Йç8®¨¨ˆñ–‡¬¬¬ÜÜ\ÀiÑ¢EïÞ½ãââRSS·lÙâçç³ÿöÛo»ººÎŸ?¿cÇŽŽ/¡Î R AÁzõê…7›Í;vd–=±Xœžž~ùò対ú ¥"ï¼ólÉÂÂÂî w?eŒV Ãy46‚uFŒ“ÉO”Ç™ ¡H$úᇨ/J-<Ü¢o6›§OŸ•M#FŒ4hÄ6)‡¨ØV«Õq¾(Çq³gÏnÜþ˜ö—#oo5£Ñ‰8 ,€ôx¬’YG€&}ñ_¶£RFùÃÂÂÊÊÊ6mÚôî»ï¾øâ‹Üý4ÀE‹-X°´ºÙDW 4ßR&˜ìçž{ŽþQ¥R1׿Èÿûßÿ0`ÀÈ‘#q±ÿꫯÐt,[¶Œ¾õ‡ï¡ˆ›L¦+W®Ð3FÄé1ÕôEùIÛßÿ=“Ì 6\»v Dÿ£>B— m Õ‡sçÎAY0:·ÔÍ“H${öìG ±¿·oߦ瘓@;v`­‡‡Gxx8U~Ú..OÙÙÙHó±ÇÃE¨wsüøq:zëÖ­ëÑ£z @_/vqqÁW1›"½¹§­uéÒ…&F1o*À Û?ýôSjj*ÈÍf3™L°„]{¯^½ÀÈ€ÜÐ÷Û`ªNŸ>]]]Ƙ˜×[·na=»D" £™Ùtúóòò0¥ÆÉÉ)$$„ßÒÒRؼq7lØ0___L£ª…ÖƒžO@¢ ÉšL¦Õ«W7z©9’H$Ð ªLÞ„  ݇úÒ|ë„#çìüw2t:$©W?þø/¿üòý÷ßÓŒ?\,˜·ôšâÄf]Ô+‰\\\<==ñ/ÅÅÅÌ#*ÅÅÅ‘‘‘~øa×®]q{ƒ>ÏÌ™31ä`W¾9Ž‹ŽŽÆ&ºwïîááÁ8]0÷4ÐÒ»wï-ZØ=!`Ì`ß¾}1„€˜QQQX 1LäZ<Á£¾h¿~ý¨s+‘H¢££q7kÖ¬Æê/5GþþþîîîL/~ùå.5jìëðu:T ª¨`ÇuëÖœpöìYŒõêÕkûöí|ðA«V­èSPàïÀs·Î÷E”°‘ÁÇÇ?———s|5)22²sçÎK–,¡/fîÛ·ð]\\È'ÉÈÎÎf˜ü¨c]¾(WGù³!d0- ª§§'« ìÒ×Á X¼x1—^z‰áp÷îÝÞ_½^ÿ믿RÍçÇ©©lÓ¦M×®]i0†ÿ Çq©©©t;ÊÏ̦ÊoµZÝÜ܆NfŒµÂ¿ ŠMdw”ã8ÎÛÛS–ËËËéóo±±±çλrå ¼ó ÂtíÚ5Œ:ôëׂ„uåq·|ùrÌN¦¡&%º¤¤£ðŒì2ÛžÒÒRºØã1Jù©S§Š‹‹1ê1 êÂQwïÞœœLe@pQ¯]»vóæMÜÝ9995J©9‚ !ƒÁ¡ŒõéÓ¦€:¢|3øÍ7ßàç-Z@ …9÷§Ñ ìììÇã;ÇüÝ2Ý­4QYcs·„pˆÿµZ½páÂ]»vµk׎ž={ñ¨ƒÄwÌ~üñG*­ZµzöÙgËS ·â AÇŽ鮌JÛ‘#GPÊŸyæ™6mÚ0Ç Øb`` rÈíX©T.^¼xðàÁÔ-tss£MÓþúûû7JsäååõôÓO3ý‹Å4ÄòÜsÏ1ùÌÓÂp|O=ለ|<•?55U£Ñ ÎÔ©Sa© ¤A&»ï+ JØÈ@÷„pí4¼;;wîÜiÓ¦9’>Ó+‹1HÈq:HvµE§Ó½ùæ›tæú÷ïÏI›ï‹Ö•(SW\”Á¤ÕËË‹žhSkkk_{í5???vµ‰ú{êÔ)»¾(u2ËÊʧ]»vu…©gïÞ½è8;;Ïš5‹o„©tss›9s&%û·\m,(¡}%\¿~½Õj]±b}‚æ’^ÈùÄO8ЖY³fyxxtìØ‘IQiÃõÕh4Ò<)»‰2@¶ªªŠš&TBºã¢›¢'Ÿ|’áÅëÃ?¼|ùrtt4mC²Ð´X,¦9–Õß´´4zšòÉRCŒ]¢zb4?ýôSz¢?aBÔ3¢A ü0ï_žkÙ²%~6 p‚|ôèQMtüpîiJ$IÆ{¯–.]záÂ…C‡Á¶Îúôéc×7KHH¨¬¬Ä‚€€«Õ Ô¨ ‹D¢“'ObôßÃã{÷îLÑ­H$‚ð@uu5½.‰¦³}úé§û÷ïoÙ²%^1 ‰2Ð4vª)úK#.R©488˜N Yooo¸Ë,ðõdÓ¦MwïÞ…Ï=zô˜5k³–H$;ËqܤI“øf°I=OÁÚZZj0nܸ±víZ(Z£Gö(å4œ••Eþ±`üý÷ßß¾}û‘#Gà¸OØœaÃÉørtyÆ‚ .¼ñÆT&l6‹Â!¸^¯¿~ý:%Hksrrø÷…=zô7Þ˜?þ¤I“Nœ8ˆ1³Fï/ÇqÔö* ÈöÔétÉÉÉtX‚ƒƒéj‚K!?wìÎ;+W®D×Þ®‚v1“N,Ÿ:u ;ÛµkW(¡9wüp« „@…(*áÒ¥K?ûì3H^Ô_*—°عs'^’ •ï[·nýá‡zõêE]GpºN:5gÎ&øF-Chh¨Õj5™LkÖ¬™0aȰa±X(&ø¢ûöíÛºu+qZ”´oß>&ë×®]áááÆ [»v­Åb¡'„?-‰ÊÊÊPZ·nݸý­®®¦aÏ‘#G‚ËúñÇoß¾êöäÉ“©šñ³7á_³Ù|ª½üÿn4gÀ]‡X,Þºuë7nܸ‘™™ W'UTTÀMš·Z­W®\qpûŸŸß•+W࢚éîîžšš:dÈ ܹsG­VCm¾Éd£€e˖͘1cúôé¹¹¹jµº¬¬Ì`0TWW›L&Z«.—ËOœ8¡P(bccFµZMÍ'N„Ò{NGC8­[·¾zõê”)S ]RR5éÉÉÉÛ_zŠàááqëÖ­èèèvíÚ%$$Zee%Þõ’íëë È6lÈÉÉÁ;>,‹Á`k)‹###5F£Q*•999999J¥î"dêûùùÁÍ=·nÝÊËË+..nŠ’y¡²¾¡ñ1ŽãÖ­[7lØ0z_ ?Ý,ÕæÍ›ùK¦D"™6mÚùóç»téBköÐÑ éÞ½ûܹsqE‡9 x`ÃÓÓó_ÿúƒf³Ù***h0pöìÙï½÷^Ïž=é-Àjúæ›oà^3 ...üñŽ; Ç®ô•Édð­Z­V(2™lÛ¶mPÁ öìÙ3**ªûëææF½Ù#F¬^½z÷îÝ~~~`©âããsöìÙ¾}ûr·dÉ’5kÖdggÆÂÂÂ]»võèÑ#66v̘1ÉÉÉkÖ¬‘H$x i.˜uÍl¼iÊ;s:ÿ7¸cÂ#;555...+W®œ={6,Õ"‘H&“aîquu }ýõ×»ví ±i¸wøüùóëׯo”þr·xñ☘‹ÅÒ¥K—Ñ£G3†ÉÏĬÍf3›ÍF£ñèÑ£ñññiiipÔÞªU«nݺ 80""ÂÛÛ®«A‡Rda@àmS¸¿K_ý5$©Ëd2WWWWWW¹\}”ðïqÈᶸ<Æb±€}@±f6ëV—|ÁO°H©.}€ª ð'­V«D"œ`Fg§ªªª¦¦Šåsã-UàyÂ….€FW}hn@ƒ›Q8^ý+’…Öá~8€¦a7š€W³5z±QÄ¡çup.ÕñPº † ÎÞ4ƒÛ<&Ûr0ŒF#\«­\.wuu…5‚¹×\8'ü«Ã3x¥È.Ûüp-6 Ó£q«ÕêääV´®*8,2²ŒˆÓšz¤Þ4rl ‡4E 9”J¥ðÉn%lŠþ¯Àó¤LÌ‘&hh^Fèåü_NwÓU' Jø0JJô\¾ ¤SŠŠ§LÌ•-t-Ǫ(fU E ѨM@ÕBVA[À¾a2 hh€ ¬ÓøY@ é#›i”þ"à:2hL >Èd2øÞÅFõŠæy2g°ÌôáJ­À‡¿÷ÍA 9\˜Ñ½Á º&ð˜~U8 Õ1h&€Z-‰Pí>ÿ€â âΑ¤Pzùþ*-S+À`Œ¹^‘&ë4bq`úËXBmê0÷5q¤¸ª¢ãÕn—ÃŒ¶¿× {Böœ†&—8~ök™kΨ`,þe–mê)Ѩ ?ÑŒ 0Òø!¿E¦S Y~ E«—Ã&ío]úÃ0@gŠQEÏ„8dA ÿ)zÈýñÑ¥†Ì ÿ‰ F,(e†8C£=&¹.|ŠVoÓÕ_ŠFqêyÚ~©nCf­®FÿÞÇ%l4fd¢.´F|}íÞikÈÓ_Äa£S{¸ç¸?ñ ÷ÏxýWPBø›AȘ@A @PB@PB”Pø›àëÀyª\]IEND®B`‚commons-validator-1.4.0-src/src/site/site.xml100644 765 0 5243 11711227702 22230 0ustarsimonetripodiwheel 0 0 Commons Validator /images/logo.png /index.html commons-validator-1.4.0-src/src/site/xdoc/building.xml100644 765 0 5643 11711227702 24022 0ustarsimonetripodiwheel 0 0 Building Commons Documentation Team

    Commons Validator uses Maven or Ant as a build system.

    To build a jar file, change into Validator's root directory and run maven jar. The result will be in the "target" subdirectory.

    To build the Javadocs, run maven javadoc. The result will be in "target/docs/apidocs".

    To build the full website, run maven site. The result will be in "target/docs".

    Further details can be found in the commons build instructions.

    To build a jar file and the javadocs, change into Validator's root directory and run ant dist. The result will be in the "dist" subdirectory.

    Nightly Builds are built once a day from the current SVN HEAD. These are provided purely for test purposes and are NOT official releases of the Apache Software Foundation - Released versions of Commons Validator are available here.

    commons-validator-1.4.0-src/src/site/xdoc/community.xml100644 765 0 3666 11711227702 24254 0ustarsimonetripodiwheel 0 0 Community

    The Apache Wiki is a Wiki run by Apache for the Apache community. The Validator Wiki home page is here.

    Anyone is welcome to create new content about Validator providing that they observe the usual rules of netiquette.

    Struts Console is a free standalone Java Swing application for managing Struts related configuration files, including Commons Validator config files. Struts Console also plugs into several popular Java IDEs for seamless management of config files from one central development tool.

    commons-validator-1.4.0-src/src/site/xdoc/download_validator.xml100644 765 0 21472 11711227702 26117 0ustarsimonetripodiwheel 0 0 Download Commons Validator Commons Documentation Team

    We recommend you use a mirror to download our release builds, but you must verify the integrity of the downloaded files using signatures downloaded from our main distribution directories. Recent releases (48 hours) may not yet be available from the mirrors.

    You are currently using [preferred]. If you encounter a problem with this mirror, please select another mirror. If all mirrors are failing, there are backup mirrors (at the end of the mirrors list) that should be available.

    [if-any logo][end]

    Other mirrors:

    The KEYS link links to the code signing keys used to sign the product. The PGP link downloads the OpenPGP compatible signature from our main site. The MD5 link downloads the checksum from the main site.

    commons-validator-1.4.0-bin.tar.gz md5 pgp
    commons-validator-1.4.0-bin.zip md5 pgp
    commons-validator-1.4.0-src.tar.gz md5 pgp
    commons-validator-1.4.0-src.zip md5 pgp
    commons-validator-1.3.1.tar.gz md5 pgp
    commons-validator-1.3.1.zip md5 pgp
    commons-validator-1.3.1-src.tar.gz md5 pgp
    commons-validator-1.3.1-src.zip md5 pgp

    Older releases can be obtained from the archives.

    commons-validator-1.4.0-src/src/site/xdoc/index.xml100644 765 0 11633 11711227702 23350 0ustarsimonetripodiwheel 0 0 Commons Validator

    A common issue when receiving data either electronically or from user input is verifying the integrity of the data. This work is repetitive and becomes even more complicated when different sets of validation rules need to be applied to the same set of data based on locale. Error messages may also vary by locale. This package addresses some of these issues to speed development and maintenance of validation rules.

    See the Downloads page for current/previous releases. For details of whats new in each version see the Release Notes. Community Notes on release are maintained on the Apache Commons Wiki.

    Validator provides two distinct sets of functionality:

    1. A configurable (typically XML) validation engine
    2. Reusable "primitive" validation methods

    Your validation methods are plugged into the engine and executed against your data. Often, these methods use resources specific to one application or framework so Commons Validator doesn't directly provide pluggable validator actions. However, it does have a set of common validation methods (email addresses, dates, URLs, etc.) that help in creating pluggable actions.

    In order to use the Validator, the following basic steps are required:

    • Create a new instance of the org.apache.commons.validator.Validator class. Currently Validator instances may be safely reused if the current ValidatorResources are the same, as long as you have completed any previous validation, and you do not try to utilize a particular Validator instance from more than one thread at a time.
    • Add any resources needed to perform the validations, such as the JavaBean to validate.
    • Call the validate method on org.apache.commons.validator.Validator.

    The package JavaDoc has useful information:

    See the subversion repository for the latest source code.

    The commons mailing lists act as the main support forum. The user list is suitable for most library usage queries. The dev list is intended for the development discussion. Please remember that the lists are shared between all commons components, so prefix your email by [validator].

    Issues may be reported via ASF JIRA.

    commons-validator-1.4.0-src/src/site/xdoc/issue-tracking.xml100644 765 0 13303 11711227702 25165 0ustarsimonetripodiwheel 0 0 Commons Validator Issue tracking Commons Documentation Team

    Commons Validator uses ASF JIRA for tracking issues. See the Commons Validator JIRA project page.

    To use JIRA you may need to create an account (if you have previously created/updated Commons issues using Bugzilla an account will have been automatically created and you can use the Forgot Password page to get a new password).

    If you would like to report a bug, or raise an enhancement request with Commons Validator please do the following:

    1. Search existing open bugs. If you find your issue listed then please add a comment with your details.
    2. Search the mailing list archive(s). You may find your issue or idea has already been discussed.
    3. Decide if your issue is a bug or an enhancement.
    4. Submit either a bug report or enhancement request.

    Please also remember these points:

    • the more information you provide, the better we can help you
    • test cases are vital, particularly for any proposed enhancements
    • the developers of Commons Validator are all unpaid volunteers

    For more information on subversion and creating patches see the Apache Contributors Guide.

    You may also find these links useful:

    commons-validator-1.4.0-src/src/site/xdoc/mail-lists.xml100644 765 0 22320 11711227702 24312 0ustarsimonetripodiwheel 0 0 Commons Validator Mailing Lists Commons Documentation Team

    Commons Validator shares mailing lists with all the other Commons Components. To make it easier for people to only read messages related to components they are interested in, the convention in Commons is to prefix the subject line of messages with the component's name, for example:

    • [validator] Problem with the ...

    Questions related to the usage of Commons Validator should be posted to the User List.
    The Developer List is for questions and discussion related to the development of Commons Validator.
    Please do not cross-post; developers are also subscribed to the user list.

    Note: please don't send patches or attachments to any of the mailing lists. Patches are best handled via the Issue Tracking system. Otherwise, please upload the file to a public server and include the URL in the mail.

    Please prefix the subject line of any messages for Commons Validator with [validator] - thanks!

    Name Subscribe Unsubscribe Post Archive Other Archives
    Commons User List

    Questions on using Commons Validator.

    Subscribe Unsubscribe Post mail-archives.apache.org markmail.org
    www.mail-archive.com
    news.gmane.org
    Commons Developer List

    Discussion of development of Commons Validator.

    Subscribe Unsubscribe Post mail-archives.apache.org markmail.org
    www.mail-archive.com
    news.gmane.org
    Commons Issues List

    Only for e-mails automatically generated by the issue tracking system.

    Subscribe Unsubscribe read only mail-archives.apache.org markmail.org
    www.mail-archive.com
    Commons Commits List

    Only for e-mails automatically generated by the source control sytem.

    Subscribe Unsubscribe read only mail-archives.apache.org markmail.org
    www.mail-archive.com

    Other mailing lists which you may find useful include:

    Name Subscribe Unsubscribe Post Archive Other Archives
    Apache Announce List

    General announcements of Apache project releases.

    Subscribe Unsubscribe read only mail-archives.apache.org markmail.org
    old.nabble.com
    www.mail-archive.com
    news.gmane.org
    commons-validator-1.4.0-src/src/site/xdoc/tasks.xml100644 765 0 7414 11711227702 23350 0ustarsimonetripodiwheel 0 0 TODO

    The following is a list of items that need to be completed in Validator. Contributions are welcome!

    • Integrate the creation of javascript javadocs into the maven build. What will need to happen is something similar to the exec task in the ant build.xml. Then to put a Maven template around the javadoc it and the legacy 1.0.2 javadoc will need to be copied to a temporary directory then the html2xdoc task will need to be run against that temporary directory.
    • Change the validation.xml file semantics to match a more general "bean" validation usage. Currently, the <form-validation>, <formset>, <form>, and <field> elements require a form-centric view of validations. Changing these to <bean-validation> or <validator-config>, <beans>, <bean>, and <property> respectively would allow Validator to be used more easily in non-form based environments. See the 2.0 DTD proposal for specifics.
    • The above changes to validation.xml could only apply to Validator's native configuration format. We could add a ValidatorResources constructor that accepts a digester-rules file to allow parsing any XML format into Validator configuration objects. This would allow higher level frameworks like Struts to use configuration semantics specific to their domain.
    • ValidatorException is only thrown to indicate configuration and programmer errors yet is a checked exception. ValidatorException should be converted to a RuntimeException to match its real purpose. Furthermore, the exception handling for pluggable validations (ValidatorActions) is not well defined or documented. RuntimeExceptions thrown from ValidatorActions should be propogated out of the Validator framework as is because they indicate programmer error. Checked exceptions thrown from a ValidatorAction should stop validation and be propogated out of the framework for handling as these indicate an unrecoverable system failure. Validation method implementation becomes easier because they can throw SQLException, IOException, etc. instead of wrapping the exception or defining it as a rule failure. This allows clients to reliably distinguish between a normal validation failure (invalid data) and exceptional conditions.
    commons-validator-1.4.0-src/src/site/xdoc/validator_2_0_0_proposal.dtd100644 765 0 24261 11711227702 27000 0ustarsimonetripodiwheel 0 0 commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/AbstractCommonTest.java100644 765 0 3472 11711227700 33565 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator; import java.io.IOException; import java.io.InputStream; import junit.framework.TestCase; import org.xml.sax.SAXException; /** * Consolidates reading in XML config file into parent class. * * @version $Revision: 658832 $ $Date: 2008-05-21 21:57:21 +0200 (Wed, 21 May 2008) $ */ abstract public class AbstractCommonTest extends TestCase { /** * Resources used for validation tests. */ protected ValidatorResources resources = null; public AbstractCommonTest(String string) { super(string); } /** * Load ValidatorResources from * validator-numeric.xml. */ protected void loadResources(String file) throws IOException, SAXException { // Load resources InputStream in = null; try { in = this.getClass().getResourceAsStream(file); resources = new ValidatorResources(in); } finally { if (in != null) { in.close(); } } } } commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/AbstractNumberTest.java100644 765 0 7063 11711227700 33565 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator; import java.io.IOException; import org.xml.sax.SAXException; /** * Abstracts number unit tests methods. * * @version $Revision: 658832 $ $Date: 2008-05-21 21:57:21 +0200 (Wed, 21 May 2008) $ */ abstract public class AbstractNumberTest extends AbstractCommonTest { /** * The key used to retrieve the set of validation * rules from the xml file. */ protected String FORM_KEY; /** * The key used to retrieve the validator action. */ protected String ACTION; public AbstractNumberTest(String name) { super(name); } /** * Load ValidatorResources from * validator-numeric.xml. */ protected void setUp() throws IOException, SAXException { // Load resources loadResources("TestNumber-config.xml"); } protected void tearDown() { } /** * Tests the number validation. */ public void testNumber() throws ValidatorException { // Create bean to run test on. ValueBean info = new ValueBean(); info.setValue("0"); valueTest(info, true); } /** * Tests the float validation failure. */ public void testNumberFailure() throws ValidatorException { // Create bean to run test on. ValueBean info = new ValueBean(); valueTest(info, false); } /** * Utlity class to run a test on a value. * * @param info Value to run test on. * @param passed Whether or not the test is expected to pass. */ protected void valueTest(Object info, boolean passed) throws ValidatorException { // Construct validator based on the loaded resources // and the form key Validator validator = new Validator(resources, FORM_KEY); // add the name bean to the validator as a resource // for the validations to be performed on. validator.setParameter(Validator.BEAN_PARAM, info); // Get results of the validation. ValidatorResults results = null; // throws ValidatorException, // but we aren't catching for testing // since no validation methods we use // throw this results = validator.validate(); assertNotNull("Results are null.", results); ValidatorResult result = results.getValidatorResult("value"); assertNotNull(ACTION + " value ValidatorResult should not be null.", result); assertTrue(ACTION + " value ValidatorResult should contain the '" + ACTION + "' action.", result.containsAction(ACTION)); assertTrue(ACTION + " value ValidatorResult for the '" + ACTION + "' action should have " + (passed ? "passed" : "failed") + ".", (passed ? result.isValid(ACTION) : !result.isValid(ACTION))); } } commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/ByteTest.java100644 765 0 5567 11711227700 31563 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator; /** * Performs Validation Test for byte validations. * * @version $Revision: 1094804 $ $Date: 2011-04-19 00:48:05 +0200 (Tue, 19 Apr 2011) $ */ public class ByteTest extends AbstractNumberTest { public ByteTest(String name) { super(name); ACTION = "byte"; FORM_KEY = "byteForm"; } /** * Tests the byte validation. */ public void testByte() throws ValidatorException { // Create bean to run test on. ValueBean info = new ValueBean(); info.setValue("0"); valueTest(info, true); } /** * Tests the byte validation. */ public void testByteMin() throws ValidatorException { // Create bean to run test on. ValueBean info = new ValueBean(); info.setValue(new Byte(Byte.MIN_VALUE).toString()); valueTest(info, true); } /** * Tests the byte validation. */ public void testByteMax() throws ValidatorException { // Create bean to run test on. ValueBean info = new ValueBean(); info.setValue(new Byte(Byte.MAX_VALUE).toString()); valueTest(info, true); } /** * Tests the byte validation failure. */ public void testByteFailure() throws ValidatorException { // Create bean to run test on. ValueBean info = new ValueBean(); valueTest(info, false); } /** * Tests the byte validation failure. */ public void testByteBeyondMin() throws ValidatorException { // Create bean to run test on. ValueBean info = new ValueBean(); info.setValue(Byte.MIN_VALUE + "1"); valueTest(info, false); } /** * Tests the byte validation failure. */ public void testByteBeyondMax() throws ValidatorException { // Create bean to run test on. ValueBean info = new ValueBean(); info.setValue(Byte.MAX_VALUE + "1"); valueTest(info, false); } } commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/CreditCardValidatorTest.java100644 765 0 6703 11711227700 34523 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator; import junit.framework.TestCase; /** * Test the CreditCardValidator class. * * @version $Revision: 1094806 $ $Date: 2011-04-19 00:53:09 +0200 (Tue, 19 Apr 2011) $ * @deprecated this test can be removed when the deprecated class is removed */ public class CreditCardValidatorTest extends TestCase { private static final String VALID_VISA = "4417123456789113"; private static final String VALID_SHORT_VISA = "4222222222222"; private static final String VALID_AMEX = "378282246310005"; private static final String VALID_MASTERCARD = "5105105105105100"; private static final String VALID_DISCOVER = "6011000990139424"; private static final String VALID_DINERS = "30569309025904"; /** * Constructor for CreditCardValidatorTest. */ public CreditCardValidatorTest(String name) { super(name); } public void testIsValid() { CreditCardValidator ccv = new CreditCardValidator(); assertFalse(ccv.isValid(null)); assertFalse(ccv.isValid("")); assertFalse(ccv.isValid("123456789012")); // too short assertFalse(ccv.isValid("12345678901234567890")); // too long assertFalse(ccv.isValid("4417123456789112")); assertFalse(ccv.isValid("4417q23456w89113")); assertTrue(ccv.isValid(VALID_VISA)); assertTrue(ccv.isValid(VALID_SHORT_VISA)); assertTrue(ccv.isValid(VALID_AMEX)); assertTrue(ccv.isValid(VALID_MASTERCARD)); assertTrue(ccv.isValid(VALID_DISCOVER)); // disallow Visa so it should fail even with good number ccv = new CreditCardValidator(CreditCardValidator.AMEX); assertFalse(ccv.isValid("4417123456789113")); } public void testAddAllowedCardType() { CreditCardValidator ccv = new CreditCardValidator(CreditCardValidator.NONE); // Turned off all cards so even valid numbers should fail assertFalse(ccv.isValid(VALID_VISA)); assertFalse(ccv.isValid(VALID_AMEX)); assertFalse(ccv.isValid(VALID_MASTERCARD)); assertFalse(ccv.isValid(VALID_DISCOVER)); // test our custom type ccv.addAllowedCardType(new DinersClub()); assertTrue(ccv.isValid(VALID_DINERS)); } /** * Test a custom implementation of CreditCardType. */ private class DinersClub implements CreditCardValidator.CreditCardType { private static final String PREFIX = "300,301,302,303,304,305,"; public boolean matches(String card) { String prefix = card.substring(0, 3) + ","; return ((PREFIX.indexOf(prefix) != -1) && (card.length() == 14)); } } } ././@LongLink100644 0 0 151 11711231552 10246 Lustar 0 0 commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/CustomValidatorResourcesTest.javacommons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/CustomValidatorResourcesTest.100644 765 0 3651 11711227700 35021 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator; import java.io.InputStream; import junit.framework.TestCase; /** * Test custom ValidatorResources. * * @version $Revision: 1094808 $ $Date: 2011-04-19 00:57:51 +0200 (Tue, 19 Apr 2011) $ */ public class CustomValidatorResourcesTest extends TestCase { /** * Construct a test case with the specified name. * @param name Name of the test */ public CustomValidatorResourcesTest(String name) { super(name); } /** * Set up. */ protected void setUp() { } /** * Tear Down */ protected void tearDown() { } /** * Test creating a custom validator resources. */ public void testCustomResources() { // Load resources InputStream in = null; try { in = this.getClass().getResourceAsStream("TestNumber-config.xml"); } catch(Exception e) { fail("Error loading resources: " + e); } finally { try { if (in != null) { in.close(); } } catch(Exception e) { } } } } commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/DateTest.java100644 765 0 7215 11711227700 31525 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator; import java.io.IOException; import java.util.Locale; import org.xml.sax.SAXException; /** * Abstracts date unit tests methods. * * @version $Revision: 1094751 $ $Date: 2011-04-18 23:17:40 +0200 (Mon, 18 Apr 2011) $ */ public class DateTest extends AbstractCommonTest { /** * The key used to retrieve the set of validation * rules from the xml file. */ protected String FORM_KEY = "dateForm"; /** * The key used to retrieve the validator action. */ protected String ACTION = "date"; public DateTest(String name) { super(name); } /** * Load ValidatorResources from * validator-numeric.xml. */ protected void setUp() throws IOException, SAXException { // Load resources loadResources("DateTest-config.xml"); } /** * Tests the date validation. */ public void testValidDate() throws ValidatorException { // Create bean to run test on. ValueBean info = new ValueBean(); info.setValue("12/01/2005"); valueTest(info, true); } /** * Tests the date validation. */ public void testInvalidDate() throws ValidatorException { // Create bean to run test on. ValueBean info = new ValueBean(); info.setValue("12/01as/2005"); valueTest(info, false); } /** * Utlity class to run a test on a value. * * @param info Value to run test on. * @param passed Whether or not the test is expected to pass. */ protected void valueTest(Object info, boolean passed) throws ValidatorException { // Construct validator based on the loaded resources // and the form key Validator validator = new Validator(resources, FORM_KEY); // add the name bean to the validator as a resource // for the validations to be performed on. validator.setParameter(Validator.BEAN_PARAM, info); validator.setParameter(Validator.LOCALE_PARAM, Locale.US); // Get results of the validation. ValidatorResults results = null; // throws ValidatorException, // but we aren't catching for testing // since no validation methods we use // throw this results = validator.validate(); assertNotNull("Results are null.", results); ValidatorResult result = results.getValidatorResult("value"); assertNotNull(ACTION + " value ValidatorResult should not be null.", result); assertTrue(ACTION + " value ValidatorResult should contain the '" + ACTION + "' action.", result.containsAction(ACTION)); assertTrue(ACTION + " value ValidatorResult for the '" + ACTION + "' action should have " + (passed ? "passed" : "failed") + ".", (passed ? result.isValid(ACTION) : !result.isValid(ACTION))); } } commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/DoubleTest.java100644 765 0 4531 11711227700 32060 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator; /** * Performs Validation Test for double validations. * * @version $Revision: 1094751 $ $Date: 2011-04-18 23:17:40 +0200 (Mon, 18 Apr 2011) $ */ public class DoubleTest extends AbstractNumberTest { public DoubleTest(String name) { super(name); ACTION = "double"; FORM_KEY = "doubleForm"; } /** * Tests the double validation. */ public void testDouble() throws ValidatorException { // Create bean to run test on. ValueBean info = new ValueBean(); info.setValue("0"); valueTest(info, true); } /** * Tests the double validation. */ public void testDoubleMin() throws ValidatorException { // Create bean to run test on. ValueBean info = new ValueBean(); info.setValue(new Double(Double.MIN_VALUE).toString()); valueTest(info, true); } /** * Tests the double validation. */ public void testDoubleMax() throws ValidatorException { // Create bean to run test on. ValueBean info = new ValueBean(); info.setValue(new Double(Double.MAX_VALUE).toString()); valueTest(info, true); } /** * Tests the double validation failure. */ public void testDoubleFailure() throws ValidatorException { // Create bean to run test on. ValueBean info = new ValueBean(); valueTest(info, false); } } commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/EmailTest.java100644 765 0 40012 11711227700 31707 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator; import java.io.IOException; import org.xml.sax.SAXException; /** * Performs Validation Test for e-mail validations. * * * @version $Revision: 1128342 $ $Date: 2011-05-27 17:00:45 +0200 (Fri, 27 May 2011) $ * @deprecated to be removed when target class is removed */ public class EmailTest extends AbstractCommonTest { /** * The key used to retrieve the set of validation * rules from the xml file. */ protected static String FORM_KEY = "emailForm"; /** * The key used to retrieve the validator action. */ protected static String ACTION = "email"; public EmailTest(String name) { super(name); } /** * Load ValidatorResources from * validator-regexp.xml. */ protected void setUp() throws IOException, SAXException { loadResources("EmailTest-config.xml"); } /** * Tests the e-mail validation. */ public void testEmail() throws ValidatorException { // Create bean to run test on. ValueBean info = new ValueBean(); info.setValue("jsmith@apache.org"); valueTest(info, true); } /** * Tests the email validation with numeric domains. */ public void testEmailWithNumericAddress() throws ValidatorException { ValueBean info = new ValueBean(); info.setValue("someone@[216.109.118.76]"); valueTest(info, true); info.setValue("someone@yahoo.com"); valueTest(info, true); } /** * Tests the e-mail validation. */ public void testEmailExtension() throws ValidatorException { // Create bean to run test on. ValueBean info = new ValueBean(); info.setValue("jsmith@apache.org"); valueTest(info, true); info.setValue("jsmith@apache.com"); valueTest(info, true); info.setValue("jsmith@apache.net"); valueTest(info, true); info.setValue("jsmith@apache.info"); valueTest(info, true); info.setValue("jsmith@apache."); valueTest(info, false); info.setValue("jsmith@apache.c"); valueTest(info, false); info.setValue("someone@yahoo.museum"); valueTest(info, true); info.setValue("someone@yahoo.mu-seum"); valueTest(info, false); } /** *

    Tests the e-mail validation with a dash in * the address.

    */ public void testEmailWithDash() throws ValidatorException { // Create bean to run test on. ValueBean info = new ValueBean(); info.setValue("andy.noble@data-workshop.com"); valueTest(info, true); info.setValue("andy-noble@data-workshop.-com"); valueTest(info, false); info.setValue("andy-noble@data-workshop.c-om"); valueTest(info,false); info.setValue("andy-noble@data-workshop.co-m"); valueTest(info, false); } /** * Tests the e-mail validation with a dot at the end of * the address. */ public void testEmailWithDotEnd() throws ValidatorException { // Create bean to run test on. ValueBean info = new ValueBean(); info.setValue("andy.noble@data-workshop.com."); valueTest(info, false); } /** * Tests the e-mail validation with an RCS-noncompliant character in * the address. */ public void testEmailWithBogusCharacter() throws ValidatorException { // Create bean to run test on. ValueBean info = new ValueBean(); info.setValue("andy.noble@\u008fdata-workshop.com"); valueTest(info, false); // The ' character is valid in an email username. info.setValue("andy.o'reilly@data-workshop.com"); valueTest(info, true); // But not in the domain name. info.setValue("andy@o'reilly.data-workshop.com"); valueTest(info, false); info.setValue("foo+bar@i.am.not.in.us.example.com"); valueTest(info, true); } /** * Tests the email validation with commas. */ public void testEmailWithCommas() throws ValidatorException { ValueBean info = new ValueBean(); info.setValue("joeblow@apa,che.org"); valueTest(info, false); info.setValue("joeblow@apache.o,rg"); valueTest(info, false); info.setValue("joeblow@apache,org"); valueTest(info, false); } /** * Tests the email validation with spaces. */ public void testEmailWithSpaces() throws ValidatorException { ValueBean info = new ValueBean(); info.setValue("joeblow @apache.org"); valueTest(info, false); info.setValue("joeblow@ apache.org"); valueTest(info, false); info.setValue(" joeblow@apache.org"); valueTest(info, true); info.setValue("joeblow@apache.org "); valueTest(info, true); info.setValue("joe blow@apache.org "); valueTest(info, false); info.setValue("joeblow@apa che.org "); valueTest(info, false); } /** * Tests the email validation with ascii control characters. * (i.e. Ascii chars 0 - 31 and 127) */ public void testEmailWithControlChars() { EmailValidator validator = new EmailValidator(); for (char c = 0; c < 32; c++) { assertFalse("Test control char " + ((int)c), validator.isValid("foo" + c + "bar@domain.com")); } assertFalse("Test control char 127", validator.isValid("foo" + ((char)127) + "bar@domain.com")); } /** * Test that @localhost and @localhost.localdomain * addresses aren't declared valid by default */ public void testEmailLocalhost() throws ValidatorException { ValueBean info = new ValueBean(); info.setValue("joe@localhost"); valueTest(info, false); info.setValue("joe@localhost.localdomain"); valueTest(info, false); } /** * Write this test according to parts of RFC, as opposed to the type of character * that is being tested. * *

    FIXME: This test fails so disable it with a leading _ for 1.1.4 release. * The real solution is to fix the email parsing. * * @throws ValidatorException */ public void _testEmailUserName() throws ValidatorException { ValueBean info = new ValueBean(); info.setValue("joe1blow@apache.org"); valueTest(info, true); info.setValue("joe$blow@apache.org"); valueTest(info, true); info.setValue("joe-@apache.org"); valueTest(info, true); info.setValue("joe_@apache.org"); valueTest(info, true); //UnQuoted Special characters are invalid info.setValue("joe.@apache.org"); valueTest(info, false); info.setValue("joe+@apache.org"); valueTest(info, false); info.setValue("joe!@apache.org"); valueTest(info, false); info.setValue("joe*@apache.org"); valueTest(info, false); info.setValue("joe'@apache.org"); valueTest(info, false); info.setValue("joe(@apache.org"); valueTest(info, false); info.setValue("joe)@apache.org"); valueTest(info, false); info.setValue("joe,@apache.org"); valueTest(info, false); info.setValue("joe%45@apache.org"); valueTest(info, false); info.setValue("joe;@apache.org"); valueTest(info, false); info.setValue("joe?@apache.org"); valueTest(info, false); info.setValue("joe&@apache.org"); valueTest(info, false); info.setValue("joe=@apache.org"); valueTest(info, false); //Quoted Special characters are valid info.setValue("\"joe.\"@apache.org"); valueTest(info, true); info.setValue("\"joe+\"@apache.org"); valueTest(info, true); info.setValue("\"joe!\"@apache.org"); valueTest(info, true); info.setValue("\"joe*\"@apache.org"); valueTest(info, true); info.setValue("\"joe'\"@apache.org"); valueTest(info, true); info.setValue("\"joe(\"@apache.org"); valueTest(info, true); info.setValue("\"joe)\"@apache.org"); valueTest(info, true); info.setValue("\"joe,\"@apache.org"); valueTest(info, true); info.setValue("\"joe%45\"@apache.org"); valueTest(info, true); info.setValue("\"joe;\"@apache.org"); valueTest(info, true); info.setValue("\"joe?\"@apache.org"); valueTest(info, true); info.setValue("\"joe&\"@apache.org"); valueTest(info, true); info.setValue("\"joe=\"@apache.org"); valueTest(info, true); } /** * These test values derive directly from RFC 822 & * Mail::RFC822::Address & RFC::RFC822::Address perl test.pl * For traceability don't combine these test values with other tests. */ ResultPair[] testEmailFromPerl = { new ResultPair("abigail@example.com", true), new ResultPair("abigail@example.com ", true), new ResultPair(" abigail@example.com", true), new ResultPair("abigail @example.com ", true), new ResultPair("*@example.net", true), new ResultPair("\"\\\"\"@foo.bar", true), new ResultPair("fred&barny@example.com", true), new ResultPair("---@example.com", true), new ResultPair("foo-bar@example.net", true), new ResultPair("\"127.0.0.1\"@[127.0.0.1]", true), new ResultPair("Abigail ", true), new ResultPair("Abigail", true), new ResultPair("Abigail<@a,@b,@c:abigail@example.com>", true), new ResultPair("\"This is a phrase\"", true), new ResultPair("\"Abigail \"", true), new ResultPair("\"Joe & J. Harvey\" ", true), new ResultPair("Abigail ", true), new ResultPair("Abigail made this < abigail @ example . com >", true), new ResultPair("Abigail(the bitch)@example.com", true), new ResultPair("Abigail ", true), new ResultPair("Abigail < (one) abigail (two) @(three)example . (bar) com (quz) >", true), new ResultPair("Abigail (foo) (((baz)(nested) (comment)) ! ) < (one) abigail (two) @(three)example . (bar) com (quz) >", true), new ResultPair("Abigail ", true), new ResultPair("Abigail ", true), new ResultPair("(foo) abigail@example.com", true), new ResultPair("abigail@example.com (foo)", true), new ResultPair("\"Abi\\\"gail\" ", true), new ResultPair("abigail@[example.com]", true), new ResultPair("abigail@[exa\\[ple.com]", true), new ResultPair("abigail@[exa\\]ple.com]", true), new ResultPair("\":sysmail\"@ Some-Group. Some-Org", true), new ResultPair("Muhammed.(I am the greatest) Ali @(the)Vegas.WBA", true), new ResultPair("mailbox.sub1.sub2@this-domain", true), new ResultPair("sub-net.mailbox@sub-domain.domain", true), new ResultPair("name:;", true), new ResultPair("':;", true), new ResultPair("name: ;", true), new ResultPair("Alfred Neuman ", true), new ResultPair("Neuman@BBN-TENEXA", true), new ResultPair("\"George, Ted\" ", true), new ResultPair("Wilt . (the Stilt) Chamberlain@NBA.US", true), new ResultPair("Cruisers: Port@Portugal, Jones@SEA;", true), new ResultPair("$@[]", true), new ResultPair("*()@[]", true), new ResultPair("\"quoted ( brackets\" ( a comment )@example.com", true), new ResultPair("\"Joe & J. Harvey\"\\x0D\\x0A ", true), new ResultPair("\"Joe &\\x0D\\x0A J. Harvey\" ", true), new ResultPair("Gourmets: Pompous Person ,\\x0D\\x0A" + " Childs\\@WGBH.Boston, \"Galloping Gourmet\"\\@\\x0D\\x0A" + " ANT.Down-Under (Australian National Television),\\x0D\\x0A" + " Cheapie\\@Discount-Liquors;", true), new ResultPair(" Just a string", false), new ResultPair("string", false), new ResultPair("(comment)", false), new ResultPair("()@example.com", false), new ResultPair("fred(&)barny@example.com", false), new ResultPair("fred\\ barny@example.com", false), new ResultPair("Abigail ", false), new ResultPair("Abigail ", false), new ResultPair("Abigail ", false), new ResultPair("\"Abi\"gail\" ", false), new ResultPair("abigail@[exa]ple.com]", false), new ResultPair("abigail@[exa[ple.com]", false), new ResultPair("abigail@[exaple].com]", false), new ResultPair("abigail@", false), new ResultPair("@example.com", false), new ResultPair("phrase: abigail@example.com abigail@example.com ;", false), new ResultPair("invalid£char@example.com", false) }; /** * Write this test based on perl Mail::RFC822::Address * which takes its example email address directly from RFC822 * * @throws ValidatorException * * FIXME This test fails so disable it with a leading _ for 1.1.4 release. * The real solution is to fix the email parsing. */ public void _testEmailFromPerl() throws ValidatorException { ValueBean info = new ValueBean(); for (int index = 0; index < testEmailFromPerl.length; index++) { info.setValue(testEmailFromPerl[index].item); valueTest(info, testEmailFromPerl[index].valid); } } /** * Utlity class to run a test on a value. * * @param info Value to run test on. * @param passed Whether or not the test is expected to pass. */ private void valueTest(ValueBean info, boolean passed) throws ValidatorException { // Construct validator based on the loaded resources // and the form key Validator validator = new Validator(resources, FORM_KEY); // add the name bean to the validator as a resource // for the validations to be performed on. validator.setParameter(Validator.BEAN_PARAM, info); // Get results of the validation. ValidatorResults results = null; // throws ValidatorException, // but we aren't catching for testing // since no validation methods we use // throw this results = validator.validate(); assertNotNull("Results are null.", results); ValidatorResult result = results.getValidatorResult("value"); assertNotNull(ACTION + " value ValidatorResult should not be null.", result); assertTrue("Value "+info.getValue()+" ValidatorResult should contain the '" + ACTION +"' action.", result.containsAction(ACTION)); assertTrue("Value "+info.getValue()+"ValidatorResult for the '" + ACTION +"' action should have " + (passed ? "passed" : "failed") + ".", (passed ? result.isValid(ACTION) : !result.isValid(ACTION))); } } commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/EntityImportTest.java100644 765 0 3663 11711227700 33322 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator; import java.net.URL; import java.util.Locale; /** * Tests entity imports. * * @version $Revision: 1094751 $ $Date: 2011-04-18 23:17:40 +0200 (Mon, 18 Apr 2011) $ */ public class EntityImportTest extends AbstractCommonTest { public EntityImportTest(String name) { super(name); } /** * Tests the entity import loading the byteForm form. */ public void testEntityImport() throws Exception { URL url = getClass().getResource("EntityImportTest-config.xml"); ValidatorResources resources = new ValidatorResources(url.toExternalForm()); assertNotNull("Form should be found", resources.getForm(Locale.getDefault(), "byteForm")); } /** * Tests loading ValidatorResources from a URL */ public void testParseURL() throws Exception { URL url = getClass().getResource("EntityImportTest-config.xml"); ValidatorResources resources = new ValidatorResources(url); assertNotNull("Form should be found", resources.getForm(Locale.getDefault(), "byteForm")); } } commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/ExceptionTest.java100644 765 0 12535 11711227700 32627 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator; import java.io.IOException; import org.xml.sax.SAXException; /** * Performs Validation Test for exception handling. * * @version $Revision: 493905 $ $Date: 2007-01-08 03:11:38 +0100 (Mon, 08 Jan 2007) $ */ public class ExceptionTest extends AbstractCommonTest { /** * The key used to retrieve the set of validation * rules from the xml file. */ protected static String FORM_KEY = "exceptionForm"; /** * The key used to retrieve the validator action. */ protected static String ACTION = "raiseException"; public ExceptionTest(String name) { super(name); } /** * Load ValidatorResources from * validator-exception.xml. */ protected void setUp() throws IOException, SAXException { loadResources("ExceptionTest-config.xml"); } /** * Tests handling of checked exceptions - should become * ValidatorExceptions. */ public void testValidatorException() { // Create bean to run test on. ValueBean info = new ValueBean(); info.setValue("VALIDATOR"); // Construct validator based on the loaded resources // and the form key Validator validator = new Validator(resources, FORM_KEY); // add the name bean to the validator as a resource // for the validations to be performed on. validator.setParameter(Validator.BEAN_PARAM, info); // Get results of the validation which can throw ValidatorException try { validator.validate(); fail("ValidatorException should occur here!"); } catch (ValidatorException expected) { assertTrue("VALIDATOR-EXCEPTION".equals(expected.getMessage())); } } /** * Tests handling of runtime exceptions. * * N.B. This test has been removed (renamed) as it currently * serves no purpose. If/When exception handling * is changed in Validator 2.0 it can be reconsidered * then. */ public void XtestRuntimeException() throws ValidatorException { // Create bean to run test on. ValueBean info = new ValueBean(); info.setValue("RUNTIME"); // Construct validator based on the loaded resources // and the form key Validator validator = new Validator(resources, FORM_KEY); // add the name bean to the validator as a resource // for the validations to be performed on. validator.setParameter(Validator.BEAN_PARAM, info); // Get results of the validation which can throw ValidatorException try { validator.validate(); //fail("RuntimeException should occur here!"); } catch (RuntimeException expected) { fail("RuntimeExceptions should be treated as validation failures in Validator 1.x."); // This will be true in Validator 2.0 //assertTrue("RUNTIME-EXCEPTION".equals(expected.getMessage())); } } /** * Tests handling of checked exceptions - should become * ValidatorExceptions. * * N.B. This test has been removed (renamed) as it currently * serves no purpose. If/When exception handling * is changed in Validator 2.0 it can be reconsidered * then. */ public void XtestCheckedException() { // Create bean to run test on. ValueBean info = new ValueBean(); info.setValue("CHECKED"); // Construct validator based on the loaded resources // and the form key Validator validator = new Validator(resources, FORM_KEY); // add the name bean to the validator as a resource // for the validations to be performed on. validator.setParameter(Validator.BEAN_PARAM, info); // Get results of the validation which can throw ValidatorException // Tests Validator 1.x exception handling try { validator.validate(); } catch (ValidatorException expected) { fail("Checked exceptions are not wrapped in ValidatorException in Validator 1.x."); } catch (Exception e) { assertTrue("CHECKED-EXCEPTION".equals(e.getMessage())); } // This will be true in Validator 2.0 // try { // validator.validate(); // fail("ValidatorException should occur here!"); // } catch (ValidatorException expected) { // assertTrue("CHECKED-EXCEPTION".equals(expected.getMessage())); // } } } commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/ExtensionTest.java100644 765 0 36247 11711227700 32653 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator; import java.io.InputStream; import junit.framework.TestCase; /** *

    Performs tests for extension in form definitions. Performs the same tests * RequiredNameTest does but with an equivalent validation definition with extension * definitions (validator-extension.xml), plus an extra check on overriding rules and * another one checking it mantains correct order when extending.

    * * @version $Revision: 1094751 $ $Date: 2011-04-18 23:17:40 +0200 (Mon, 18 Apr 2011) $ */ public class ExtensionTest extends TestCase { /** * The key used to retrieve the set of validation * rules from the xml file. */ protected static String FORM_KEY = "nameForm"; /** * The key used to retrieve the set of validation * rules from the xml file. */ protected static String FORM_KEY2 = "nameForm2"; /** * The key used to retrieve the set of validation * rules from the xml file. */ protected static String CHECK_MSG_KEY = "nameForm.lastname.displayname"; /** * The key used to retrieve the validator action. */ protected static String ACTION = "required"; /** * Resources used for validation tests. */ private ValidatorResources resources = null; /** * Constructor de ExtensionTest. * @param arg0 */ public ExtensionTest(String arg0) { super(arg0); } /** * Load ValidatorResources from * validator-extension.xml. */ protected void setUp() throws Exception { // Load resources InputStream in = null; try { in = this.getClass().getResourceAsStream("ExtensionTest-config.xml"); resources = new ValidatorResources(in); } finally { if (in != null) { in.close(); } } } protected void tearDown() { } /** * Tests the required validation failure. */ public void testRequired() throws ValidatorException { // Create bean to run test on. NameBean name = new NameBean(); // Construct validator based on the loaded resources // and the form key Validator validator = new Validator(resources, FORM_KEY); // add the name bean to the validator as a resource // for the validations to be performed on. validator.setParameter(Validator.BEAN_PARAM, name); // Get results of the validation. ValidatorResults results = null; // throws ValidatorException, // but we aren't catching for testing // since no validation methods we use // throw this results = validator.validate(); assertNotNull("Results are null.", results); ValidatorResult firstNameResult = results.getValidatorResult("firstName"); ValidatorResult lastNameResult = results.getValidatorResult("lastName"); assertNotNull("First Name ValidatorResult should not be null.", firstNameResult); assertTrue("First Name ValidatorResult should contain the '" + ACTION +"' action.", firstNameResult.containsAction(ACTION)); assertTrue("First Name ValidatorResult for the '" + ACTION +"' action should have failed.", !firstNameResult.isValid(ACTION)); assertNotNull("First Name ValidatorResult should not be null.", lastNameResult); assertTrue("Last Name ValidatorResult should contain the '" + ACTION +"' action.", lastNameResult.containsAction(ACTION)); assertTrue("Last Name ValidatorResult for the '" + ACTION +"' action should have failed.", !lastNameResult.isValid(ACTION)); } /** * Tests the required validation for first name if it is blank. */ public void testRequiredFirstNameBlank() throws ValidatorException { // Create bean to run test on. NameBean name = new NameBean(); name.setFirstName(""); // Construct validator based on the loaded resources // and the form key Validator validator = new Validator(resources, FORM_KEY); // add the name bean to the validator as a resource // for the validations to be performed on. validator.setParameter(Validator.BEAN_PARAM, name); // Get results of the validation. ValidatorResults results = null; results = validator.validate(); assertNotNull("Results are null.", results); ValidatorResult firstNameResult = results.getValidatorResult("firstName"); ValidatorResult lastNameResult = results.getValidatorResult("lastName"); assertNotNull("First Name ValidatorResult should not be null.", firstNameResult); assertTrue("First Name ValidatorResult should contain the '" + ACTION +"' action.", firstNameResult.containsAction(ACTION)); assertTrue("First Name ValidatorResult for the '" + ACTION +"' action should have failed.", !firstNameResult.isValid(ACTION)); assertNotNull("First Name ValidatorResult should not be null.", lastNameResult); assertTrue("Last Name ValidatorResult should contain the '" + ACTION +"' action.", lastNameResult.containsAction(ACTION)); assertTrue("Last Name ValidatorResult for the '" + ACTION +"' action should have failed.", !lastNameResult.isValid(ACTION)); } /** * Tests the required validation for first name. */ public void testRequiredFirstName() throws ValidatorException { // Create bean to run test on. NameBean name = new NameBean(); name.setFirstName("Joe"); // Construct validator based on the loaded resources // and the form key Validator validator = new Validator(resources, FORM_KEY); // add the name bean to the validator as a resource // for the validations to be performed on. validator.setParameter(Validator.BEAN_PARAM, name); // Get results of the validation. ValidatorResults results = null; results = validator.validate(); assertNotNull("Results are null.", results); ValidatorResult firstNameResult = results.getValidatorResult("firstName"); ValidatorResult lastNameResult = results.getValidatorResult("lastName"); assertNotNull("First Name ValidatorResult should not be null.", firstNameResult); assertTrue("First Name ValidatorResult should contain the '" + ACTION +"' action.", firstNameResult.containsAction(ACTION)); assertTrue("First Name ValidatorResult for the '" + ACTION +"' action should have passed.", firstNameResult.isValid(ACTION)); assertNotNull("First Name ValidatorResult should not be null.", lastNameResult); assertTrue("Last Name ValidatorResult should contain the '" + ACTION +"' action.", lastNameResult.containsAction(ACTION)); assertTrue("Last Name ValidatorResult for the '" + ACTION +"' action should have failed.", !lastNameResult.isValid(ACTION)); } /** * Tests the required validation for last name if it is blank. */ public void testRequiredLastNameBlank() throws ValidatorException { // Create bean to run test on. NameBean name = new NameBean(); name.setLastName(""); // Construct validator based on the loaded resources // and the form key Validator validator = new Validator(resources, FORM_KEY); // add the name bean to the validator as a resource // for the validations to be performed on. validator.setParameter(Validator.BEAN_PARAM, name); // Get results of the validation. ValidatorResults results = null; results = validator.validate(); assertNotNull("Results are null.", results); ValidatorResult firstNameResult = results.getValidatorResult("firstName"); ValidatorResult lastNameResult = results.getValidatorResult("lastName"); assertNotNull("First Name ValidatorResult should not be null.", firstNameResult); assertTrue("First Name ValidatorResult should contain the '" + ACTION +"' action.", firstNameResult.containsAction(ACTION)); assertTrue("First Name ValidatorResult for the '" + ACTION +"' action should have failed.", !firstNameResult.isValid(ACTION)); assertNotNull("First Name ValidatorResult should not be null.", lastNameResult); assertTrue("Last Name ValidatorResult should contain the '" + ACTION +"' action.", lastNameResult.containsAction(ACTION)); assertTrue("Last Name ValidatorResult for the '" + ACTION +"' action should have failed.", !lastNameResult.isValid(ACTION)); } /** * Tests the required validation for last name. */ public void testRequiredLastName() throws ValidatorException { // Create bean to run test on. NameBean name = new NameBean(); name.setLastName("Smith"); // Construct validator based on the loaded resources // and the form key Validator validator = new Validator(resources, FORM_KEY); // add the name bean to the validator as a resource // for the validations to be performed on. validator.setParameter(Validator.BEAN_PARAM, name); // Get results of the validation. ValidatorResults results = null; results = validator.validate(); assertNotNull("Results are null.", results); ValidatorResult firstNameResult = results.getValidatorResult("firstName"); ValidatorResult lastNameResult = results.getValidatorResult("lastName"); assertNotNull("First Name ValidatorResult should not be null.", firstNameResult); assertTrue("First Name ValidatorResult should contain the '" + ACTION +"' action.", firstNameResult.containsAction(ACTION)); assertTrue("First Name ValidatorResult for the '" + ACTION +"' action should have failed.", !firstNameResult.isValid(ACTION)); assertNotNull("First Name ValidatorResult should not be null.", lastNameResult); assertTrue("Last Name ValidatorResult should contain the '" + ACTION +"' action.", lastNameResult.containsAction(ACTION)); assertTrue("Last Name ValidatorResult for the '" + ACTION +"' action should have passed.", lastNameResult.isValid(ACTION)); } /** * Tests the required validation for first and last name. */ public void testRequiredName() throws ValidatorException { // Create bean to run test on. NameBean name = new NameBean(); name.setFirstName("Joe"); name.setLastName("Smith"); // Construct validator based on the loaded resources // and the form key Validator validator = new Validator(resources, FORM_KEY); // add the name bean to the validator as a resource // for the validations to be performed on. validator.setParameter(Validator.BEAN_PARAM, name); // Get results of the validation. ValidatorResults results = null; results = validator.validate(); assertNotNull("Results are null.", results); ValidatorResult firstNameResult = results.getValidatorResult("firstName"); ValidatorResult lastNameResult = results.getValidatorResult("lastName"); assertNotNull("First Name ValidatorResult should not be null.", firstNameResult); assertTrue("First Name ValidatorResult should contain the '" + ACTION +"' action.", firstNameResult.containsAction(ACTION)); assertTrue("First Name ValidatorResult for the '" + ACTION +"' action should have passed.", firstNameResult.isValid(ACTION)); assertNotNull("Last Name ValidatorResult should not be null.", lastNameResult); assertTrue("Last Name ValidatorResult should contain the '" + ACTION +"' action.", lastNameResult.containsAction(ACTION)); assertTrue("Last Name ValidatorResult for the '" + ACTION +"' action should have passed.", lastNameResult.isValid(ACTION)); } /** * Tests if we can override a rule. We "can" override a rule if the message shown * when the firstName required test fails and the lastName test is null. */ public void testOverrideRule() throws ValidatorException { // Create bean to run test on. NameBean name = new NameBean(); name.setLastName("Smith"); // Construct validator based on the loaded resources // and the form key Validator validator = new Validator(resources, FORM_KEY2); // add the name bean to the validator as a resource // for the validations to be performed on. validator.setParameter(Validator.BEAN_PARAM, name); // Get results of the validation. ValidatorResults results = null; results = validator.validate(); assertNotNull("Results are null.", results); ValidatorResult firstNameResult = results.getValidatorResult("firstName"); ValidatorResult lastNameResult = results.getValidatorResult("lastName"); assertNotNull("First Name ValidatorResult should not be null.", firstNameResult); assertTrue("First Name ValidatorResult for the '" + ACTION +"' action should have '" + CHECK_MSG_KEY + " as a key.", firstNameResult.field.getArg(0).getKey().equals(CHECK_MSG_KEY)); assertNull("Last Name ValidatorResult should be null.", lastNameResult); } /** * Tests if the order is mantained when extending a form. Parent form fields should * preceed self form fields, except if we override the rules. */ public void testOrder() { Form form = resources.getForm(ValidatorResources.defaultLocale, FORM_KEY); Form form2 = resources.getForm(ValidatorResources.defaultLocale, FORM_KEY2); assertNotNull(FORM_KEY + " is null.", form); assertTrue("There should only be 2 fields in " + FORM_KEY, form.getFields().size() == 2); assertNotNull(FORM_KEY2 + " is null.", form2); assertTrue("There should only be 2 fields in " + FORM_KEY2, form2.getFields().size() == 2); //get the first field Field fieldFirstName = (Field)form.getFields().get(0); //get the second field Field fieldLastName = (Field)form.getFields().get(1); assertTrue("firstName in " + FORM_KEY + " should be the first in the list", fieldFirstName.getKey().equals("firstName")); assertTrue("lastName in " + FORM_KEY + " should be the first in the list", fieldLastName.getKey().equals("lastName")); // get the second field fieldLastName = (Field)form2.getFields().get(0); //get the first field fieldFirstName = (Field)form2.getFields().get(1); assertTrue("firstName in " + FORM_KEY2 + " should be the first in the list", fieldFirstName.getKey().equals("firstName")); assertTrue("lastName in " + FORM_KEY2 + " should be the first in the list", fieldLastName.getKey().equals("lastName")); } }commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/FieldTest.java100644 765 0 27442 11711227700 31717 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator; import junit.framework.TestCase; /** * Test Field objects. * * @version $Revision: 493905 $ $Date: 2007-01-08 03:11:38 +0100 (Mon, 08 Jan 2007) $ */ public class FieldTest extends TestCase { protected Field field; /** * FieldTest constructor. */ public FieldTest() { super(); } /** * FieldTest constructor. * @param name */ public FieldTest(String name) { super(name); } /** * Test setup */ public void setUp() { field = new Field(); } /** * Test clean up */ public void tearDown() { field = null; } /** * test Field with no arguments */ public void testEmptyArgs() { assertEquals("Empty Args(1) ", 0, field.getArgs("required").length); } /** * test Field with only 'default' arguments, no positions specified. */ public void testDefaultPositionImplied() { field.addArg(createArg("default-position-0")); field.addArg(createArg("default-position-1")); field.addArg(createArg("default-position-2")); assertEquals("testDefaultPositionImplied(1) ", 3, field.getArgs("required").length); assertEquals("testDefaultPositionImplied(2) ", "default-position-0", field.getArg("required", 0).getKey()); assertEquals("testDefaultPositionImplied(3) ", "default-position-1", field.getArg("required", 1).getKey()); assertEquals("testDefaultPositionImplied(4) ", "default-position-2", field.getArg("required", 2).getKey()); } /** * test Field with only 'default' arguments, positions specified. */ public void testDefaultUsingPositions() { field.addArg(createArg("default-position-1", 1)); field.addArg(createArg("default-position-0", 0)); field.addArg(createArg("default-position-2", 2)); assertEquals("testDefaultUsingPositions(1) ", 3, field.getArgs("required").length); assertEquals("testDefaultUsingPositions(2) ", "default-position-0", field.getArg("required", 0).getKey()); assertEquals("testDefaultUsingPositions(3) ", "default-position-1", field.getArg("required", 1).getKey()); assertEquals("testDefaultUsingPositions(4) ", "default-position-2", field.getArg("required", 2).getKey()); } /** * test Field with only 'default' arguments, position specified for one argument */ public void testDefaultOnePosition() { field.addArg(createArg("default-position-0")); field.addArg(createArg("default-position-2", 2)); field.addArg(createArg("default-position-3")); assertEquals("testDefaultOnePosition(1) ", 4, field.getArgs("required").length); assertEquals("testDefaultOnePosition(2) ", "default-position-0", field.getArg("required", 0).getKey()); assertNull("testDefaultOnePosition(3) ", field.getArg("required", 1)); assertEquals("testDefaultOnePosition(4) ", "default-position-2", field.getArg("required", 2).getKey()); assertEquals("testDefaultOnePosition(5) ", "default-position-3", field.getArg("required", 3).getKey()); } /** * test Field with only 'default' arguments, some position specified. */ public void testDefaultSomePositions() { field.addArg(createArg("default-position-0")); field.addArg(createArg("default-position-2", 2)); field.addArg(createArg("default-position-3")); field.addArg(createArg("default-position-1", 1)); assertEquals("testDefaultSomePositions(1) ", 4, field.getArgs("required").length); assertEquals("testDefaultSomePositions(2) ", "default-position-0", field.getArg("required", 0).getKey()); assertEquals("testDefaultSomePositions(3) ", "default-position-1", field.getArg("required", 1).getKey()); assertEquals("testDefaultSomePositions(4) ", "default-position-2", field.getArg("required", 2).getKey()); assertEquals("testDefaultSomePositions(5) ", "default-position-3", field.getArg("required", 3).getKey()); } /** * test Field with a 'default' argument overriden using 'position' property */ public void testOverrideUsingPositionA() { field.addArg(createArg("default-position-0")); field.addArg(createArg("default-position-1")); field.addArg(createArg("default-position-2")); field.addArg(createArg("required-position-1", "required", 1)); // use 'required' as name assertEquals("testOverrideUsingPositionA(1) ", 3, field.getArgs("required").length); assertEquals("testOverrideUsingPositionA(2) ", "required-position-1", field.getArg("required", 1).getKey()); // use 'mask' as name assertEquals("testOverrideUsingPositionA(3) ", 3, field.getArgs("mask").length); assertEquals("testOverrideUsingPositionA(4) ", "default-position-1", field.getArg("mask", 1).getKey()); // Get Default assertEquals("testOverrideUsingPositionA(5) ", "default-position-1", field.getArg(1).getKey()); } /** * test Field with a 'default' argument overriden using 'position' property */ public void testOverrideUsingPositionB() { field.addArg(createArg("required-position-3", "required", 3)); field.addArg(createArg("required-position-1", "required", 1)); field.addArg(createArg("default-position-0")); field.addArg(createArg("default-position-1")); field.addArg(createArg("default-position-2")); // use 'required' as name assertEquals("testOverrideUsingPositionB(1) ", 4, field.getArgs("required").length); assertEquals("testOverrideUsingPositionB(2) ", "default-position-0", field.getArg("required", 0).getKey()); assertEquals("testOverrideUsingPositionB(3) ", "required-position-1", field.getArg("required", 1).getKey()); assertEquals("testOverrideUsingPositionB(4) ", "default-position-2", field.getArg("required", 2).getKey()); assertEquals("testOverrideUsingPositionB(5) ", "required-position-3", field.getArg("required", 3).getKey()); // use 'mask' as name assertEquals("testOverrideUsingPositionB(6) ", 4, field.getArgs("mask").length); assertEquals("testOverrideUsingPositionB(6) ", "default-position-0", field.getArg("mask", 0).getKey()); assertEquals("testOverrideUsingPositionB(7) ", "default-position-1", field.getArg("mask", 1).getKey()); assertEquals("testOverrideUsingPositionB(8) ", "default-position-2", field.getArg("mask", 2).getKey()); assertNull("testOverrideUsingPositionB(9) ", field.getArg("mask", 3)); } /** * test Field with a 'default' argument overriden without positions specified. */ public void testOverridePositionImplied() { field.addArg(createArg("default-position-0")); field.addArg(createArg("required-position-1", "required")); field.addArg(createArg("required-position-2", "required")); field.addArg(createArg("mask-position-1", "mask")); // use 'required' as name assertEquals("testOverridePositionImplied(1) ", 3, field.getArgs("required").length); assertEquals("testOverridePositionImplied(2) ", "default-position-0", field.getArg("required", 0).getKey()); assertEquals("testOverridePositionImplied(3) ", "required-position-1", field.getArg("required", 1).getKey()); assertEquals("testOverridePositionImplied(4) ", "required-position-2", field.getArg("required", 2).getKey()); // use 'mask' as name assertEquals("testOverridePositionImplied(5) ", 3, field.getArgs("mask").length); assertEquals("testOverridePositionImplied(6) ", "default-position-0", field.getArg("mask", 0).getKey()); assertEquals("testOverridePositionImplied(7) ", "mask-position-1", field.getArg("mask", 1).getKey()); assertNull("testOverridePositionImplied(8) ", field.getArg("mask", 2)); // Get Defaults assertEquals("testOverridePositionImplied(9) ", "default-position-0", field.getArg(0).getKey()); assertNull("testOverridePositionImplied(10) ", field.getArg(1)); assertNull("testOverridePositionImplied(11) ", field.getArg(2)); } /** * test Field with a 'default' argument overriden with some positions specified */ public void testOverrideSomePosition() { field.addArg(createArg("default-position-0")); field.addArg(createArg("default-position-1")); field.addArg(createArg("default-position-2")); field.addArg(createArg("required-position-1", "required", 1)); field.addArg(createArg("required-position-2", "required")); field.addArg(createArg("mask-position-3", "mask")); // use 'required' as name assertEquals("testOverrideSomePosition(1) ", 4, field.getArgs("required").length); assertEquals("testOverrideSomePosition(2) ", "default-position-0", field.getArg("required", 0).getKey()); assertEquals("testOverrideSomePosition(3) ", "required-position-1", field.getArg("required", 1).getKey()); assertEquals("testOverrideSomePosition(4) ", "required-position-2", field.getArg("required", 2).getKey()); assertNull("testOverrideSomePosition(5) ", field.getArg("required", 3)); // use 'mask' as name assertEquals("testOverrideSomePosition(6) ", 4, field.getArgs("mask").length); assertEquals("testOverrideSomePosition(7) ", "default-position-0", field.getArg("mask", 0).getKey()); assertEquals("testOverrideSomePosition(8) ", "default-position-1", field.getArg("mask", 1).getKey()); assertEquals("testOverrideSomePosition(9) ", "default-position-2", field.getArg("mask", 2).getKey()); assertEquals("testOverrideSomePosition(10) ", "mask-position-3", field.getArg("mask", 3).getKey()); // Get Defaults assertEquals("testOverrideSomePosition(11) ", "default-position-0", field.getArg(0).getKey()); assertEquals("testOverrideSomePosition(12) ", "default-position-1", field.getArg(1).getKey()); assertEquals("testOverrideSomePosition(13) ", "default-position-2", field.getArg(2).getKey()); assertNull("testOverrideSomePosition(14) ", field.getArg(3)); } /** * Convenience Method - create argument (no name or position specified) */ private Arg createArg(String key) { Arg arg = new Arg(); arg.setKey(key); return arg; } /** * Convenience Method - create argument (no name, position specified) */ private Arg createArg(String key, int position) { Arg arg = createArg(key); arg.setPosition(position); return arg; } /** * Convenience Method - create argument (name specified, no position) */ private Arg createArg(String key, String name) { Arg arg = createArg(key); arg.setName(name); return arg; } /** * Convenience Method - create argument (name & position specified) */ private Arg createArg(String key, String name, int position) { Arg arg = createArg(key, name); arg.setPosition(position); return arg; } } commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/FloatTest.java100644 765 0 4507 11711227700 31716 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator; /** * Performs Validation Test for float validations. * * @version $Revision: 1094751 $ $Date: 2011-04-18 23:17:40 +0200 (Mon, 18 Apr 2011) $ */ public class FloatTest extends AbstractNumberTest { public FloatTest(String name) { super(name); ACTION = "float"; FORM_KEY = "floatForm"; } /** * Tests the float validation. */ public void testFloat() throws ValidatorException { // Create bean to run test on. ValueBean info = new ValueBean(); info.setValue("0"); valueTest(info, true); } /** * Tests the float validation. */ public void testFloatMin() throws ValidatorException { // Create bean to run test on. ValueBean info = new ValueBean(); info.setValue(new Float(Float.MIN_VALUE).toString()); valueTest(info, true); } /** * Tests the float validation. */ public void testFloatMax() throws ValidatorException { // Create bean to run test on. ValueBean info = new ValueBean(); info.setValue(new Float(Float.MAX_VALUE).toString()); valueTest(info, true); } /** * Tests the float validation failure. */ public void testFloatFailure() throws ValidatorException { // Create bean to run test on. ValueBean info = new ValueBean(); valueTest(info, false); } } ././@LongLink100644 0 0 145 11711231552 10251 Lustar 0 0 commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/GenericTypeValidatorImpl.javacommons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/GenericTypeValidatorImpl.java100644 765 0 23231 11711227700 34732 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator; import java.util.*; import org.apache.commons.validator.util.ValidatorUtils; /** * Contains validation methods for different unit tests. * * @version $Revision: 1094801 $ $Date: 2011-04-19 00:45:45 +0200 (Tue, 19 Apr 2011) $ */ public class GenericTypeValidatorImpl { /** * Checks if the field can be successfully converted to a byte. * * @param bean The value validation is being performed on. * @param field the field to use * @return boolean If the field can be successfully converted * to a byte true is returned. * Otherwise false. */ public static Byte validateByte(Object bean, Field field) { String value = ValidatorUtils.getValueAsString(bean, field.getProperty()); return GenericTypeValidator.formatByte(value); } /** * Checks if the field can be successfully converted to a byte. * * @param bean The value validation is being performed on. * @param field the field to use * @return boolean If the field can be successfully converted * to a byte true is returned. * Otherwise false. */ public static Byte validateByte(Object bean, Field field, Locale locale) { String value = ValidatorUtils.getValueAsString(bean, field.getProperty()); return GenericTypeValidator.formatByte(value, locale); } /** * Checks if the field can be successfully converted to a short. * * @param bean The value validation is being performed on. * @param field the field to use * @return boolean If the field can be successfully converted * to a short true is returned. * Otherwise false. */ public static Short validateShort(Object bean, Field field) { String value = ValidatorUtils.getValueAsString(bean, field.getProperty()); return GenericTypeValidator.formatShort(value); } /** * Checks if the field can be successfully converted to a short. * * @param bean The value validation is being performed on. * @param field the field to use * @return boolean If the field can be successfully converted * to a short true is returned. * Otherwise false. */ public static Short validateShort(Object bean, Field field, Locale locale) { String value = ValidatorUtils.getValueAsString(bean, field.getProperty()); return GenericTypeValidator.formatShort(value, locale); } /** * Checks if the field can be successfully converted to a int. * * @param bean The value validation is being performed on. * @param field the field to use * @return boolean If the field can be successfully converted * to a int true is returned. * Otherwise false. */ public static Integer validateInt(Object bean, Field field) { String value = ValidatorUtils.getValueAsString(bean, field.getProperty()); return GenericTypeValidator.formatInt(value); } /** * Checks if the field can be successfully converted to a int. * * @param bean The value validation is being performed on. * @param field the field to use * @return boolean If the field can be successfully converted * to a int true is returned. * Otherwise false. */ public static Integer validateInt(Object bean, Field field, Locale locale) { String value = ValidatorUtils.getValueAsString(bean, field.getProperty()); return GenericTypeValidator.formatInt(value, locale); } /** * Checks if the field can be successfully converted to a long. * * @param bean The value validation is being performed on. * @param field the field to use * @return boolean If the field can be successfully converted * to a long true is returned. * Otherwise false. */ public static Long validateLong(Object bean, Field field) { String value = ValidatorUtils.getValueAsString(bean, field.getProperty()); return GenericTypeValidator.formatLong(value); } /** * Checks if the field can be successfully converted to a long. * * @param bean The value validation is being performed on. * @param field the field to use * @return boolean If the field can be successfully converted * to a long true is returned. * Otherwise false. */ public static Long validateLong(Object bean, Field field, Locale locale) { String value = ValidatorUtils.getValueAsString(bean, field.getProperty()); return GenericTypeValidator.formatLong(value, locale); } /** * Checks if the field can be successfully converted to a float. * * @param bean The value validation is being performed on. * @param field the field to use * @return boolean If the field can be successfully converted * to a float true is returned. * Otherwise false. */ public static Float validateFloat(Object bean, Field field) { String value = ValidatorUtils.getValueAsString(bean, field.getProperty()); return GenericTypeValidator.formatFloat(value); } /** * Checks if the field can be successfully converted to a float. * * @param bean The value validation is being performed on. * @param field the field to use * @return boolean If the field can be successfully converted * to a float true is returned. * Otherwise false. */ public static Float validateFloat(Object bean, Field field, Locale locale) { String value = ValidatorUtils.getValueAsString(bean, field.getProperty()); return GenericTypeValidator.formatFloat(value, locale); } /** * Checks if the field can be successfully converted to a double. * * @param bean The value validation is being performed on. * @param field the field to use * @return boolean If the field can be successfully converted * to a double true is returned. * Otherwise false. */ public static Double validateDouble(Object bean, Field field) { String value = ValidatorUtils.getValueAsString(bean, field.getProperty()); return GenericTypeValidator.formatDouble(value); } /** * Checks if the field can be successfully converted to a double. * * @param bean The value validation is being performed on. * @param field the field to use * @return boolean If the field can be successfully converted * to a double true is returned. * Otherwise false. */ public static Double validateDouble(Object bean, Field field, Locale locale) { String value = ValidatorUtils.getValueAsString(bean, field.getProperty()); return GenericTypeValidator.formatDouble(value, locale); } /** * Checks if the field can be successfully converted to a date. * * @param bean The value validation is being performed on. * @param field the field to use * @return boolean If the field can be successfully converted * to a date true is returned. * Otherwise false. */ public static Date validateDate(Object bean, Field field, Locale locale) { String value = ValidatorUtils.getValueAsString(bean, field.getProperty()); return GenericTypeValidator.formatDate(value, locale); } /** * Checks if the field can be successfully converted to a date. * * @param bean The value validation is being performed on. * @param field the field to use * @return boolean If the field can be successfully converted * to a date true is returned. * Otherwise false. */ public static Date validateDate(Object bean, Field field) { String value = ValidatorUtils.getValueAsString(bean, field.getProperty()); String datePattern = field.getVarValue("datePattern"); String datePatternStrict = field.getVarValue("datePatternStrict"); Date result = null; if (datePattern != null && datePattern.length() > 0) { result = GenericTypeValidator.formatDate(value, datePattern, false); } else if (datePatternStrict != null && datePatternStrict.length() > 0) { result = GenericTypeValidator.formatDate(value, datePatternStrict, true); } return result; } } ././@LongLink100644 0 0 145 11711231552 10251 Lustar 0 0 commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/GenericTypeValidatorTest.javacommons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/GenericTypeValidatorTest.java100644 765 0 17457 11711227700 34765 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator; import java.io.IOException; import java.util.Date; import java.util.Iterator; import java.util.Locale; import java.util.Map; import org.xml.sax.SAXException; /** * Performs Validation Test for type validations. * * @version $Revision: 1128355 $ $Date: 2011-05-27 17:16:36 +0200 (Fri, 27 May 2011) $ */ public class GenericTypeValidatorTest extends AbstractCommonTest { /** * The key used to retrieve the set of validation * rules from the xml file. */ protected static String FORM_KEY = "typeForm"; /** * The key used to retrieve the validator action. */ protected static String ACTION = "byte"; public GenericTypeValidatorTest(String name) { super(name); } /** * Load ValidatorResources from * validator-type.xml. */ protected void setUp() throws IOException, SAXException { // Load resources loadResources("GenericTypeValidatorTest-config.xml"); } protected void tearDown() { } /** * Tests the byte validation. */ public void testType() throws ValidatorException { // Create bean to run test on. TypeBean info = new TypeBean(); info.setByte("12"); info.setShort("129"); info.setInteger("-144"); info.setLong("88000"); info.setFloat("12.1555f"); info.setDouble("129.1551511111d"); // Construct validator based on the loaded resources // and the form key Validator validator = new Validator(resources, FORM_KEY); // add the name bean to the validator as a resource // for the validations to be performed on. validator.setParameter(Validator.BEAN_PARAM, info); // Get results of the validation. ValidatorResults results = null; // throws ValidatorException, // but we aren't catching for testing // since no validation methods we use // throw this results = validator.validate(); assertNotNull("Results are null.", results); Map hResultValues = results.getResultValueMap(); assertTrue("Expecting byte result to be an instance of Byte.", (hResultValues.get("byte") instanceof Byte)); assertTrue("Expecting short result to be an instance of Short.", (hResultValues.get("short") instanceof Short)); assertTrue("Expecting integer result to be an instance of Integer.", (hResultValues.get("integer") instanceof Integer)); assertTrue("Expecting long result to be an instance of Long.", (hResultValues.get("long") instanceof Long)); assertTrue("Expecting float result to be an instance of Float.", (hResultValues.get("float") instanceof Float)); assertTrue("Expecting double result to be an instance of Double.", (hResultValues.get("double") instanceof Double)); for (Iterator i = hResultValues.keySet().iterator(); i.hasNext(); ) { String key = (String)i.next(); Object value = hResultValues.get(key); assertNotNull("value ValidatorResults.getResultValueMap() should not be null.", value); } //ValidatorResult result = results.getValidatorResult("value"); //assertNotNull(ACTION + " value ValidatorResult should not be null.", result); //assertTrue(ACTION + " value ValidatorResult should contain the '" + ACTION +"' action.", result.containsAction(ACTION)); //assertTrue(ACTION + " value ValidatorResult for the '" + ACTION +"' action should have " + (passed ? "passed" : "failed") + ".", (passed ? result.isValid(ACTION) : !result.isValid(ACTION))); } /** * Tests the us locale */ public void testUSLocale() throws ValidatorException { // Create bean to run test on. TypeBean info = new TypeBean(); info.setByte("12"); info.setShort("129"); info.setInteger("-144"); info.setLong("88000"); info.setFloat("12.1555"); info.setDouble("129.1551511111"); info.setDate("12/21/2010"); localeTest(info, Locale.US); } /** * Tests the fr locale. */ public void testFRLocale() throws ValidatorException { // Create bean to run test on. TypeBean info = new TypeBean(); info.setByte("12"); info.setShort("-129"); info.setInteger("1443"); info.setLong("88000"); info.setFloat("12,1555"); info.setDouble("129,1551511111"); info.setDate("21/12/2010"); Map map = localeTest(info, Locale.FRENCH); assertTrue("float value not correct", ((Float)map.get("float")).intValue() == 12); assertTrue("double value not correct", ((Double)map.get("double")).intValue() == 129); } /** * Tests the locale. */ private Map localeTest(TypeBean info, Locale locale) throws ValidatorException { // Construct validator based on the loaded resources // and the form key Validator validator = new Validator(resources, "typeLocaleForm"); // add the name bean to the validator as a resource // for the validations to be performed on. validator.setParameter(Validator.BEAN_PARAM, info); validator.setParameter("java.util.Locale", locale); // Get results of the validation. ValidatorResults results = null; // throws ValidatorException, // but we aren't catching for testing // since no validation methods we use // throw this results = validator.validate(); assertNotNull("Results are null.", results); Map hResultValues = results.getResultValueMap(); assertTrue("Expecting byte result to be an instance of Byte for locale: "+locale, (hResultValues.get("byte") instanceof Byte)); assertTrue("Expecting short result to be an instance of Short for locale: "+locale, (hResultValues.get("short") instanceof Short)); assertTrue("Expecting integer result to be an instance of Integer for locale: "+locale, (hResultValues.get("integer") instanceof Integer)); assertTrue("Expecting long result to be an instance of Long for locale: "+locale, (hResultValues.get("long") instanceof Long)); assertTrue("Expecting float result to be an instance of Float for locale: "+locale, (hResultValues.get("float") instanceof Float)); assertTrue("Expecting double result to be an instance of Double for locale: "+locale, (hResultValues.get("double") instanceof Double)); assertTrue("Expecting date result to be an instance of Date for locale: "+locale, (hResultValues.get("date") instanceof Date)); for (Iterator i = hResultValues.keySet().iterator(); i.hasNext(); ) { String key = (String)i.next(); Object value = hResultValues.get(key); assertNotNull("value ValidatorResults.getResultValueMap() should not be null for locale: "+locale, value); } return hResultValues; } } commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/GenericValidatorImpl.java100644 765 0 25360 11711227700 34075 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator; import org.apache.commons.validator.util.ValidatorUtils; /** * Contains validation methods for different unit tests. * * @version $Revision: 1094802 $ $Date: 2011-04-19 00:47:06 +0200 (Tue, 19 Apr 2011) $ */ public class GenericValidatorImpl { /** * Throws a runtime exception if the value of the argument is "RUNTIME", * an exception if the value of the argument is "CHECKED", and a * ValidatorException otherwise. * * @throws RuntimeException with "RUNTIME-EXCEPTION as message" * if value is "RUNTIME" * @throws Exception with "CHECKED-EXCEPTION" as message * if value is "CHECKED" * @throws ValidatorException with "VALIDATOR-EXCEPTION" as message * otherwise */ public static boolean validateRaiseException( final Object bean, final Field field) throws Exception { final String value = ValidatorUtils.getValueAsString(bean, field.getProperty()); if ("RUNTIME".equals(value)) { throw new RuntimeException("RUNTIME-EXCEPTION"); } else if ("CHECKED".equals(value)) { throw new Exception("CHECKED-EXCEPTION"); } else { throw new ValidatorException("VALIDATOR-EXCEPTION"); } } /** * Checks if the field is required. * * @return boolean If the field isn't null and * has a length greater than zero, true is returned. * Otherwise false. */ public static boolean validateRequired(Object bean, Field field) { String value = ValidatorUtils.getValueAsString(bean, field.getProperty()); return !GenericValidator.isBlankOrNull(value); } /** * Checks if the field can be successfully converted to a byte. * * @param bean The value validation is being performed on. * @param field the field to use * @return boolean If the field can be successfully converted * to a byte true is returned. * Otherwise false. */ public static boolean validateByte(Object bean, Field field) { String value = ValidatorUtils.getValueAsString(bean, field.getProperty()); return GenericValidator.isByte(value); } /** * Checks if the field can be successfully converted to a short. * * @param bean The value validation is being performed on. * @param field the field to use * @return boolean If the field can be successfully converted * to a short true is returned. * Otherwise false. */ public static boolean validateShort(Object bean, Field field) { String value = ValidatorUtils.getValueAsString(bean, field.getProperty()); return GenericValidator.isShort(value); } /** * Checks if the field can be successfully converted to a int. * * @param bean The value validation is being performed on. * @param field the field to use * @return boolean If the field can be successfully converted * to a int true is returned. * Otherwise false. */ public static boolean validateInt(Object bean, Field field) { String value = ValidatorUtils.getValueAsString(bean, field.getProperty()); return GenericValidator.isInt(value); } /** * Checks if field is positive assuming it is an integer * * @param bean The value validation is being performed on. * @param field Description of the field to be evaluated * @return boolean If the integer field is greater than zero, returns * true, otherwise returns false. */ public static boolean validatePositive(Object bean , Field field) { String value = ValidatorUtils.getValueAsString(bean, field.getProperty()); return GenericTypeValidator.formatInt(value).intValue() > 0; } /** * Checks if the field can be successfully converted to a long. * * @param bean The value validation is being performed on. * @param field the field to use * @return boolean If the field can be successfully converted * to a long true is returned. * Otherwise false. */ public static boolean validateLong(Object bean, Field field) { String value = ValidatorUtils.getValueAsString(bean, field.getProperty()); return GenericValidator.isLong(value); } /** * Checks if the field can be successfully converted to a float. * * @param bean The value validation is being performed on. * @param field the field to use * @return boolean If the field can be successfully converted * to a float true is returned. * Otherwise false. */ public static boolean validateFloat(Object bean, Field field) { String value = ValidatorUtils.getValueAsString(bean, field.getProperty()); return GenericValidator.isFloat(value); } /** * Checks if the field can be successfully converted to a double. * * @param bean The value validation is being performed on. * @param field the field to use * @return boolean If the field can be successfully converted * to a double true is returned. * Otherwise false. */ public static boolean validateDouble(Object bean, Field field) { String value = ValidatorUtils.getValueAsString(bean, field.getProperty()); return GenericValidator.isDouble(value); } /** * Checks if the field is an e-mail address. * * @param bean The value validation is being performed on. * @param field the field to use * @return boolean If the field is an e-mail address * true is returned. * Otherwise false. */ public static boolean validateEmail(Object bean, Field field) { String value = ValidatorUtils.getValueAsString(bean, field.getProperty()); return GenericValidator.isEmail(value); } public final static String FIELD_TEST_NULL = "NULL"; public final static String FIELD_TEST_NOTNULL = "NOTNULL"; public final static String FIELD_TEST_EQUAL = "EQUAL"; public static boolean validateRequiredIf( Object bean, Field field, Validator validator) { Object form = validator.getParameterValue(Validator.BEAN_PARAM); String value = null; boolean required = false; if (isString(bean)) { value = (String) bean; } else { value = ValidatorUtils.getValueAsString(bean, field.getProperty()); } int i = 0; String fieldJoin = "AND"; if (!GenericValidator.isBlankOrNull(field.getVarValue("fieldJoin"))) { fieldJoin = field.getVarValue("fieldJoin"); } if (fieldJoin.equalsIgnoreCase("AND")) { required = true; } while (!GenericValidator.isBlankOrNull(field.getVarValue("field[" + i + "]"))) { String dependProp = field.getVarValue("field[" + i + "]"); String dependTest = field.getVarValue("fieldTest[" + i + "]"); String dependTestValue = field.getVarValue("fieldValue[" + i + "]"); String dependIndexed = field.getVarValue("fieldIndexed[" + i + "]"); if (dependIndexed == null) dependIndexed = "false"; String dependVal = null; boolean this_required = false; if (field.isIndexed() && dependIndexed.equalsIgnoreCase("true")) { String key = field.getKey(); if ((key.indexOf("[") > -1) && (key.indexOf("]") > -1)) { String ind = key.substring(0, key.indexOf(".") + 1); dependProp = ind + dependProp; } } dependVal = ValidatorUtils.getValueAsString(form, dependProp); if (dependTest.equals(FIELD_TEST_NULL)) { if ((dependVal != null) && (dependVal.length() > 0)) { this_required = false; } else { this_required = true; } } if (dependTest.equals(FIELD_TEST_NOTNULL)) { if ((dependVal != null) && (dependVal.length() > 0)) { this_required = true; } else { this_required = false; } } if (dependTest.equals(FIELD_TEST_EQUAL)) { this_required = dependTestValue.equalsIgnoreCase(dependVal); } if (fieldJoin.equalsIgnoreCase("AND")) { required = required && this_required; } else { required = required || this_required; } i++; } if (required) { if ((value != null) && (value.length() > 0)) { return true; } else { return false; } } return true; } private static Class stringClass = new String().getClass(); private static boolean isString(Object o) { if (o == null) return true; return (stringClass.isInstance(o)); } } commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/GenericValidatorTest.java100644 765 0 6663 11711227700 34100 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator; import junit.framework.TestCase; /** * Test the GenericValidator class. * * @version $Revision: 493905 $ $Date: 2007-01-08 03:11:38 +0100 (Mon, 08 Jan 2007) $ */ public class GenericValidatorTest extends TestCase { /** * Constructor for GenericValidatorTest. */ public GenericValidatorTest(String name) { super(name); } public void testMinLength() { // Use 0 for line end length assertTrue("Min=5 End=0", GenericValidator.minLength("12345\n\r", 5, 0)); assertFalse("Min=6 End=0", GenericValidator.minLength("12345\n\r", 6, 0)); assertFalse("Min=7 End=0", GenericValidator.minLength("12345\n\r", 7, 0)); assertFalse("Min=8 End=0", GenericValidator.minLength("12345\n\r", 8, 0)); // Use 1 for line end length assertTrue("Min=5 End=1", GenericValidator.minLength("12345\n\r", 5, 1)); assertTrue("Min=6 End=1", GenericValidator.minLength("12345\n\r", 6, 1)); assertFalse("Min=7 End=1", GenericValidator.minLength("12345\n\r", 7, 1)); assertFalse("Min=8 End=1", GenericValidator.minLength("12345\n\r", 8, 1)); // Use 2 for line end length assertTrue("Min=5 End=2", GenericValidator.minLength("12345\n\r", 5, 2)); assertTrue("Min=6 End=2", GenericValidator.minLength("12345\n\r", 6, 2)); assertTrue("Min=7 End=2", GenericValidator.minLength("12345\n\r", 7, 2)); assertFalse("Min=8 End=2", GenericValidator.minLength("12345\n\r", 8, 2)); } public void testMaxLength() { // Use 0 for line end length assertFalse("Max=4 End=0", GenericValidator.maxLength("12345\n\r", 4, 0)); assertTrue("Max=5 End=0", GenericValidator.maxLength("12345\n\r", 5, 0)); assertTrue("Max=6 End=0", GenericValidator.maxLength("12345\n\r", 6, 0)); assertTrue("Max=7 End=0", GenericValidator.maxLength("12345\n\r", 7, 0)); // Use 1 for line end length assertFalse("Max=4 End=1", GenericValidator.maxLength("12345\n\r", 4, 1)); assertFalse("Max=5 End=1", GenericValidator.maxLength("12345\n\r", 5, 1)); assertTrue("Max=6 End=1", GenericValidator.maxLength("12345\n\r", 6, 1)); assertTrue("Max=7 End=1", GenericValidator.maxLength("12345\n\r", 7, 1)); // Use 2 for line end length assertFalse("Max=4 End=2", GenericValidator.maxLength("12345\n\r", 4, 2)); assertFalse("Max=5 End=2", GenericValidator.maxLength("12345\n\r", 5, 2)); assertFalse("Max=6 End=2", GenericValidator.maxLength("12345\n\r", 6, 2)); assertTrue("Max=7 End=2", GenericValidator.maxLength("12345\n\r", 7, 2)); } } commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/ISBNValidatorTest.java100644 765 0 4660 11711227700 33252 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator; import junit.framework.TestCase; /** * ISBNValidator Test Case. * * @version $Revision: 1094806 $ $Date: 2011-04-19 00:53:09 +0200 (Tue, 19 Apr 2011) $ * @deprecated to be removed when the org.apache.commons.validator.ISBNValidator class is removed */ public class ISBNValidatorTest extends TestCase { private static final String VALID_ISBN_RAW = "1930110995"; private static final String VALID_ISBN_DASHES = "1-930110-99-5"; private static final String VALID_ISBN_SPACES = "1 930110 99 5"; private static final String VALID_ISBN_X = "0-201-63385-X"; private static final String INVALID_ISBN = "068-556-98-45"; public ISBNValidatorTest(String name) { super(name); } public void testIsValid() throws Exception { ISBNValidator validator = new ISBNValidator(); assertFalse(validator.isValid(null)); assertFalse(validator.isValid("")); assertFalse(validator.isValid("1")); assertFalse(validator.isValid("12345678901234")); assertFalse(validator.isValid("dsasdsadsads")); assertFalse(validator.isValid("535365")); assertFalse(validator.isValid("I love sparrows!")); assertFalse(validator.isValid("--1 930110 99 5")); assertFalse(validator.isValid("1 930110 99 5--")); assertFalse(validator.isValid("1 930110-99 5-")); assertTrue(validator.isValid(VALID_ISBN_RAW)); assertTrue(validator.isValid(VALID_ISBN_DASHES)); assertTrue(validator.isValid(VALID_ISBN_SPACES)); assertTrue(validator.isValid(VALID_ISBN_X)); assertFalse(validator.isValid(INVALID_ISBN)); } } commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/IntegerTest.java100644 765 0 5515 11711227700 32246 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator; /** * Performs Validation Test for int validations. * * @version $Revision: 1094751 $ $Date: 2011-04-18 23:17:40 +0200 (Mon, 18 Apr 2011) $ */ public class IntegerTest extends AbstractNumberTest { public IntegerTest(String name) { super(name); FORM_KEY = "intForm"; ACTION = "int"; } /** * Tests the int validation. */ public void testInt() throws ValidatorException { // Create bean to run test on. ValueBean info = new ValueBean(); info.setValue("0"); valueTest(info, true); } /** * Tests the int validation. */ public void testIntMin() throws ValidatorException { // Create bean to run test on. ValueBean info = new ValueBean(); info.setValue(new Integer(Integer.MIN_VALUE).toString()); valueTest(info, true); } /** * Tests the int validation. */ public void testIntegerMax() throws ValidatorException { // Create bean to run test on. ValueBean info = new ValueBean(); info.setValue(new Integer(Integer.MAX_VALUE).toString()); valueTest(info, true); } /** * Tests the int validation failure. */ public void testIntFailure() throws ValidatorException { // Create bean to run test on. ValueBean info = new ValueBean(); valueTest(info, false); } /** * Tests the int validation failure. */ public void testIntBeyondMin() throws ValidatorException { // Create bean to run test on. ValueBean info = new ValueBean(); info.setValue(Integer.MIN_VALUE + "1"); valueTest(info, false); } /** * Tests the int validation failure. */ public void testIntBeyondMax() throws ValidatorException { // Create bean to run test on. ValueBean info = new ValueBean(); info.setValue(Integer.MAX_VALUE + "1"); valueTest(info, false); } }commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/LocaleTest.java100644 765 0 14263 11711227700 32070 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator; import java.io.IOException; import java.util.Locale; import org.xml.sax.SAXException; /** * Performs Validation Test for locale validations. * * @version $Revision: 1094751 $ $Date: 2011-04-18 23:17:40 +0200 (Mon, 18 Apr 2011) $ */ public class LocaleTest extends AbstractCommonTest { /** * The key used to retrieve the set of validation rules from the xml file. */ protected static String FORM_KEY = "nameForm"; /** The key used to retrieve the validator action. */ protected static String ACTION = "required"; /** * Constructor for the LocaleTest object * * @param name param */ public LocaleTest(String name) { super(name); } /** * Load ValidatorResources from validator-locale.xml. * * @exception IOException If something goes wrong * @exception SAXException If something goes wrong */ protected void setUp() throws IOException, SAXException { // Load resources loadResources("LocaleTest-config.xml"); } /** The teardown method for JUnit */ protected void tearDown() { } /** * See what happens when we try to validate with a Locale, Country and * variant. Also check if the added locale validation field is getting used. * * @exception ValidatorException If something goes wrong */ public void testLocale1() throws ValidatorException { // Create bean to run test on. NameBean name = new NameBean(); name.setFirstName(""); name.setLastName(""); valueTest(name, new Locale("en", "US", "TEST1"), false, false, false); } /** * See what happens when we try to validate with a Locale, Country and * variant * * @exception ValidatorException If something goes wrong */ public void testLocale2() throws ValidatorException { // Create bean to run test on. NameBean name = new NameBean(); name.setFirstName(""); name.setLastName(""); valueTest(name, new Locale("en", "US", "TEST2"), true, false, true); } /** * See what happens when we try to validate with a Locale, Country and * variant * * @exception ValidatorException If something goes wrong */ public void testLocale3() throws ValidatorException { // Create bean to run test on. NameBean name = new NameBean(); name.setFirstName(""); name.setLastName(""); valueTest(name, new Locale("en", "UK"), false, true, true); } /** * See if a locale of en_UK_TEST falls back to en_UK instead of default form * set. Bug #16920 states that this isn't happening, even though it is * passing this test. see #16920. * * @exception ValidatorException If something goes wrong */ public void testLocale4() throws ValidatorException { // Create bean to run test on. NameBean name = new NameBean(); name.setFirstName(""); name.setLastName(""); valueTest(name, new Locale("en", "UK", "TEST"), false, true, true); } /** * See if a locale of language=en falls back to default form set. * * @exception ValidatorException If something goes wrong */ public void testLocale5() throws ValidatorException { // Create bean to run test on. NameBean name = new NameBean(); name.setFirstName(""); name.setLastName(""); valueTest(name, new Locale("en", ""), false, false, true); } /** * Utlity class to run a test on a value. * * @param name param * @param loc param * @param firstGood param * @param lastGood param * @param middleGood param * @exception ValidatorException If something goes wrong */ private void valueTest(Object name, Locale loc, boolean firstGood, boolean lastGood, boolean middleGood) throws ValidatorException { // Construct validator based on the loaded resources // and the form key Validator validator = new Validator(resources, FORM_KEY); // add the name bean to the validator as a resource // for the validations to be performed on. validator.setParameter(Validator.BEAN_PARAM, name); validator.setParameter(Validator.LOCALE_PARAM, loc); // Get results of the validation. ValidatorResults results = null; // throws ValidatorException, // but we aren't catching for testing // since no validation methods we use // throw this results = validator.validate(); assertNotNull("Results are null.", results); ValidatorResult resultlast = results.getValidatorResult("lastName"); ValidatorResult resultfirst = results.getValidatorResult("firstName"); ValidatorResult resultmiddle = results.getValidatorResult("middleName"); if (firstGood) { assertNull(resultfirst); } else { assertNotNull(resultfirst); } if (middleGood) { assertNull(resultmiddle); } else { assertNotNull(resultmiddle); } if (lastGood) { assertNull(resultlast); } else { assertNotNull(resultlast); } } } commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/LongTest.java100644 765 0 5475 11711227700 31555 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator; /** * Performs Validation Test for long validations. * * @version $Revision: 1094751 $ $Date: 2011-04-18 23:17:40 +0200 (Mon, 18 Apr 2011) $ */ public class LongTest extends AbstractNumberTest { public LongTest(String name) { super(name); FORM_KEY = "longForm"; ACTION = "long"; } /** * Tests the long validation. */ public void testLong() throws ValidatorException { // Create bean to run test on. ValueBean info = new ValueBean(); info.setValue("0"); valueTest(info, true); } /** * Tests the long validation. */ public void testLongMin() throws ValidatorException { // Create bean to run test on. ValueBean info = new ValueBean(); info.setValue(new Long(Long.MIN_VALUE).toString()); valueTest(info, true); } /** * Tests the long validation. */ public void testLongMax() throws ValidatorException { // Create bean to run test on. ValueBean info = new ValueBean(); info.setValue(new Long(Long.MAX_VALUE).toString()); valueTest(info, true); } /** * Tests the long validation failure. */ public void testLongFailure() throws ValidatorException { // Create bean to run test on. ValueBean info = new ValueBean(); valueTest(info, false); } /** * Tests the long validation failure. */ public void testLongBeyondMin() throws ValidatorException { // Create bean to run test on. ValueBean info = new ValueBean(); info.setValue(Long.MIN_VALUE + "1"); valueTest(info, false); } /** * Tests the long validation failure. */ public void testLongBeyondMax() throws ValidatorException { // Create bean to run test on. ValueBean info = new ValueBean(); info.setValue(Long.MAX_VALUE + "1"); valueTest(info, false); } }commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/MultipleConfigFilesTest.java100644 765 0 23644 11711227700 34600 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator; import java.io.IOException; import java.io.InputStream; import junit.framework.TestCase; import org.xml.sax.SAXException; /** * Tests that validator rules split between 2 different XML files get * merged properly. * * @version $Revision: 1094808 $ $Date: 2011-04-19 00:57:51 +0200 (Tue, 19 Apr 2011) $ */ public class MultipleConfigFilesTest extends TestCase { /** * Resources used for validation tests. */ private ValidatorResources resources = null; /** * The key used to retrieve the set of validation * rules from the xml file. */ private static final String FORM_KEY = "nameForm"; /** * The key used to retrieve the validator action. */ private static final String ACTION = "required"; /** * Constructor for MultipleConfigFilesTest. * @param name */ public MultipleConfigFilesTest(String name) { super(name); } /** * Load ValidatorResources from multiple xml files. */ protected void setUp() throws IOException, SAXException { InputStream[] streams = new InputStream[] { this.getClass().getResourceAsStream( "MultipleConfigFilesTest-1-config.xml"), this.getClass().getResourceAsStream( "MultipleConfigFilesTest-2-config.xml")}; this.resources = new ValidatorResources(streams); for (int i = 0; i < streams.length; i++) { streams[i].close(); } } /** * Check the forms and constants from different config files have * been merged into the same FormSet. */ public void testMergedConfig() { // *********** Default Locale ******************* // Check the form from the first config file exists Form form1 = resources.getForm("", "", "", "testForm1"); assertNotNull("Form 'testForm1' not found", form1); // Check the form from the second config file exists Form form2 = resources.getForm("", "", "", "testForm2"); assertNotNull("Form 'testForm2' not found", form2); // Check the Constants for the form from the first config file Field field1 = form1.getField("testProperty1"); assertEquals("testProperty1 - const 1", "testConstValue1", field1.getVarValue("var11")); assertEquals("testProperty1 - const 2", "testConstValue2", field1.getVarValue("var12")); // Check the Constants for the form from the second config file Field field2 = form2.getField("testProperty2"); assertEquals("testProperty2 - const 1", "testConstValue1", field2.getVarValue("var21")); assertEquals("testProperty2 - const 2", "testConstValue2", field2.getVarValue("var22")); // *********** 'fr' locale ******************* // Check the form from the first config file exists Form form1_fr = resources.getForm("fr", "", "", "testForm1_fr"); assertNotNull("Form 'testForm1_fr' not found", form1_fr); // Check the form from the second config file exists Form form2_fr = resources.getForm("fr", "", "", "testForm2_fr"); assertNotNull("Form 'testForm2_fr' not found", form2_fr); // Check the Constants for the form from the first config file Field field1_fr = form1_fr.getField("testProperty1_fr"); assertEquals("testProperty1_fr - const 1", "testConstValue1_fr", field1_fr.getVarValue("var11_fr")); assertEquals("testProperty1_fr - const 2", "testConstValue2_fr", field1_fr.getVarValue("var12_fr")); // Check the Constants for the form from the second config file Field field2_fr = form2_fr.getField("testProperty2_fr"); assertEquals("testProperty2_fr - const 1", "testConstValue1_fr", field2_fr.getVarValue("var21_fr")); assertEquals("testProperty2_fr - const 2", "testConstValue2_fr", field2_fr.getVarValue("var22_fr")); } /** * With nothing provided, we should fail both because both are required. */ public void testBothBlank() throws ValidatorException { // Create bean to run test on. NameBean name = new NameBean(); // Construct validator based on the loaded resources // and the form key Validator validator = new Validator(resources, FORM_KEY); // add the name bean to the validator as a resource // for the validations to be performed on. validator.setParameter(Validator.BEAN_PARAM, name); // Get results of the validation. ValidatorResults results = null; // throws ValidatorException, // but we aren't catching for testing // since no validation methods we use // throw this results = validator.validate(); assertNotNull("Results are null.", results); ValidatorResult firstNameResult = results.getValidatorResult("firstName"); ValidatorResult lastNameResult = results.getValidatorResult("lastName"); assertNotNull(firstNameResult); assertTrue(firstNameResult.containsAction(ACTION)); assertTrue(!firstNameResult.isValid(ACTION)); assertNotNull(lastNameResult); assertTrue(lastNameResult.containsAction(ACTION)); assertTrue(!lastNameResult.isValid(ACTION)); assertTrue(!lastNameResult.containsAction("int")); } /** * If the first name fails required, and the second test fails int, we should get two errors. */ public void testRequiredFirstNameBlankLastNameShort() throws ValidatorException { // Create bean to run test on. NameBean name = new NameBean(); name.setFirstName(""); name.setLastName("Test"); // Construct validator based on the loaded resources // and the form key Validator validator = new Validator(resources, FORM_KEY); // add the name bean to the validator as a resource // for the validations to be performed on. validator.setParameter(Validator.BEAN_PARAM, name); // Get results of the validation. ValidatorResults results = null; results = validator.validate(); assertNotNull("Results are null.", results); ValidatorResult firstNameResult = results.getValidatorResult("firstName"); ValidatorResult lastNameResult = results.getValidatorResult("lastName"); assertNotNull(firstNameResult); assertTrue(firstNameResult.containsAction(ACTION)); assertTrue(!firstNameResult.isValid(ACTION)); assertNotNull(lastNameResult); assertTrue(lastNameResult.containsAction("int")); assertTrue(!lastNameResult.isValid("int")); } /** * If the first name is there, and the last name fails int, we should get one error. */ public void testRequiredLastNameShort() throws ValidatorException { // Create bean to run test on. NameBean name = new NameBean(); name.setFirstName("Test"); name.setLastName("Test"); // Construct validator based on the loaded resources // and the form key Validator validator = new Validator(resources, FORM_KEY); // add the name bean to the validator as a resource // for the validations to be performed on. validator.setParameter(Validator.BEAN_PARAM, name); // Get results of the validation. ValidatorResults results = null; results = validator.validate(); assertNotNull("Results are null.", results); ValidatorResult firstNameResult = results.getValidatorResult("firstName"); ValidatorResult lastNameResult = results.getValidatorResult("lastName"); assertNotNull(firstNameResult); assertTrue(firstNameResult.containsAction(ACTION)); assertTrue(firstNameResult.isValid(ACTION)); assertNotNull(lastNameResult); assertTrue(lastNameResult.containsAction("int")); assertTrue(!lastNameResult.isValid("int")); } /** * If first name is ok and last name is ok and is an int, no errors. */ public void testRequiredLastNameLong() throws ValidatorException { // Create bean to run test on. NameBean name = new NameBean(); name.setFirstName("Joe"); name.setLastName("12345678"); // Construct validator based on the loaded resources // and the form key Validator validator = new Validator(resources, FORM_KEY); // add the name bean to the validator as a resource // for the validations to be performed on. validator.setParameter(Validator.BEAN_PARAM, name); // Get results of the validation. ValidatorResults results = null; results = validator.validate(); assertNotNull("Results are null.", results); ValidatorResult firstNameResult = results.getValidatorResult("firstName"); ValidatorResult lastNameResult = results.getValidatorResult("lastName"); assertNotNull(firstNameResult); assertTrue(firstNameResult.containsAction(ACTION)); assertTrue(firstNameResult.isValid(ACTION)); assertNotNull(lastNameResult); assertTrue(lastNameResult.containsAction("int")); assertTrue(lastNameResult.isValid("int")); } } commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/MultipleTest.java100644 765 0 36136 11711227700 32467 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator; import java.io.IOException; import org.xml.sax.SAXException; /** * Performs Validation Test. * * @version $Revision: 1094751 $ $Date: 2011-04-18 23:17:40 +0200 (Mon, 18 Apr 2011) $ */ public class MultipleTest extends AbstractCommonTest { /** * The key used to retrieve the set of validation * rules from the xml file. */ protected static String FORM_KEY = "nameForm"; /** * The key used to retrieve the validator action. */ protected static String ACTION = "required"; public MultipleTest(String name) { super(name); } /** * Load ValidatorResources from * validator-multipletest.xml. */ protected void setUp() throws IOException, SAXException { // Load resources loadResources("MultipleTests-config.xml"); } protected void tearDown() { } /** * With nothing provided, we should fail both because both are required. */ public void testBothBlank() throws ValidatorException { // Create bean to run test on. NameBean name = new NameBean(); // Construct validator based on the loaded resources // and the form key Validator validator = new Validator(resources, FORM_KEY); // add the name bean to the validator as a resource // for the validations to be performed on. validator.setParameter(Validator.BEAN_PARAM, name); // Get results of the validation. ValidatorResults results = null; // throws ValidatorException, // but we aren't catching for testing // since no validation methods we use // throw this results = validator.validate(); assertNotNull("Results are null.", results); ValidatorResult firstNameResult = results.getValidatorResult("firstName"); ValidatorResult lastNameResult = results.getValidatorResult("lastName"); assertNotNull("First Name ValidatorResult should not be null.", firstNameResult); assertTrue("First Name ValidatorResult should contain the '" + ACTION +"' action.", firstNameResult.containsAction(ACTION)); assertTrue("First Name ValidatorResult for the '" + ACTION +"' action should have failed.", !firstNameResult.isValid(ACTION)); assertNotNull("Last Name ValidatorResult should not be null.", lastNameResult); assertTrue("Last Name ValidatorResult should contain the '" + ACTION +"' action.", lastNameResult.containsAction(ACTION)); assertTrue("Last Name ValidatorResult for the '" + ACTION +"' action should have failed.", !lastNameResult.isValid(ACTION)); assertTrue("Last Name ValidatorResults should not contain the 'int' action.", !lastNameResult.containsAction("int")); } /** * If the first name fails required, and the second test fails int, we should get two errors. */ public void testRequiredFirstNameBlankLastNameShort() throws ValidatorException { // Create bean to run test on. NameBean name = new NameBean(); name.setFirstName(""); name.setLastName("Test"); // Construct validator based on the loaded resources // and the form key Validator validator = new Validator(resources, FORM_KEY); // add the name bean to the validator as a resource // for the validations to be performed on. validator.setParameter(Validator.BEAN_PARAM, name); // Get results of the validation. ValidatorResults results = null; results = validator.validate(); assertNotNull("Results are null.", results); ValidatorResult firstNameResult = results.getValidatorResult("firstName"); ValidatorResult lastNameResult = results.getValidatorResult("lastName"); assertNotNull("First Name ValidatorResult should not be null.", firstNameResult); assertTrue("First Name ValidatorResult should contain the '" + ACTION +"' action.", firstNameResult.containsAction(ACTION)); assertTrue("First Name ValidatorResult for the '" + ACTION +"' action should have failed.", !firstNameResult.isValid(ACTION)); assertNotNull("Last Name ValidatorResult should not be null.", lastNameResult); assertTrue("Last Name ValidatorResult should contain the 'int' action.", lastNameResult.containsAction("int")); assertTrue("Last Name ValidatorResult for the 'int' action should have failed.", !lastNameResult.isValid("int")); } /** * If the first name is there, and the last name fails int, we should get one error. */ public void testRequiredLastNameShort() throws ValidatorException { // Create bean to run test on. NameBean name = new NameBean(); name.setFirstName("Test"); name.setLastName("Test"); // Construct validator based on the loaded resources // and the form key Validator validator = new Validator(resources, FORM_KEY); // add the name bean to the validator as a resource // for the validations to be performed on. validator.setParameter(Validator.BEAN_PARAM, name); // Get results of the validation. ValidatorResults results = null; results = validator.validate(); assertNotNull("Results are null.", results); ValidatorResult firstNameResult = results.getValidatorResult("firstName"); ValidatorResult lastNameResult = results.getValidatorResult("lastName"); assertNotNull("First Name ValidatorResult should not be null.", firstNameResult); assertTrue("First Name ValidatorResult should contain the '" + ACTION +"' action.", firstNameResult.containsAction(ACTION)); assertTrue("First Name ValidatorResult for the '" + ACTION +"' action should have passed.", firstNameResult.isValid(ACTION)); assertNotNull("Last Name ValidatorResult should not be null.", lastNameResult); assertTrue("Last Name ValidatorResult should contain the 'int' action.", lastNameResult.containsAction("int")); assertTrue("Last Name ValidatorResult for the 'int' action should have failed.", !lastNameResult.isValid("int")); } /** * If first name is ok and last name is ok and is an int, no errors. */ public void testRequiredLastNameLong() throws ValidatorException { // Create bean to run test on. NameBean name = new NameBean(); name.setFirstName("Joe"); name.setLastName("12345678"); // Construct validator based on the loaded resources // and the form key Validator validator = new Validator(resources, FORM_KEY); // add the name bean to the validator as a resource // for the validations to be performed on. validator.setParameter(Validator.BEAN_PARAM, name); // Get results of the validation. ValidatorResults results = null; results = validator.validate(); assertNotNull("Results are null.", results); ValidatorResult firstNameResult = results.getValidatorResult("firstName"); ValidatorResult lastNameResult = results.getValidatorResult("lastName"); assertNotNull("First Name ValidatorResult should not be null.", firstNameResult); assertTrue("First Name ValidatorResult should contain the '" + ACTION +"' action.", firstNameResult.containsAction(ACTION)); assertTrue("First Name ValidatorResult for the '" + ACTION +"' action should have passed.", firstNameResult.isValid(ACTION)); assertNotNull("Last Name ValidatorResult should not be null.", lastNameResult); assertTrue("Last Name ValidatorResult should contain the 'int' action.", lastNameResult.containsAction("int")); assertTrue("Last Name ValidatorResult for the 'int' action should have passed.", lastNameResult.isValid("int")); } /** * If middle name is not there, then the required dependent test should fail. * No other tests should run * * @throws ValidatorException */ public void testFailingFirstDependentValidator() throws ValidatorException { // Create bean to run test on. NameBean name = new NameBean(); // Construct validator based on the loaded resources // and the form key Validator validator = new Validator(resources, FORM_KEY); // add the name bean to the validator as a resource // for the validations to be performed on. validator.setParameter(Validator.BEAN_PARAM, name); // Get results of the validation. ValidatorResults results = null; results = validator.validate(); assertNotNull("Results are null.", results); ValidatorResult middleNameResult = results.getValidatorResult("middleName"); assertNotNull("Middle Name ValidatorResult should not be null.", middleNameResult); assertTrue("Middle Name ValidatorResult should contain the 'required' action.", middleNameResult.containsAction("required")); assertTrue("Middle Name ValidatorResult for the 'required' action should have failed", !middleNameResult.isValid("required")); assertTrue("Middle Name ValidatorResult should not contain the 'int' action.", !middleNameResult.containsAction("int")); assertTrue("Middle Name ValidatorResult should not contain the 'positive' action.", !middleNameResult.containsAction("positive")); } /** * If middle name is there but not int, then the required dependent test * should pass, but the int dependent test should fail. No other tests should * run. * * @throws ValidatorException */ public void testFailingNextDependentValidator() throws ValidatorException { // Create bean to run test on. NameBean name = new NameBean(); name.setMiddleName("TEST"); // Construct validator based on the loaded resources // and the form key Validator validator = new Validator(resources, FORM_KEY); // add the name bean to the validator as a resource // for the validations to be performed on. validator.setParameter(Validator.BEAN_PARAM, name); // Get results of the validation. ValidatorResults results = null; results = validator.validate(); assertNotNull("Results are null.", results); ValidatorResult middleNameResult = results.getValidatorResult("middleName"); assertNotNull("Middle Name ValidatorResult should not be null.", middleNameResult); assertTrue("Middle Name ValidatorResult should contain the 'required' action.", middleNameResult.containsAction("required")); assertTrue("Middle Name ValidatorResult for the 'required' action should have passed", middleNameResult.isValid("required")); assertTrue("Middle Name ValidatorResult should contain the 'int' action.", middleNameResult.containsAction("int")); assertTrue("Middle Name ValidatorResult for the 'int' action should have failed", !middleNameResult.isValid("int")); assertTrue("Middle Name ValidatorResult should not contain the 'positive' action.", !middleNameResult.containsAction("positive")); } /** * If middle name is there and a negative int, then the required and int * dependent tests should pass, but the positive test should fail. * * @throws ValidatorException */ public void testPassingDependentsFailingMain() throws ValidatorException { // Create bean to run test on. NameBean name = new NameBean(); name.setMiddleName("-2534"); // Construct validator based on the loaded resources // and the form key Validator validator = new Validator(resources, FORM_KEY); // add the name bean to the validator as a resource // for the validations to be performed on. validator.setParameter(Validator.BEAN_PARAM, name); // Get results of the validation. ValidatorResults results = null; results = validator.validate(); assertNotNull("Results are null.", results); ValidatorResult middleNameResult = results.getValidatorResult("middleName"); assertNotNull("Middle Name ValidatorResult should not be null.", middleNameResult); assertTrue("Middle Name ValidatorResult should contain the 'required' action.", middleNameResult.containsAction("required")); assertTrue("Middle Name ValidatorResult for the 'required' action should have passed", middleNameResult.isValid("required")); assertTrue("Middle Name ValidatorResult should contain the 'int' action.", middleNameResult.containsAction("int")); assertTrue("Middle Name ValidatorResult for the 'int' action should have passed", middleNameResult.isValid("int")); assertTrue("Middle Name ValidatorResult should contain the 'positive' action.", middleNameResult.containsAction("positive")); assertTrue("Middle Name ValidatorResult for the 'positive' action should have failed", !middleNameResult.isValid("positive")); } /** * If middle name is there and a positve int, then the required and int * dependent tests should pass, and the positive test should pass. * * @throws ValidatorException */ public void testPassingDependentsPassingMain() throws ValidatorException { // Create bean to run test on. NameBean name = new NameBean(); name.setMiddleName("2534"); // Construct validator based on the loaded resources // and the form key Validator validator = new Validator(resources, FORM_KEY); // add the name bean to the validator as a resource // for the validations to be performed on. validator.setParameter(Validator.BEAN_PARAM, name); // Get results of the validation. ValidatorResults results = null; results = validator.validate(); assertNotNull("Results are null.", results); ValidatorResult middleNameResult = results.getValidatorResult("middleName"); assertNotNull("Middle Name ValidatorResult should not be null.", middleNameResult); assertTrue("Middle Name ValidatorResult should contain the 'required' action.", middleNameResult.containsAction("required")); assertTrue("Middle Name ValidatorResult for the 'required' action should have passed", middleNameResult.isValid("required")); assertTrue("Middle Name ValidatorResult should contain the 'int' action.", middleNameResult.containsAction("int")); assertTrue("Middle Name ValidatorResult for the 'int' action should have passed", middleNameResult.isValid("int")); assertTrue("Middle Name ValidatorResult should contain the 'positive' action.", middleNameResult.containsAction("positive")); assertTrue("Middle Name ValidatorResult for the 'positive' action should have passed", middleNameResult.isValid("positive")); } } commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/NameBean.java100644 765 0 3217 11711227700 31454 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator; /** * Value object that contains a first name and last name. * * @version $Revision: 493905 $ $Date: 2007-01-08 03:11:38 +0100 (Mon, 08 Jan 2007) $ */ public class NameBean { protected String firstName = null; protected String middleName = null; protected String lastName = null; public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getMiddleName() { return middleName; } public void setMiddleName(String middleName) { this.middleName = middleName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } }commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/ParameterTest.java100644 765 0 7322 11711227700 32567 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator; import java.io.IOException; import java.util.Locale; import org.xml.sax.SAXException; /** * This TestCase is a confirmation of the parameter of the validator's method. * * @version $Revision: 1094808 $ $Date: 2011-04-19 00:57:51 +0200 (Tue, 19 Apr 2011) $ */ public class ParameterTest extends AbstractCommonTest { private static final String FORM_KEY = "nameForm"; private String firstName; private String middleName; private String lastName; /** * Constructor. */ public ParameterTest(String name) { super(name); } /** * Load ValidatorResources from * ValidatorResultsTest-config.xml. */ protected void setUp() throws IOException, SAXException { // Load resources loadResources("ParameterTest-config.xml"); // initialize values firstName = "foo"; middleName = "123"; lastName = "456"; } protected void tearDown() { } /** * Test all validations ran and passed. */ public void testAllValid() { // Create bean to run test on. NameBean bean = createNameBean(); Validator validator = new Validator(resources, FORM_KEY); // add the name bean to the validator as a resource // for the validations to be performed on. validator.setParameter(Validator.BEAN_PARAM, bean); validator.setParameter(Validator.LOCALE_PARAM, Locale.getDefault()); // Get results of the validation. try { validator.validate(); } catch(Exception e) { fail("Validator.validate() threw " + e); } assertParameterValue(validator, Validator.BEAN_PARAM, Object.class); assertParameterValue(validator, Validator.FIELD_PARAM, Field.class); assertParameterValue(validator, Validator.FORM_PARAM, Form.class); assertParameterValue(validator, Validator.LOCALE_PARAM, Locale.class); assertParameterValue(validator, Validator.VALIDATOR_ACTION_PARAM, ValidatorAction.class); assertParameterValue(validator, Validator.VALIDATOR_PARAM, Validator.class); assertParameterValue(validator, Validator.VALIDATOR_RESULTS_PARAM, ValidatorResults.class); } private void assertParameterValue(Validator validator, String name, Class type) { Object value = validator.getParameterValue(name); assertNotNull("Expected '" + type.getName() + "' but was null", value); assertTrue("Expected '" + type.getName() + "' but was '" + value.getClass().getName() + "'", type.isInstance(value)); } /** * Create a NameBean. */ private NameBean createNameBean() { NameBean name = new NameBean(); name.setFirstName(firstName); name.setMiddleName(middleName); name.setLastName(lastName); return name; } } commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/ParameterValidatorImpl.java100644 765 0 3235 11711227700 34416 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator; /** * Contains validation methods for different unit tests. * * @version $Revision: 493905 $ $Date: 2007-01-08 03:11:38 +0100 (Mon, 08 Jan 2007) $ */ public class ParameterValidatorImpl { /** * ValidatorParameter is valid. * */ public static boolean validateParameter( final java.lang.Object bean, final org.apache.commons.validator.Form form, final org.apache.commons.validator.Field field, final org.apache.commons.validator.Validator validator, final org.apache.commons.validator.ValidatorAction action, final org.apache.commons.validator.ValidatorResults results, final java.util.Locale locale) throws Exception { return true; } } commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/RequiredIfTest.java100644 765 0 24341 11711227700 32726 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator; import java.io.IOException; import org.xml.sax.SAXException; /** * Performs Validation Test. * * @version $Revision: 1094751 $ $Date: 2011-04-18 23:17:40 +0200 (Mon, 18 Apr 2011) $ */ public class RequiredIfTest extends AbstractCommonTest { /** * The key used to retrieve the set of validation * rules from the xml file. */ protected static String FORM_KEY = "nameForm"; /** * The key used to retrieve the validator action. */ protected static String ACTION = "requiredif"; public RequiredIfTest(String name) { super(name); } /** * Load ValidatorResources from * validator-requiredif.xml. */ protected void setUp() throws IOException, SAXException { // Load resources loadResources("RequiredIfTest-config.xml"); } protected void tearDown() { } /** * With nothing provided, we should pass since the fields only fail on * null if the other field is non-blank. */ public void testRequired() throws ValidatorException { // Create bean to run test on. NameBean name = new NameBean(); // Construct validator based on the loaded resources // and the form key Validator validator = new Validator(resources, FORM_KEY); // add the name bean to the validator as a resource // for the validations to be performed on. validator.setParameter(Validator.BEAN_PARAM, name); // Get results of the validation. ValidatorResults results = null; // throws ValidatorException, // but we aren't catching for testing // since no validation methods we use // throw this results = validator.validate(); assertNotNull("Results are null.", results); ValidatorResult firstNameResult = results.getValidatorResult("firstName"); ValidatorResult lastNameResult = results.getValidatorResult("lastName"); assertNotNull("First Name ValidatorResult should not be null.", firstNameResult); assertTrue("First Name ValidatorResult should contain the '" + ACTION +"' action.", firstNameResult.containsAction(ACTION)); assertTrue("First Name ValidatorResult for the '" + ACTION +"' action should have passed.", firstNameResult.isValid(ACTION)); assertNotNull("Last Name ValidatorResult should not be null.", lastNameResult); assertTrue("Last Name ValidatorResult should contain the '" + ACTION +"' action.", lastNameResult.containsAction(ACTION)); assertTrue("Last Name ValidatorResult for the '" + ACTION +"' action should have passed.", lastNameResult.isValid(ACTION)); } /** * Tests the required validation for first name if it is blank. */ public void testRequiredFirstNameBlank() throws ValidatorException { // Create bean to run test on. NameBean name = new NameBean(); name.setFirstName(""); name.setLastName("Test"); // Construct validator based on the loaded resources // and the form key Validator validator = new Validator(resources, FORM_KEY); // add the name bean to the validator as a resource // for the validations to be performed on. validator.setParameter(Validator.BEAN_PARAM, name); // Get results of the validation. ValidatorResults results = null; results = validator.validate(); assertNotNull("Results are null.", results); ValidatorResult firstNameResult = results.getValidatorResult("firstName"); ValidatorResult lastNameResult = results.getValidatorResult("lastName"); assertNotNull("First Name ValidatorResult should not be null.", firstNameResult); assertTrue("First Name ValidatorResult should contain the '" + ACTION +"' action.", firstNameResult.containsAction(ACTION)); assertTrue("First Name ValidatorResult for the '" + ACTION +"' action should have failed.", !firstNameResult.isValid(ACTION)); assertNotNull("Last Name ValidatorResult should not be null.", lastNameResult); assertTrue("Last Name ValidatorResult should contain the '" + ACTION +"' action.", lastNameResult.containsAction(ACTION)); assertTrue("Last Name ValidatorResult for the '" + ACTION +"' action should have passed.", lastNameResult.isValid(ACTION)); } /** * Tests the required validation for last name. */ public void testRequiredFirstName() throws ValidatorException { // Create bean to run test on. NameBean name = new NameBean(); name.setFirstName("Test"); name.setLastName("Test"); // Construct validator based on the loaded resources // and the form key Validator validator = new Validator(resources, FORM_KEY); // add the name bean to the validator as a resource // for the validations to be performed on. validator.setParameter(Validator.BEAN_PARAM, name); // Get results of the validation. ValidatorResults results = null; results = validator.validate(); assertNotNull("Results are null.", results); ValidatorResult firstNameResult = results.getValidatorResult("firstName"); ValidatorResult lastNameResult = results.getValidatorResult("lastName"); assertNotNull("First Name ValidatorResult should not be null.", firstNameResult); assertTrue("First Name ValidatorResult should contain the '" + ACTION +"' action.", firstNameResult.containsAction(ACTION)); assertTrue("First Name ValidatorResult for the '" + ACTION +"' action should have passed.", firstNameResult.isValid(ACTION)); assertNotNull("Last Name ValidatorResult should not be null.", lastNameResult); assertTrue("Last Name ValidatorResult should contain the '" + ACTION +"' action.", lastNameResult.containsAction(ACTION)); assertTrue("Last Name ValidatorResult for the '" + ACTION +"' action should have passed.", lastNameResult.isValid(ACTION)); } /** * Tests the required validation for last name if it is blank. */ public void testRequiredLastNameBlank() throws ValidatorException { // Create bean to run test on. NameBean name = new NameBean(); name.setFirstName("Joe"); name.setLastName(""); // Construct validator based on the loaded resources // and the form key Validator validator = new Validator(resources, FORM_KEY); // add the name bean to the validator as a resource // for the validations to be performed on. validator.setParameter(Validator.BEAN_PARAM, name); // Get results of the validation. ValidatorResults results = null; results = validator.validate(); assertNotNull("Results are null.", results); ValidatorResult firstNameResult = results.getValidatorResult("firstName"); ValidatorResult lastNameResult = results.getValidatorResult("lastName"); assertNotNull("First Name ValidatorResult should not be null.", firstNameResult); assertTrue("First Name ValidatorResult should contain the '" + ACTION +"' action.", firstNameResult.containsAction(ACTION)); assertTrue("First Name ValidatorResult for the '" + ACTION +"' action should have passed.", firstNameResult.isValid(ACTION)); assertNotNull("Last Name ValidatorResult should not be null.", lastNameResult); assertTrue("Last Name ValidatorResult should contain the '" + ACTION +"' action.", lastNameResult.containsAction(ACTION)); assertTrue("Last Name ValidatorResult for the '" + ACTION +"' action should have failed.", !lastNameResult.isValid(ACTION)); } /** * Tests the required validation for last name. */ public void testRequiredLastName() throws ValidatorException { // Create bean to run test on. NameBean name = new NameBean(); name.setFirstName("Joe"); name.setLastName("Smith"); // Construct validator based on the loaded resources // and the form key Validator validator = new Validator(resources, FORM_KEY); // add the name bean to the validator as a resource // for the validations to be performed on. validator.setParameter(Validator.BEAN_PARAM, name); // Get results of the validation. ValidatorResults results = null; results = validator.validate(); assertNotNull("Results are null.", results); ValidatorResult firstNameResult = results.getValidatorResult("firstName"); ValidatorResult lastNameResult = results.getValidatorResult("lastName"); assertNotNull("First Name ValidatorResult should not be null.", firstNameResult); assertTrue("First Name ValidatorResult should contain the '" + ACTION +"' action.", firstNameResult.containsAction(ACTION)); assertTrue("First Name ValidatorResult for the '" + ACTION +"' action should have passed.", firstNameResult.isValid(ACTION)); assertNotNull("Last Name ValidatorResult should not be null.", lastNameResult); assertTrue("Last Name ValidatorResult should contain the '" + ACTION +"' action.", lastNameResult.containsAction(ACTION)); assertTrue("Last Name ValidatorResult for the '" + ACTION +"' action should have passed.", lastNameResult.isValid(ACTION)); } } commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/RequiredNameTest.java100644 765 0 27255 11711227700 33257 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator; import java.io.IOException; import org.xml.sax.SAXException; /** * Performs Validation Test. * * @version $Revision: 1094751 $ $Date: 2011-04-18 23:17:40 +0200 (Mon, 18 Apr 2011) $ */ public class RequiredNameTest extends AbstractCommonTest { /** * The key used to retrieve the set of validation * rules from the xml file. */ protected static String FORM_KEY = "nameForm"; /** * The key used to retrieve the validator action. */ protected static String ACTION = "required"; public RequiredNameTest(String name) { super(name); } /** * Load ValidatorResources from * validator-name-required.xml. */ protected void setUp() throws IOException, SAXException { // Load resources loadResources("RequiredNameTest-config.xml"); } protected void tearDown() { } /** * Tests the required validation failure. */ public void testRequired() throws ValidatorException { // Create bean to run test on. NameBean name = new NameBean(); // Construct validator based on the loaded resources // and the form key Validator validator = new Validator(resources, FORM_KEY); // add the name bean to the validator as a resource // for the validations to be performed on. validator.setParameter(Validator.BEAN_PARAM, name); // Get results of the validation. ValidatorResults results = null; // throws ValidatorException, // but we aren't catching for testing // since no validation methods we use // throw this results = validator.validate(); assertNotNull("Results are null.", results); ValidatorResult firstNameResult = results.getValidatorResult("firstName"); ValidatorResult lastNameResult = results.getValidatorResult("lastName"); assertNotNull("First Name ValidatorResult should not be null.", firstNameResult); assertTrue("First Name ValidatorResult should contain the '" + ACTION +"' action.", firstNameResult.containsAction(ACTION)); assertTrue("First Name ValidatorResult for the '" + ACTION +"' action should have failed.", !firstNameResult.isValid(ACTION)); assertNotNull("First Name ValidatorResult should not be null.", lastNameResult); assertTrue("Last Name ValidatorResult should contain the '" + ACTION +"' action.", lastNameResult.containsAction(ACTION)); assertTrue("Last Name ValidatorResult for the '" + ACTION +"' action should have failed.", !lastNameResult.isValid(ACTION)); } /** * Tests the required validation for first name if it is blank. */ public void testRequiredFirstNameBlank() throws ValidatorException { // Create bean to run test on. NameBean name = new NameBean(); name.setFirstName(""); // Construct validator based on the loaded resources // and the form key Validator validator = new Validator(resources, FORM_KEY); // add the name bean to the validator as a resource // for the validations to be performed on. validator.setParameter(Validator.BEAN_PARAM, name); // Get results of the validation. ValidatorResults results = null; results = validator.validate(); assertNotNull("Results are null.", results); ValidatorResult firstNameResult = results.getValidatorResult("firstName"); ValidatorResult lastNameResult = results.getValidatorResult("lastName"); assertNotNull("First Name ValidatorResult should not be null.", firstNameResult); assertTrue("First Name ValidatorResult should contain the '" + ACTION +"' action.", firstNameResult.containsAction(ACTION)); assertTrue("First Name ValidatorResult for the '" + ACTION +"' action should have failed.", !firstNameResult.isValid(ACTION)); assertNotNull("First Name ValidatorResult should not be null.", lastNameResult); assertTrue("Last Name ValidatorResult should contain the '" + ACTION +"' action.", lastNameResult.containsAction(ACTION)); assertTrue("Last Name ValidatorResult for the '" + ACTION +"' action should have failed.", !lastNameResult.isValid(ACTION)); } /** * Tests the required validation for first name. */ public void testRequiredFirstName() throws ValidatorException { // Create bean to run test on. NameBean name = new NameBean(); name.setFirstName("Joe"); // Construct validator based on the loaded resources // and the form key Validator validator = new Validator(resources, FORM_KEY); // add the name bean to the validator as a resource // for the validations to be performed on. validator.setParameter(Validator.BEAN_PARAM, name); // Get results of the validation. ValidatorResults results = null; results = validator.validate(); assertNotNull("Results are null.", results); ValidatorResult firstNameResult = results.getValidatorResult("firstName"); ValidatorResult lastNameResult = results.getValidatorResult("lastName"); assertNotNull("First Name ValidatorResult should not be null.", firstNameResult); assertTrue("First Name ValidatorResult should contain the '" + ACTION +"' action.", firstNameResult.containsAction(ACTION)); assertTrue("First Name ValidatorResult for the '" + ACTION +"' action should have passed.", firstNameResult.isValid(ACTION)); assertNotNull("First Name ValidatorResult should not be null.", lastNameResult); assertTrue("Last Name ValidatorResult should contain the '" + ACTION +"' action.", lastNameResult.containsAction(ACTION)); assertTrue("Last Name ValidatorResult for the '" + ACTION +"' action should have failed.", !lastNameResult.isValid(ACTION)); } /** * Tests the required validation for last name if it is blank. */ public void testRequiredLastNameBlank() throws ValidatorException { // Create bean to run test on. NameBean name = new NameBean(); name.setLastName(""); // Construct validator based on the loaded resources // and the form key Validator validator = new Validator(resources, FORM_KEY); // add the name bean to the validator as a resource // for the validations to be performed on. validator.setParameter(Validator.BEAN_PARAM, name); // Get results of the validation. ValidatorResults results = null; results = validator.validate(); assertNotNull("Results are null.", results); ValidatorResult firstNameResult = results.getValidatorResult("firstName"); ValidatorResult lastNameResult = results.getValidatorResult("lastName"); assertNotNull("First Name ValidatorResult should not be null.", firstNameResult); assertTrue("First Name ValidatorResult should contain the '" + ACTION +"' action.", firstNameResult.containsAction(ACTION)); assertTrue("First Name ValidatorResult for the '" + ACTION +"' action should have failed.", !firstNameResult.isValid(ACTION)); assertNotNull("First Name ValidatorResult should not be null.", lastNameResult); assertTrue("Last Name ValidatorResult should contain the '" + ACTION +"' action.", lastNameResult.containsAction(ACTION)); assertTrue("Last Name ValidatorResult for the '" + ACTION +"' action should have failed.", !lastNameResult.isValid(ACTION)); } /** * Tests the required validation for last name. */ public void testRequiredLastName() throws ValidatorException { // Create bean to run test on. NameBean name = new NameBean(); name.setLastName("Smith"); // Construct validator based on the loaded resources // and the form key Validator validator = new Validator(resources, FORM_KEY); // add the name bean to the validator as a resource // for the validations to be performed on. validator.setParameter(Validator.BEAN_PARAM, name); // Get results of the validation. ValidatorResults results = null; results = validator.validate(); assertNotNull("Results are null.", results); ValidatorResult firstNameResult = results.getValidatorResult("firstName"); ValidatorResult lastNameResult = results.getValidatorResult("lastName"); assertNotNull("First Name ValidatorResult should not be null.", firstNameResult); assertTrue("First Name ValidatorResult should contain the '" + ACTION +"' action.", firstNameResult.containsAction(ACTION)); assertTrue("First Name ValidatorResult for the '" + ACTION +"' action should have failed.", !firstNameResult.isValid(ACTION)); assertNotNull("First Name ValidatorResult should not be null.", lastNameResult); assertTrue("Last Name ValidatorResult should contain the '" + ACTION +"' action.", lastNameResult.containsAction(ACTION)); assertTrue("Last Name ValidatorResult for the '" + ACTION +"' action should have passed.", lastNameResult.isValid(ACTION)); } /** * Tests the required validation for first and last name. */ public void testRequiredName() throws ValidatorException { // Create bean to run test on. NameBean name = new NameBean(); name.setFirstName("Joe"); name.setLastName("Smith"); // Construct validator based on the loaded resources // and the form key Validator validator = new Validator(resources, FORM_KEY); // add the name bean to the validator as a resource // for the validations to be performed on. validator.setParameter(Validator.BEAN_PARAM, name); // Get results of the validation. ValidatorResults results = null; results = validator.validate(); assertNotNull("Results are null.", results); ValidatorResult firstNameResult = results.getValidatorResult("firstName"); ValidatorResult lastNameResult = results.getValidatorResult("lastName"); assertNotNull("First Name ValidatorResult should not be null.", firstNameResult); assertTrue("First Name ValidatorResult should contain the '" + ACTION +"' action.", firstNameResult.containsAction(ACTION)); assertTrue("First Name ValidatorResult for the '" + ACTION +"' action should have passed.", firstNameResult.isValid(ACTION)); assertNotNull("First Name ValidatorResult should not be null.", lastNameResult); assertTrue("Last Name ValidatorResult should contain the '" + ACTION +"' action.", lastNameResult.containsAction(ACTION)); assertTrue("Last Name ValidatorResult for the '" + ACTION +"' action should have passed.", lastNameResult.isValid(ACTION)); } } commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/ResultPair.java100644 765 0 2317 11711227700 32100 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator; /** * Groups tests and expected results. * * @version $Revision: 588091 $ $Date: 2007-10-25 02:17:42 +0200 (Thu, 25 Oct 2007) $ */ public class ResultPair { public String item; public boolean valid; public ResultPair(String item, boolean valid) { this.item = item; this.valid = valid; //Weather the individual part of url is valid. } } commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/RetrieveFormTest.java100644 765 0 15227 11711227700 33303 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator; import java.io.IOException; import java.io.InputStream; import java.util.Locale; import junit.framework.TestCase; import org.xml.sax.SAXException; /** * Tests retrieving forms using different Locales. * * @version $Revision: 1094738 $ $Date: 2011-04-18 22:51:21 +0200 (Mon, 18 Apr 2011) $ */ public class RetrieveFormTest extends TestCase { /** * Resources used for validation tests. */ private ValidatorResources resources = null; /** * Prefix for the forms. */ private static final String FORM_PREFIX = "testForm_"; /** * Prefix for the forms. */ private static final Locale CANADA_FRENCH_XXX = new Locale("fr", "CA", "XXX"); /** * Constructor for FormTest. * @param name */ public RetrieveFormTest(String name) { super(name); } /** * Load ValidatorResources from multiple xml files. */ protected void setUp() throws IOException, SAXException { InputStream[] streams = new InputStream[] { this.getClass().getResourceAsStream( "RetrieveFormTest-config.xml")}; this.resources = new ValidatorResources(streams); for (int i = 0; i < streams.length; i++) { streams[i].close(); } } /** * Test a form defined only in the "default" formset. */ public void testDefaultForm() { String formKey = FORM_PREFIX + "default"; // *** US locale *** checkForm(Locale.US, formKey, "default"); // *** French locale *** checkForm(Locale.FRENCH, formKey, "default"); // *** France locale *** checkForm(Locale.FRANCE, formKey, "default"); // *** Candian (English) locale *** checkForm(Locale.CANADA, formKey, "default"); // *** Candian French locale *** checkForm(Locale.CANADA_FRENCH, formKey, "default"); // *** Candian French Variant locale *** checkForm(CANADA_FRENCH_XXX, formKey, "default"); } /** * Test a form defined in the "default" formset and formsets * where just the "language" is specified. */ public void testLanguageForm() { String formKey = FORM_PREFIX + "language"; // *** US locale *** checkForm(Locale.US, formKey, "default"); // *** French locale *** checkForm(Locale.FRENCH, formKey, "fr"); // *** France locale *** checkForm(Locale.FRANCE, formKey, "fr"); // *** Candian (English) locale *** checkForm(Locale.CANADA, formKey, "default"); // *** Candian French locale *** checkForm(Locale.CANADA_FRENCH, formKey, "fr"); // *** Candian French Variant locale *** checkForm(CANADA_FRENCH_XXX, formKey, "fr"); } /** * Test a form defined in the "default" formset, formsets * where just the "language" is specified and formset where * the language and country are specified. */ public void testLanguageCountryForm() { String formKey = FORM_PREFIX + "language_country"; // *** US locale *** checkForm(Locale.US, formKey, "default"); // *** French locale *** checkForm(Locale.FRENCH, formKey, "fr"); // *** France locale *** checkForm(Locale.FRANCE, formKey, "fr_FR"); // *** Candian (English) locale *** checkForm(Locale.CANADA, formKey, "default"); // *** Candian French locale *** checkForm(Locale.CANADA_FRENCH, formKey, "fr_CA"); // *** Candian French Variant locale *** checkForm(CANADA_FRENCH_XXX, formKey, "fr_CA"); } /** * Test a form defined in all the formsets */ public void testLanguageCountryVariantForm() { String formKey = FORM_PREFIX + "language_country_variant"; // *** US locale *** checkForm(Locale.US, formKey, "default"); // *** French locale *** checkForm(Locale.FRENCH, formKey, "fr"); // *** France locale *** checkForm(Locale.FRANCE, formKey, "fr_FR"); // *** Candian (English) locale *** checkForm(Locale.CANADA, formKey, "default"); // *** Candian French locale *** checkForm(Locale.CANADA_FRENCH, formKey, "fr_CA"); // *** Candian French Variant locale *** checkForm(CANADA_FRENCH_XXX, formKey, "fr_CA_XXX"); } /** * Test a form not defined */ public void testFormNotFound() { String formKey = "INVALID_NAME"; // *** US locale *** checkFormNotFound(Locale.US, formKey); // *** French locale *** checkFormNotFound(Locale.FRENCH, formKey); // *** France locale *** checkFormNotFound(Locale.FRANCE, formKey); // *** Candian (English) locale *** checkFormNotFound(Locale.CANADA, formKey); // *** Candian French locale *** checkFormNotFound(Locale.CANADA_FRENCH, formKey); // *** Candian French Variant locale *** checkFormNotFound(CANADA_FRENCH_XXX, formKey); } private void checkForm(Locale locale, String formKey, String expectedVarValue) { // Retrieve the Form Form testForm = resources.getForm(locale, formKey); assertNotNull("Form '" +formKey+"' null for locale " + locale, testForm); // Validate the expected Form is retrieved by checking the "localeVar" // value of the field. Field testField = testForm.getField("testProperty"); assertEquals("Incorrect Form '" + formKey + "' for locale '" + locale + "'", expectedVarValue, testField.getVarValue("localeVar")); } private void checkFormNotFound(Locale locale, String formKey) { // Retrieve the Form Form testForm = resources.getForm(locale, formKey); assertNull("Form '" +formKey+"' not null for locale " + locale, testForm); } } commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/ShortTest.java100644 765 0 4704 11711227700 31747 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator; /** * Performs Validation Test for short validations. * * @version $Revision: 1094751 $ $Date: 2011-04-18 23:17:40 +0200 (Mon, 18 Apr 2011) $ */ public class ShortTest extends AbstractNumberTest { public ShortTest(String name) { super(name); FORM_KEY = "shortForm"; ACTION = "short"; } /** * Tests the short validation. */ public void testShortMin() throws ValidatorException { // Create bean to run test on. ValueBean info = new ValueBean(); info.setValue(new Short(Short.MIN_VALUE).toString()); valueTest(info, true); } /** * Tests the short validation. */ public void testShortMax() throws ValidatorException { // Create bean to run test on. ValueBean info = new ValueBean(); info.setValue(new Short(Short.MAX_VALUE).toString()); valueTest(info, true); } /** * Tests the short validation failure. */ public void testShortBeyondMin() throws ValidatorException { // Create bean to run test on. ValueBean info = new ValueBean(); info.setValue(Short.MIN_VALUE + "1"); valueTest(info, false); } /** * Tests the short validation failure. */ public void testShortBeyondMax() throws ValidatorException { // Create bean to run test on. ValueBean info = new ValueBean(); info.setValue(Short.MAX_VALUE + "1"); valueTest(info, false); } } commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/TypeBean.java100644 765 0 5015 11711227700 31513 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator; /** * Value object that contains different fields to test type conversion * validation. * * @version $Revision: 658832 $ $Date: 2008-05-21 21:57:21 +0200 (Wed, 21 May 2008) $ */ public class TypeBean { private String sByte = null; private String sShort = null; private String sInteger = null; private String sLong = null; private String sFloat = null; private String sDouble = null; private String sDate = null; private String sCreditCard = null; public String getByte() { return sByte; } public void setByte(String sByte) { this.sByte = sByte; } public String getShort() { return sShort; } public void setShort(String sShort) { this.sShort = sShort; } public String getInteger() { return sInteger; } public void setInteger(String sInteger) { this.sInteger = sInteger; } public String getLong() { return sLong; } public void setLong(String sLong) { this.sLong = sLong; } public String getFloat() { return sFloat; } public void setFloat(String sFloat) { this.sFloat = sFloat; } public String getDouble() { return sDouble; } public void setDouble(String sDouble) { this.sDouble = sDouble; } public String getDate() { return sDate; } public void setDate(String sDate) { this.sDate = sDate; } public String getCreditCard() { return sCreditCard; } public void setCreditCard(String sCreditCard) { this.sCreditCard = sCreditCard; } } commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/UrlTest.java100644 765 0 27573 11711227700 31443 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator; import junit.framework.TestCase; /** * Performs Validation Test for url validations. * * @version $Revision: 1094806 $ $Date: 2011-04-19 00:53:09 +0200 (Tue, 19 Apr 2011) $ * @deprecated to be removed when org.apache.commons.validator.UrlValidator is removed */ public class UrlTest extends TestCase { private boolean printStatus = false; private boolean printIndex = false;//print index that indicates current scheme,host,port,path, query test were using. public UrlTest(String testName) { super(testName); } protected void setUp() { for (int index = 0; index < testPartsIndex.length - 1; index++) { testPartsIndex[index] = 0; } } public void testIsValid() { testIsValid(testUrlParts, UrlValidator.ALLOW_ALL_SCHEMES); setUp(); int options = UrlValidator.ALLOW_2_SLASHES + UrlValidator.ALLOW_ALL_SCHEMES + UrlValidator.NO_FRAGMENTS; testIsValid(testUrlPartsOptions, options); } public void testIsValidScheme() { if (printStatus) { System.out.print("\n testIsValidScheme() "); } String[] schemes = {"http", "gopher"}; //UrlValidator urlVal = new UrlValidator(schemes,false,false,false); UrlValidator urlVal = new UrlValidator(schemes, 0); for (int sIndex = 0; sIndex < testScheme.length; sIndex++) { ResultPair testPair = testScheme[sIndex]; boolean result = urlVal.isValidScheme(testPair.item); assertEquals(testPair.item, testPair.valid, result); if (printStatus) { if (result == testPair.valid) { System.out.print('.'); } else { System.out.print('X'); } } } if (printStatus) { System.out.println(); } } /** * Create set of tests by taking the testUrlXXX arrays and * running through all possible permutations of their combinations. * * @param testObjects Used to create a url. */ public void testIsValid(Object[] testObjects, int options) { UrlValidator urlVal = new UrlValidator(null, options); assertTrue(urlVal.isValid("http://www.google.com")); assertTrue(urlVal.isValid("http://www.google.com/")); int statusPerLine = 60; int printed = 0; if (printIndex) { statusPerLine = 6; } do { StringBuffer testBuffer = new StringBuffer(); boolean expected = true; for (int testPartsIndexIndex = 0; testPartsIndexIndex < testPartsIndex.length; ++testPartsIndexIndex) { int index = testPartsIndex[testPartsIndexIndex]; ResultPair[] part = (ResultPair[]) testObjects[testPartsIndexIndex]; testBuffer.append(part[index].item); expected &= part[index].valid; } String url = testBuffer.toString(); boolean result = urlVal.isValid(url); assertEquals(url, expected, result); if (printStatus) { if (printIndex) { System.out.print(testPartsIndextoString()); } else { if (result == expected) { System.out.print('.'); } else { System.out.print('X'); } } printed++; if (printed == statusPerLine) { System.out.println(); printed = 0; } } } while (incrementTestPartsIndex(testPartsIndex, testObjects)); if (printStatus) { System.out.println(); } } public void testValidator202() { String[] schemes = {"http","https"}; UrlValidator urlValidator = new UrlValidator(schemes, UrlValidator.NO_FRAGMENTS); urlValidator.isValid("http://www.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.log"); } public void testValidator204() { String[] schemes = {"http","https"}; UrlValidator urlValidator = new UrlValidator(schemes); assertTrue(urlValidator.isValid("http://tech.yahoo.com/rc/desktops/102;_ylt=Ao8yevQHlZ4On0O3ZJGXLEQFLZA5")); } static boolean incrementTestPartsIndex(int[] testPartsIndex, Object[] testParts) { boolean carry = true; //add 1 to lowest order part. boolean maxIndex = true; for (int testPartsIndexIndex = testPartsIndex.length - 1; testPartsIndexIndex >= 0; --testPartsIndexIndex) { int index = testPartsIndex[testPartsIndexIndex]; ResultPair[] part = (ResultPair[]) testParts[testPartsIndexIndex]; if (carry) { if (index < part.length - 1) { index++; testPartsIndex[testPartsIndexIndex] = index; carry = false; } else { testPartsIndex[testPartsIndexIndex] = 0; carry = true; } } maxIndex &= (index == (part.length - 1)); } return (!maxIndex); } private String testPartsIndextoString() { StringBuffer carryMsg = new StringBuffer("{"); for (int testPartsIndexIndex = 0; testPartsIndexIndex < testPartsIndex.length; ++testPartsIndexIndex) { carryMsg.append(testPartsIndex[testPartsIndexIndex]); if (testPartsIndexIndex < testPartsIndex.length - 1) { carryMsg.append(','); } else { carryMsg.append('}'); } } return carryMsg.toString(); } public void testValidateUrl() { assertTrue(true); } /** * Only used to debug the unit tests. * @param argv */ public static void main(String[] argv) { UrlTest fct = new UrlTest("url test"); fct.setUp(); fct.testIsValid(); fct.testIsValidScheme(); } //-------------------- Test data for creating a composite URL /** * The data given below approximates the 4 parts of a URL * ://? except that the port number * is broken out of authority to increase the number of permutations. * A complete URL is composed of a scheme+authority+port+path+query, * all of which must be individually valid for the entire URL to be considered * valid. */ ResultPair[] testUrlScheme = {new ResultPair("http://", true), new ResultPair("ftp://", true), new ResultPair("h3t://", true), new ResultPair("3ht://", false), new ResultPair("http:/", false), new ResultPair("http:", false), new ResultPair("http/", false), new ResultPair("://", false), new ResultPair("", true)}; ResultPair[] testUrlAuthority = {new ResultPair("www.google.com", true), new ResultPair("go.com", true), new ResultPair("go.au", true), new ResultPair("0.0.0.0", true), new ResultPair("255.255.255.255", true), new ResultPair("256.256.256.256", false), new ResultPair("255.com", true), new ResultPair("1.2.3.4.5", false), new ResultPair("1.2.3.4.", false), new ResultPair("1.2.3", false), new ResultPair(".1.2.3.4", false), new ResultPair("go.a", false), new ResultPair("go.a1a", true), new ResultPair("go.1aa", false), new ResultPair("aaa.", false), new ResultPair(".aaa", false), new ResultPair("aaa", false), new ResultPair("", false) }; ResultPair[] testUrlPort = {new ResultPair(":80", true), new ResultPair(":65535", true), new ResultPair(":0", true), new ResultPair("", true), new ResultPair(":-1", false), new ResultPair(":65636", true), new ResultPair(":65a", false) }; ResultPair[] testPath = {new ResultPair("/test1", true), new ResultPair("/t123", true), new ResultPair("/$23", true), new ResultPair("/..", false), new ResultPair("/../", false), new ResultPair("/test1/", true), new ResultPair("", true), new ResultPair("/test1/file", true), new ResultPair("/..//file", false), new ResultPair("/test1//file", false) }; //Test allow2slash, noFragment ResultPair[] testUrlPathOptions = {new ResultPair("/test1", true), new ResultPair("/t123", true), new ResultPair("/$23", true), new ResultPair("/..", false), new ResultPair("/../", false), new ResultPair("/test1/", true), new ResultPair("/#", false), new ResultPair("", true), new ResultPair("/test1/file", true), new ResultPair("/t123/file", true), new ResultPair("/$23/file", true), new ResultPair("/../file", false), new ResultPair("/..//file", false), new ResultPair("/test1//file", true), new ResultPair("/#/file", false) }; ResultPair[] testUrlQuery = {new ResultPair("?action=view", true), new ResultPair("?action=edit&mode=up", true), new ResultPair("", true) }; Object[] testUrlParts = {testUrlScheme, testUrlAuthority, testUrlPort, testPath, testUrlQuery}; Object[] testUrlPartsOptions = {testUrlScheme, testUrlAuthority, testUrlPort, testUrlPathOptions, testUrlQuery}; int[] testPartsIndex = {0, 0, 0, 0, 0}; //---------------- Test data for individual url parts ---------------- ResultPair[] testScheme = {new ResultPair("http", true), new ResultPair("ftp", false), new ResultPair("httpd", false), new ResultPair("telnet", false)}; } commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/ValidatorResourcesTest.java100644 765 0 3016 11711227700 34463 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator; import java.io.InputStream; import junit.framework.TestCase; /** * Test ValidatorResources. * * @version $Revision: 1094804 $ */ public class ValidatorResourcesTest extends TestCase { /** * Constructor. */ public ValidatorResourcesTest(String name) { super(name); } /** * Test null Input Stream for Validator Resources. */ public void testNullInputStream() throws Exception { try { new ValidatorResources((InputStream)null); fail("Expected IllegalArgumentException"); } catch(IllegalArgumentException e) { // expected result // System.out.println("Exception: " + e); } } } commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/ValidatorResultsTest.java100644 765 0 12127 11711227700 34175 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator; import java.io.IOException; import org.xml.sax.SAXException; /** * Test ValidatorResults. * * @version $Revision: 1094751 $ $Date: 2011-04-18 23:17:40 +0200 (Mon, 18 Apr 2011) $ */ public class ValidatorResultsTest extends AbstractCommonTest { private static final String FORM_KEY = "nameForm"; private static final String firstNameField = "firstName"; private static final String middleNameField = "middleName"; private static final String lastNameField = "lastName"; private String firstName; private String middleName; private String lastName; /** * Constructor. */ public ValidatorResultsTest(String name) { super(name); } /** * Load ValidatorResources from * ValidatorResultsTest-config.xml. */ protected void setUp() throws IOException, SAXException { // Load resources loadResources("ValidatorResultsTest-config.xml"); // initialize values firstName = "foo"; middleName = "123"; lastName = "456"; } protected void tearDown() { } /** * Test all validations ran and passed. */ public void testAllValid() throws ValidatorException { // Create bean to run test on. NameBean bean = createNameBean(); // Validate. ValidatorResults results = validate(bean); // Check results checkValidatorResult(results, firstNameField, "required", true); checkValidatorResult(results, middleNameField, "required", true); checkValidatorResult(results, middleNameField, "int", true); checkValidatorResult(results, middleNameField, "positive", true); checkValidatorResult(results, lastNameField, "required", true); checkValidatorResult(results, lastNameField, "int", true); } /** * Test some validations failed and some didn't run. */ public void testErrors() throws ValidatorException { middleName = "XXX"; lastName = null; // Create bean to run test on. NameBean bean = createNameBean(); // Validate. ValidatorResults results = validate(bean); // Check results checkValidatorResult(results, firstNameField, "required", true); checkValidatorResult(results, middleNameField, "required", true); checkValidatorResult(results, middleNameField, "int", false); checkNotRun(results, middleNameField, "positive"); checkValidatorResult(results, lastNameField, "required", false); checkNotRun(results, lastNameField, "int"); } /** * Check a validator has not been run for a field and the result. */ private void checkNotRun(ValidatorResults results, String field, String action) { ValidatorResult result = results.getValidatorResult(field); assertNotNull(field + " result", result); assertFalse(field + "[" + action + "] run", result.containsAction(action)); // System.out.println(field + "[" + action + "] not run"); } /** * Check a validator has run for a field and the result. */ private void checkValidatorResult(ValidatorResults results, String field, String action, boolean expected) { ValidatorResult result = results.getValidatorResult(field); // System.out.println(field + "[" + action + "]=" + result.isValid(action)); assertNotNull(field + " result", result); assertTrue(field + "[" + action + "] not run", result.containsAction(action)); assertEquals(field + "[" + action + "] result", expected, result.isValid(action)); } /** * Create a NameBean. */ private NameBean createNameBean() { NameBean name = new NameBean(); name.setFirstName(firstName); name.setMiddleName(middleName); name.setLastName(lastName); return name; } /** * Validate results. */ private ValidatorResults validate(Object bean) throws ValidatorException { // Construct validator based on the loaded resources // and the form key Validator validator = new Validator(resources, FORM_KEY); // add the name bean to the validator as a resource // for the validations to be performed on. validator.setParameter(Validator.BEAN_PARAM, bean); // Get results of the validation. ValidatorResults results = validator.validate(); return results; } } commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/ValidatorTest.java100644 765 0 23016 11711227700 32612 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator; import java.text.DateFormat; import java.text.ParseException; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; import junit.framework.TestCase; import org.apache.commons.validator.util.ValidatorUtils; /** * Performs Validation Test. * * @version $Revision: 1094751 $ $Date: 2011-04-18 23:17:40 +0200 (Mon, 18 Apr 2011) $ */ public class ValidatorTest extends TestCase { public ValidatorTest(String name) { super(name); } /** * Verify that one value generates an error and the other passes. The validation * method being tested returns an object (null will be considered an error). */ public void testManualObject() { // property name of the method we are validating String property = "date"; // name of ValidatorAction String action = "date"; ValidatorResources resources = setupDateResources(property, action); TestBean bean = new TestBean(); bean.setDate("2/3/1999"); Validator validator = new Validator(resources, "testForm"); validator.setParameter(Validator.BEAN_PARAM, bean); try { ValidatorResults results = validator.validate(); assertNotNull("Results are null.", results); ValidatorResult result = results.getValidatorResult(property); assertNotNull("Results are null.", results); assertTrue("ValidatorResult does not contain '" + action + "' validator result.", result.containsAction(action)); assertTrue("Validation of the date formatting has failed.", result.isValid(action)); } catch (Exception e) { fail("An exception was thrown while calling Validator.validate()"); } bean.setDate("2/30/1999"); try { ValidatorResults results = validator.validate(); assertNotNull("Results are null.", results); ValidatorResult result = results.getValidatorResult(property); assertNotNull("Results are null.", results); assertTrue("ValidatorResult does not contain '" + action + "' validator result.", result.containsAction(action)); assertTrue("Validation of the date formatting has passed when it should have failed.", !result.isValid(action)); } catch (Exception e) { fail("An exception was thrown while calling Validator.validate()"); } } public void testOnlyReturnErrors() throws ValidatorException { // property name of the method we are validating String property = "date"; // name of ValidatorAction String action = "date"; ValidatorResources resources = setupDateResources(property, action); TestBean bean = new TestBean(); bean.setDate("2/3/1999"); Validator validator = new Validator(resources, "testForm"); validator.setParameter(Validator.BEAN_PARAM, bean); ValidatorResults results = validator.validate(); assertNotNull(results); // Field passed and should be in results assertTrue(results.getPropertyNames().contains(property)); // Field passed but should not be in results validator.setOnlyReturnErrors(true); results = validator.validate(); assertFalse(results.getPropertyNames().contains(property)); } public void testOnlyValidateField() throws ValidatorException { // property name of the method we are validating String property = "date"; // name of ValidatorAction String action = "date"; ValidatorResources resources = setupDateResources(property, action); TestBean bean = new TestBean(); bean.setDate("2/3/1999"); Validator validator = new Validator(resources, "testForm", property); validator.setParameter(Validator.BEAN_PARAM, bean); ValidatorResults results = validator.validate(); assertNotNull(results); // Field passed and should be in results assertTrue(results.getPropertyNames().contains(property)); } private ValidatorResources setupDateResources(String property, String action) { ValidatorResources resources = new ValidatorResources(); ValidatorAction va = new ValidatorAction(); va.setName(action); va.setClassname("org.apache.commons.validator.ValidatorTest"); va.setMethod("formatDate"); va.setMethodParams("java.lang.Object,org.apache.commons.validator.Field"); FormSet fs = new FormSet(); Form form = new Form(); form.setName("testForm"); Field field = new Field(); field.setProperty(property); field.setDepends(action); form.addField(field); fs.addForm(form); resources.addValidatorAction(va); resources.addFormSet(fs); resources.process(); return resources; } /** * Verify that one value generates an error and the other passes. The validation * method being tested returns a boolean value. */ public void testManualBoolean() { ValidatorResources resources = new ValidatorResources(); ValidatorAction va = new ValidatorAction(); va.setName("capLetter"); va.setClassname("org.apache.commons.validator.ValidatorTest"); va.setMethod("isCapLetter"); va.setMethodParams("java.lang.Object,org.apache.commons.validator.Field,java.util.List"); FormSet fs = new FormSet(); Form form = new Form(); form.setName("testForm"); Field field = new Field(); field.setProperty("letter"); field.setDepends("capLetter"); form.addField(field); fs.addForm(form); resources.addValidatorAction(va); resources.addFormSet(fs); resources.process(); List l = new ArrayList(); TestBean bean = new TestBean(); bean.setLetter("A"); Validator validator = new Validator(resources, "testForm"); validator.setParameter(Validator.BEAN_PARAM, bean); validator.setParameter("java.util.List", l); try { validator.validate(); } catch (Exception e) { fail("An exception was thrown while calling Validator.validate()"); } assertEquals("Validation of the letter 'A'.", 0, l.size()); l.clear(); bean.setLetter("AA"); try { validator.validate(); } catch (Exception e) { fail("An exception was thrown while calling Validator.validate()"); } assertEquals("Validation of the letter 'AA'.", 1, l.size()); } /** * Checks if the field is one upper case letter between 'A' and 'Z'. */ public static boolean isCapLetter(Object bean, Field field, List l) { String value = ValidatorUtils.getValueAsString(bean, field.getProperty()); if (value != null && value.length() == 1) { if (value.charAt(0) >= 'A' && value.charAt(0) <= 'Z') { return true; } else { l.add("Error"); return false; } } else { l.add("Error"); return false; } } /** * Formats a String to a Date. * The Validator will interpret a null * as validation having failed. */ public static Date formatDate(Object bean, Field field) { String value = ValidatorUtils.getValueAsString(bean, field.getProperty()); Date date = null; try { DateFormat formatter = null; formatter = DateFormat.getDateInstance(DateFormat.SHORT, Locale.US); formatter.setLenient(false); date = formatter.parse(value); } catch (ParseException e) { System.out.println("ValidatorTest.formatDate() - " + e.getMessage()); } return date; } public class TestBean { private String letter = null; private String date = null; public String getLetter() { return letter; } public void setLetter(String letter) { this.letter = letter; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } } } commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/ValueBean.java100644 765 0 2543 11711227700 31651 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator; /** * Value object for storing a value to run tests on. * * @version $Revision: 658832 $ $Date: 2008-05-21 21:57:21 +0200 (Wed, 21 May 2008) $ */ public class ValueBean { protected String value = null; /** * Gets the value. */ public String getValue() { return value; } /** * Sets the value. */ public void setValue(String value) { this.value = value; } } commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/VarTest.java100644 765 0 7533 11711227700 31403 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator; import java.io.IOException; import java.util.Locale; import org.xml.sax.SAXException; /** * Test that the new Var attributes and the * digester rule changes work. * * @version $Revision: 1094808 $ $Date: 2011-04-19 00:57:51 +0200 (Tue, 19 Apr 2011) $ */ public class VarTest extends AbstractCommonTest { /** * The key used to retrieve the set of validation * rules from the xml file. */ protected static String FORM_KEY = "testForm"; /** * The key used to retrieve the validator action. */ protected static String ACTION = "byte"; public VarTest(String name) { super(name); } /** * Load ValidatorResources from * validator-multipletest.xml. */ protected void setUp() throws IOException, SAXException { // Load resources loadResources("VarTest-config.xml"); } protected void tearDown() { } /** * With nothing provided, we should fail both because both are required. */ public void testVars() { Form form = resources.getForm(Locale.getDefault(), FORM_KEY); // Get field 1 Field field1 = form.getField("field-1"); assertNotNull("field-1 is null.", field1); assertEquals("field-1 property is wrong", "field-1", field1.getProperty()); // Get var-1-1 Var var11 = field1.getVar("var-1-1"); assertNotNull("var-1-1 is null.", var11); assertEquals("var-1-1 name is wrong", "var-1-1", var11.getName()); assertEquals("var-1-1 value is wrong", "value-1-1", var11.getValue()); assertEquals("var-1-1 jstype is wrong", "jstype-1-1", var11.getJsType()); assertFalse("var-1-1 resource is true", var11.isResource()); assertNull("var-1-1 bundle is not null.", var11.getBundle()); // Get field 2 Field field2 = form.getField("field-2"); assertNotNull("field-2 is null.", field2); assertEquals("field-2 property is wrong", "field-2", field2.getProperty()); // Get var-2-1 Var var21 = field2.getVar("var-2-1"); assertNotNull("var-2-1 is null.", var21); assertEquals("var-2-1 name is wrong", "var-2-1", var21.getName()); assertEquals("var-2-1 value is wrong", "value-2-1", var21.getValue()); assertEquals("var-2-1 jstype is wrong", "jstype-2-1", var21.getJsType()); assertTrue("var-2-1 resource is false", var21.isResource()); assertEquals("var-2-1 bundle is wrong", "bundle-2-1", var21.getBundle()); // Get var-2-2 Var var22 = field2.getVar("var-2-2"); assertNotNull("var-2-2 is null.", var22); assertEquals("var-2-2 name is wrong", "var-2-2", var22.getName()); assertEquals("var-2-2 value is wrong", "value-2-2", var22.getValue()); assertNull("var-2-2 jstype is not null", var22.getJsType()); assertFalse("var-2-2 resource is true", var22.isResource()); assertEquals("var-2-2 bundle is wrong", "bundle-2-2", var22.getBundle()); } } ././@LongLink100644 0 0 154 11711231552 10251 Lustar 0 0 commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/custom/CustomValidatorResources.javacommons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/custom/CustomValidatorResourc100644 765 0 3235 11711227700 35063 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.custom; import java.io.InputStream; import java.io.IOException; import org.xml.sax.SAXException; import org.apache.commons.validator.ValidatorResources; /** * Custom ValidatorResources implementation. * * @version $Revision: 493905 $ $Date: 2007-01-08 03:11:38 +0100 (Mon, 08 Jan 2007) $ */ public class CustomValidatorResources extends ValidatorResources { /** * Create a custom ValidatorResources object from an uri * * @param in InputStream for the validation.xml configuration file. * @throws SAXException if the validation XML files are not valid or well formed. * @throws IOException if an I/O error occurs processing the XML files */ public CustomValidatorResources(InputStream in) throws IOException, SAXException { super(in); } }././@LongLink100644 0 0 163 11711231552 10251 Lustar 0 0 commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/routines/AbstractCalendarValidatorTest.javacommons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/routines/AbstractCalendarVali100644 765 0 23603 11711227700 34770 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines; import junit.framework.TestCase; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Date; import java.util.Calendar; import java.util.Locale; import java.util.TimeZone; /** * Base Calendar Test Case. * * @version $Revision: 909006 $ $Date: 2010-02-11 15:46:51 +0100 (Thu, 11 Feb 2010) $ */ public abstract class AbstractCalendarValidatorTest extends TestCase { protected AbstractCalendarValidator validator; protected static final TimeZone GMT = TimeZone.getTimeZone("GMT"); // 0 offset protected static final TimeZone EST = TimeZone.getTimeZone("EST"); // - 5 hours protected static final TimeZone EET = TimeZone.getTimeZone("EET"); // + 2 hours protected static final TimeZone UTC = TimeZone.getTimeZone("UTC"); // + 2 hours protected String[] patternValid = new String[] { "2005-01-01" ,"2005-12-31" ,"2004-02-29" // valid leap ,"2005-04-30" ,"05-12-31" ,"2005-1-1" ,"05-1-1"}; protected String[] localeValid = new String[] { "01/01/2005" ,"12/31/2005" ,"02/29/2004" // valid leap ,"04/30/2005" ,"12/31/05" ,"1/1/2005" ,"1/1/05"}; protected Date[] patternExpect = new Date[] { createDate(null, 20050101, 0) ,createDate(null, 20051231, 0) ,createDate(null, 20040229, 0) ,createDate(null, 20050430, 0) ,createDate(null, 20051231, 0) ,createDate(null, 20050101, 0) ,createDate(null, 20050101, 0)}; protected String[] patternInvalid = new String[] { "2005-00-01" // zero month ,"2005-01-00" // zero day ,"2005-13-03" // month invalid ,"2005-04-31" // invalid day ,"2005-03-32" // invalid day ,"2005-02-29" // invalid leap ,"200X-01-01" // invalid char ,"2005-0X-01" // invalid char ,"2005-01-0X" // invalid char ,"01/01/2005" // invalid pattern ,"2005-01" // invalid pattern ,"2005--01" // invalid pattern ,"2005-01-"}; // invalid pattern protected String[] localeInvalid = new String[] { "01/00/2005" // zero month ,"00/01/2005" // zero day ,"13/01/2005" // month invalid ,"04/31/2005" // invalid day ,"03/32/2005" // invalid day ,"02/29/2005" // invalid leap ,"01/01/200X" // invalid char ,"01/0X/2005" // invalid char ,"0X/01/2005" // invalid char ,"01-01-2005" // invalid pattern ,"01/2005" // invalid pattern // -------- ,"/01/2005" ---- passes on some JDK ,"01//2005"}; // invalid pattern /** * Constructor * @param name test name */ public AbstractCalendarValidatorTest(String name) { super(name); } /** * Set Up. * @throws Exception */ protected void setUp() throws Exception { super.setUp(); } /** * Tear down * @throws Exception */ protected void tearDown() throws Exception { super.tearDown(); validator = null; } /** * Test Valid Dates with "pattern" validation */ public void testPatternValid() { for (int i = 0; i < patternValid.length; i++) { String text = i + " value=[" +patternValid[i]+"] failed "; Object date = validator.parse(patternValid[i], "yy-MM-dd", null, null); assertNotNull("validateObj() " + text + date, date); assertTrue("isValid() " + text, validator.isValid(patternValid[i], "yy-MM-dd")); if (date instanceof Calendar) { date = ((Calendar)date).getTime(); } assertEquals("compare " + text, patternExpect[i], date); } } /** * Test Invalid Dates with "pattern" validation */ public void testPatternInvalid() { for (int i = 0; i < patternInvalid.length; i++) { String text = i + " value=[" +patternInvalid[i]+"] passed "; Object date = validator.parse(patternInvalid[i], "yy-MM-dd", null, null); assertNull("validateObj() " + text + date, date); assertFalse("isValid() " + text, validator.isValid(patternInvalid[i], "yy-MM-dd")); } } /** * Test Valid Dates with "locale" validation */ public void testLocaleValid() { for (int i = 0; i < localeValid.length; i++) { String text = i + " value=[" +localeValid[i]+"] failed "; Object date = validator.parse(localeValid[i], null, Locale.US, null); assertNotNull("validateObj() " + text + date, date); assertTrue("isValid() " + text, validator.isValid(localeValid[i], Locale.US)); if (date instanceof Calendar) { date = ((Calendar)date).getTime(); } assertEquals("compare " + text, patternExpect[i], date); } } /** * Test Invalid Dates with "locale" validation */ public void testLocaleInvalid() { for (int i = 0; i < localeInvalid.length; i++) { String text = i + " value=[" +localeInvalid[i]+"] passed "; Object date = validator.parse(localeInvalid[i], null, Locale.US, null); assertNull("validateObj() " + text + date, date); assertFalse("isValid() " + text, validator.isValid(localeInvalid[i], Locale.US)); } } /** * Test Invalid Dates with "locale" validation */ public void testFormat() { // Create a Date or Calendar Object test = validator.parse("2005-11-28", "yyyy-MM-dd", null, null); assertNotNull("Test Date ", test); assertEquals("Format pattern", "28.11.05", validator.format(test, "dd.MM.yy")); assertEquals("Format locale", "11/28/05", validator.format(test, Locale.US)); } /** * Test validator serialization. */ public void testSerialization() { // Serialize the check digit routine ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(validator); oos.flush(); oos.close(); } catch (Exception e) { fail(validator.getClass().getName() + " error during serialization: " + e); } // Deserialize the test object Object result = null; try { ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bais); result = ois.readObject(); bais.close(); } catch (Exception e) { fail(validator.getClass().getName() + " error during deserialization: " + e); } assertNotNull(result); } /** * Create a calendar instance for a specified time zone, date and time. * * @param zone The time zone * @param date The date in yyyyMMdd format * @param time the time in HH:mm:ss format * @return the new Calendar instance. */ protected static Calendar createCalendar(TimeZone zone, int date, int time) { Calendar calendar = zone == null ? Calendar.getInstance() : Calendar.getInstance(zone); int year = ((date / 10000) * 10000); int mth = ((date / 100) * 100) - year; int day = date - (year + mth); int hour = ((time / 10000) * 10000); int min = ((time / 100) * 100) - hour; int sec = time - (hour + min); calendar.set(Calendar.YEAR, (year / 10000)); calendar.set(Calendar.MONTH, ((mth / 100) - 1)); calendar.set(Calendar.DATE, day); calendar.set(Calendar.HOUR_OF_DAY, (hour / 10000)); calendar.set(Calendar.MINUTE, (min / 100)); calendar.set(Calendar.SECOND, sec); calendar.set(Calendar.MILLISECOND, 0); return calendar; } /** * Create a date instance for a specified time zone, date and time. * * @param zone The time zone * @param date The date in yyyyMMdd format * @param time the time in HH:mm:ss format * @return the new Date instance. */ protected static Date createDate(TimeZone zone, int date, int time) { Calendar calendar = createCalendar(zone, date, time); return calendar.getTime(); } } ././@LongLink100644 0 0 161 11711231552 10247 Lustar 0 0 commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/routines/AbstractNumberValidatorTest.javacommons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/routines/AbstractNumberValida100644 765 0 22675 11711227700 35024 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines; import junit.framework.TestCase; import java.util.Locale; import java.text.DecimalFormat; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.math.BigDecimal; /** * Base Number Test Case. * * @version $Revision: 909006 $ $Date: 2010-02-11 15:46:51 +0100 (Thu, 11 Feb 2010) $ */ public abstract class AbstractNumberValidatorTest extends TestCase { protected AbstractNumberValidator validator; protected AbstractNumberValidator strictValidator; protected Number max; protected Number maxPlusOne; protected Number min; protected Number minMinusOne; protected String[] invalid; protected String[] valid; protected Number[] validCompare; protected String[] invalidStrict; protected String[] validStrict; protected Number[] validStrictCompare; protected String testPattern; protected Number testNumber; protected Number testZero; protected String testStringUS; protected String testStringDE; protected String localeValue; protected String localePattern; protected Locale testLocale; protected Number localeExpected; /** * Constructor * @param name test name */ public AbstractNumberValidatorTest(String name) { super(name); } protected void setUp() throws Exception { super.setUp(); Locale.setDefault(Locale.US); } /** * Tear down * @throws Exception */ protected void tearDown() throws Exception { super.tearDown(); validator = null; strictValidator = null; } /** * Test Format Type */ public void testFormatType() { assertEquals("Format Type A", 0, validator.getFormatType()); assertEquals("Format Type B", AbstractNumberValidator.STANDARD_FORMAT, validator.getFormatType()); } /** * Test Min/Max values allowed */ public void testValidateMinMax() { DecimalFormat fmt = new DecimalFormat("#"); if (max != null) { assertEquals("Test Max", max, validator.parse(fmt.format(max), "#", null)); assertNull("Test Max + 1", validator.parse(fmt.format(maxPlusOne), "#", null)); assertEquals("Test Min", min, validator.parse(fmt.format(min), "#", null)); assertNull("Test min - 1", validator.parse(fmt.format(minMinusOne), "#", null)); } } /** * Test Invalid, strict=true */ public void testInvalidStrict() { for (int i = 0; i < invalidStrict.length; i++) { String text = "idx=["+i+"] value=[" + invalidStrict[i] + "]"; assertNull("(A) " + text, strictValidator.parse(invalidStrict[i], null, Locale.US)); assertFalse("(B) " + text, strictValidator.isValid(invalidStrict[i], null, Locale.US)); assertNull("(C) " + text, strictValidator.parse(invalidStrict[i], testPattern, null)); assertFalse("(D) " + text, strictValidator.isValid(invalidStrict[i], testPattern, null)); } } /** * Test Invalid, strict=false */ public void testInvalidNotStrict() { for (int i = 0; i < invalid.length; i++) { String text = "idx=["+i+"] value=[" + invalid[i] + "]"; assertNull("(A) " + text, validator.parse(invalid[i], null, Locale.US)); assertFalse("(B) " + text, validator.isValid(invalid[i], null, Locale.US)); assertNull("(C) " + text, validator.parse(invalid[i], testPattern, null)); assertFalse("(D) " + text, validator.isValid(invalid[i], testPattern, null)); } } /** * Test Valid, strict=true */ public void testValidStrict() { for (int i = 0; i < validStrict.length; i++) { String text = "idx=["+i+"] value=[" + validStrictCompare[i] + "]"; assertEquals("(A) " + text, validStrictCompare[i], strictValidator.parse(validStrict[i], null, Locale.US)); assertTrue("(B) " + text, strictValidator.isValid(validStrict[i], null, Locale.US)); assertEquals("(C) " + text, validStrictCompare[i], strictValidator.parse(validStrict[i], testPattern, null)); assertTrue("(D) " + text, strictValidator.isValid(validStrict[i], testPattern, null)); } } /** * Test Valid, strict=false */ public void testValidNotStrict() { for (int i = 0; i < valid.length; i++) { String text = "idx=["+i+"] value=[" + validCompare[i] + "]"; assertEquals("(A) " + text, validCompare[i], validator.parse(valid[i], null, Locale.US)); assertTrue("(B) " + text, validator.isValid(valid[i], null, Locale.US)); assertEquals("(C) " + text, validCompare[i], validator.parse(valid[i], testPattern, null)); assertTrue("(D) " + text, validator.isValid(valid[i], testPattern, null)); } } /** * Test different Locale */ public void testValidateLocale() { assertEquals("US Locale, US Format", testNumber, strictValidator.parse(testStringUS, null, Locale.US)); assertNull("US Locale, DE Format", strictValidator.parse(testStringDE, null, Locale.US)); // Default German Locale assertEquals("DE Locale, DE Format", testNumber, strictValidator.parse(testStringDE, null, Locale.GERMAN)); assertNull("DE Locale, US Format", strictValidator.parse(testStringUS, null, Locale.GERMAN)); // Default Locale has been set to Locale.US in setup() assertEquals("Default Locale, US Format", testNumber, strictValidator.parse(testStringUS, null, null)); assertNull("Default Locale, DE Format", strictValidator.parse(testStringDE, null, null)); } /** * Test format() methods */ public void testFormat() { Number number = new BigDecimal("1234.5"); assertEquals("US Locale, US Format", "1,234.5", strictValidator.format(number, Locale.US)); assertEquals("DE Locale, DE Format", "1.234,5", strictValidator.format(number, Locale.GERMAN)); assertEquals("Pattern #,#0.00", "12,34.50", strictValidator.format(number, "#,#0.00")); } /** * Test Range/Min/Max */ public void testRangeMinMax() { Number number9 = new Integer(9); Number number10 = new Integer(10); Number number11 = new Integer(11); Number number19 = new Integer(19); Number number20 = new Integer(20); Number number21 = new Integer(21); // Test isInRange() assertFalse("isInRange() < min", strictValidator.isInRange(number9 , number10, number20)); assertTrue("isInRange() = min", strictValidator.isInRange(number10 , number10, number20)); assertTrue("isInRange() in range", strictValidator.isInRange(number11 , number10, number20)); assertTrue("isInRange() = max", strictValidator.isInRange(number20 , number10, number20)); assertFalse("isInRange() > max", strictValidator.isInRange(number21 , number10, number20)); // Test minValue() assertFalse("minValue() < min", strictValidator.minValue(number9 , number10)); assertTrue("minValue() = min", strictValidator.minValue(number10 , number10)); assertTrue("minValue() > min", strictValidator.minValue(number11 , number10)); // Test minValue() assertTrue("maxValue() < max", strictValidator.maxValue(number19 , number20)); assertTrue("maxValue() = max", strictValidator.maxValue(number20 , number20)); assertFalse("maxValue() > max", strictValidator.maxValue(number21 , number20)); } /** * Test validator serialization. */ public void testSerialization() { // Serialize the check digit routine ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(validator); oos.flush(); oos.close(); } catch (Exception e) { fail(validator.getClass().getName() + " error during serialization: " + e); } // Deserialize the test object Object result = null; try { ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bais); result = ois.readObject(); bais.close(); } catch (Exception e) { fail(validator.getClass().getName() + " error during deserialization: " + e); } assertNotNull(result); } } ././@LongLink100644 0 0 155 11711231552 10252 Lustar 0 0 commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/routines/BigDecimalValidatorTest.javacommons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/routines/BigDecimalValidatorT100644 765 0 14623 11711227700 34733 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines; import java.math.BigDecimal; import java.util.Locale; /** * Test Case for BigDecimalValidator. * * @version $Revision: 1094808 $ $Date: 2011-04-19 00:57:51 +0200 (Tue, 19 Apr 2011) $ */ public class BigDecimalValidatorTest extends AbstractNumberValidatorTest { /** * Constructor * @param name test name */ public BigDecimalValidatorTest(String name) { super(name); } protected void setUp() throws Exception { super.setUp(); validator = new BigDecimalValidator(false); strictValidator = new BigDecimalValidator(); testPattern = "#,###.###"; // testValidateMinMax() max = null; maxPlusOne = null; min = null; minMinusOne = null; // testInvalidStrict() invalidStrict = new String[] {null, "", "X", "X12", "12X", "1X2", "1.234X"}; // testInvalidNotStrict() invalid = new String[] {null, "", "X", "X12"}; // testValid() testNumber = new BigDecimal("1234.5"); Number testNumber2 = new BigDecimal(".1"); Number testNumber3 = new BigDecimal("12345.67899"); testZero = new BigDecimal("0"); validStrict = new String[] {"0", "1234.5", "1,234.5", ".1", "12345.678990"}; validStrictCompare = new Number[] {testZero, testNumber, testNumber, testNumber2, testNumber3}; valid = new String[] {"0", "1234.5", "1,234.5", "1,234.5", "1234.5X"}; validCompare = new Number[] {testZero, testNumber, testNumber, testNumber, testNumber}; testStringUS = "1,234.5"; testStringDE = "1.234,5"; // Localized Pattern test localeValue = testStringDE; localePattern = "#.###,#"; testLocale = Locale.GERMANY; localeExpected = testNumber; } /** * Test BigDecimalValidator validate Methods */ public void testBigDecimalValidatorMethods() { Locale locale = Locale.GERMAN; String pattern = "0,00,00"; String patternVal = "1,23,45"; String germanPatternVal = "1.23.45"; String localeVal = "12.345"; String defaultVal = "12,345"; String XXXX = "XXXX"; BigDecimal expected = new BigDecimal(12345); assertEquals("validate(A) default", expected, BigDecimalValidator.getInstance().validate(defaultVal)); assertEquals("validate(A) locale ", expected, BigDecimalValidator.getInstance().validate(localeVal, locale)); assertEquals("validate(A) pattern", expected, BigDecimalValidator.getInstance().validate(patternVal, pattern)); assertEquals("validate(A) both", expected, BigDecimalValidator.getInstance().validate(germanPatternVal, pattern, Locale.GERMAN)); assertTrue("isValid(A) default", BigDecimalValidator.getInstance().isValid(defaultVal)); assertTrue("isValid(A) locale ", BigDecimalValidator.getInstance().isValid(localeVal, locale)); assertTrue("isValid(A) pattern", BigDecimalValidator.getInstance().isValid(patternVal, pattern)); assertTrue("isValid(A) both", BigDecimalValidator.getInstance().isValid(germanPatternVal, pattern, Locale.GERMAN)); assertNull("validate(B) default", BigDecimalValidator.getInstance().validate(XXXX)); assertNull("validate(B) locale ", BigDecimalValidator.getInstance().validate(XXXX, locale)); assertNull("validate(B) pattern", BigDecimalValidator.getInstance().validate(XXXX, pattern)); assertNull("validate(B) both", BigDecimalValidator.getInstance().validate(patternVal, pattern, Locale.GERMAN)); assertFalse("isValid(B) default", BigDecimalValidator.getInstance().isValid(XXXX)); assertFalse("isValid(B) locale ", BigDecimalValidator.getInstance().isValid(XXXX, locale)); assertFalse("isValid(B) pattern", BigDecimalValidator.getInstance().isValid(XXXX, pattern)); assertFalse("isValid(B) both", BigDecimalValidator.getInstance().isValid(patternVal, pattern, Locale.GERMAN)); } /** * Test BigDecimal Range/Min/Max */ public void testBigDecimalRangeMinMax() { BigDecimalValidator validator = new BigDecimalValidator(true, AbstractNumberValidator.STANDARD_FORMAT, true); BigDecimal number9 = new BigDecimal("9"); BigDecimal number10 = new BigDecimal("10"); BigDecimal number11 = new BigDecimal("11"); BigDecimal number19 = new BigDecimal("19"); BigDecimal number20 = new BigDecimal("20"); BigDecimal number21 = new BigDecimal("21"); float min = 10; float max = 20; // Test isInRange() assertFalse("isInRange(A) < min", validator.isInRange(number9, min, max)); assertTrue("isInRange(A) = min", validator.isInRange(number10, min, max)); assertTrue("isInRange(A) in range", validator.isInRange(number11, min, max)); assertTrue("isInRange(A) = max", validator.isInRange(number20, min, max)); assertFalse("isInRange(A) > max", validator.isInRange(number21, min, max)); // Test minValue() assertFalse("minValue(A) < min", validator.minValue(number9, min)); assertTrue("minValue(A) = min", validator.minValue(number10, min)); assertTrue("minValue(A) > min", validator.minValue(number11, min)); // Test minValue() assertTrue("maxValue(A) < max", validator.maxValue(number19, max)); assertTrue("maxValue(A) = max", validator.maxValue(number20, max)); assertFalse("maxValue(A) > max", validator.maxValue(number21, max)); } } ././@LongLink100644 0 0 155 11711231552 10252 Lustar 0 0 commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/routines/BigIntegerValidatorTest.javacommons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/routines/BigIntegerValidatorT100644 765 0 14164 11711227700 34772 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines; import java.math.BigInteger; import java.util.Locale; /** * Test Case for BigIntegerValidator. * * @version $Revision: 1094751 $ $Date: 2011-04-18 23:17:40 +0200 (Mon, 18 Apr 2011) $ */ public class BigIntegerValidatorTest extends AbstractNumberValidatorTest { /** * Constructor * @param name test name */ public BigIntegerValidatorTest(String name) { super(name); } protected void setUp() throws Exception { super.setUp(); validator = new BigIntegerValidator(false, 0); strictValidator = new BigIntegerValidator(); testPattern = "#,###"; // testValidateMinMax() max = null; maxPlusOne = null; min = null; minMinusOne = null; // testInvalidStrict() invalidStrict = new String[] {null, "", "X", "X12", "12X", "1X2", "1.2"}; // testInvalidNotStrict() invalid = new String[] {null, "", "X", "X12"}; // testValid() testNumber = new BigInteger("1234"); testZero = new BigInteger("0"); validStrict = new String[] {"0", "1234", "1,234"}; validStrictCompare = new Number[] {testZero, testNumber, testNumber}; valid = new String[] {"0", "1234", "1,234", "1,234.5", "1234X"}; validCompare = new Number[] {testZero, testNumber, testNumber, testNumber, testNumber}; testStringUS = "1,234"; testStringDE = "1.234"; // Localized Pattern test localeValue = testStringDE; localePattern = "#.###"; testLocale = Locale.GERMANY; localeExpected = testNumber; } /** * Test BigIntegerValidator validate Methods */ public void testBigIntegerValidatorMethods() { Locale locale = Locale.GERMAN; String pattern = "0,00,00"; String patternVal = "1,23,45"; String germanPatternVal = "1.23.45"; String localeVal = "12.345"; String defaultVal = "12,345"; String XXXX = "XXXX"; BigInteger expected = new BigInteger("12345"); assertEquals("validate(A) default", expected, BigIntegerValidator.getInstance().validate(defaultVal)); assertEquals("validate(A) locale ", expected, BigIntegerValidator.getInstance().validate(localeVal, locale)); assertEquals("validate(A) pattern", expected, BigIntegerValidator.getInstance().validate(patternVal, pattern)); assertEquals("validate(A) both", expected, BigIntegerValidator.getInstance().validate(germanPatternVal, pattern, Locale.GERMAN)); assertTrue("isValid(A) default", BigIntegerValidator.getInstance().isValid(defaultVal)); assertTrue("isValid(A) locale ", BigIntegerValidator.getInstance().isValid(localeVal, locale)); assertTrue("isValid(A) pattern", BigIntegerValidator.getInstance().isValid(patternVal, pattern)); assertTrue("isValid(A) both", BigIntegerValidator.getInstance().isValid(germanPatternVal, pattern, Locale.GERMAN)); assertNull("validate(B) default", BigIntegerValidator.getInstance().validate(XXXX)); assertNull("validate(B) locale ", BigIntegerValidator.getInstance().validate(XXXX, locale)); assertNull("validate(B) pattern", BigIntegerValidator.getInstance().validate(XXXX, pattern)); assertNull("validate(B) both", BigIntegerValidator.getInstance().validate(patternVal, pattern, Locale.GERMAN)); assertFalse("isValid(B) default", BigIntegerValidator.getInstance().isValid(XXXX)); assertFalse("isValid(B) locale ", BigIntegerValidator.getInstance().isValid(XXXX, locale)); assertFalse("isValid(B) pattern", BigIntegerValidator.getInstance().isValid(XXXX, pattern)); assertFalse("isValid(B) both", BigIntegerValidator.getInstance().isValid(patternVal, pattern, Locale.GERMAN)); } /** * Test BigInteger Range/Min/Max */ public void testBigIntegerRangeMinMax() { BigIntegerValidator validator = (BigIntegerValidator)strictValidator; BigInteger number9 = validator.validate("9", "#"); BigInteger number10 = validator.validate("10", "#"); BigInteger number11 = validator.validate("11", "#"); BigInteger number19 = validator.validate("19", "#"); BigInteger number20 = validator.validate("20", "#"); BigInteger number21 = validator.validate("21", "#"); // Test isInRange() assertFalse("isInRange() < min", validator.isInRange(number9, 10, 20)); assertTrue("isInRange() = min", validator.isInRange(number10, 10, 20)); assertTrue("isInRange() in range", validator.isInRange(number11, 10, 20)); assertTrue("isInRange() = max", validator.isInRange(number20, 10, 20)); assertFalse("isInRange() > max", validator.isInRange(number21, 10, 20)); // Test minValue() assertFalse("minValue() < min", validator.minValue(number9, 10)); assertTrue("minValue() = min", validator.minValue(number10, 10)); assertTrue("minValue() > min", validator.minValue(number11, 10)); // Test minValue() assertTrue("maxValue() < max", validator.maxValue(number19, 20)); assertTrue("maxValue() = max", validator.maxValue(number20, 20)); assertFalse("maxValue() > max", validator.maxValue(number21, 20)); } } ././@LongLink100644 0 0 147 11711231552 10253 Lustar 0 0 commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/routines/ByteValidatorTest.javacommons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/routines/ByteValidatorTest.ja100644 765 0 14020 11711227700 34752 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines; import java.util.Locale; /** * Test Case for ByteValidator. * * @version $Revision: 1094751 $ $Date: 2011-04-18 23:17:40 +0200 (Mon, 18 Apr 2011) $ */ public class ByteValidatorTest extends AbstractNumberValidatorTest { /** * Constructor * @param name test name */ public ByteValidatorTest(String name) { super(name); } protected void setUp() throws Exception { super.setUp(); validator = new ByteValidator(false, 0); strictValidator = new ByteValidator(); testPattern = "#,###"; // testValidateMinMax() max = new Byte(Byte.MAX_VALUE); maxPlusOne = new Long(max.longValue() + 1); min = new Byte(Byte.MIN_VALUE); minMinusOne = new Long(min.longValue() - 1); // testInvalidStrict() invalidStrict = new String[] {null, "", "X", "X12", "12X", "1X2", "1.2"}; // testInvalidNotStrict() invalid = new String[] {null, "", "X", "X12"}; // testValid() testNumber = new Byte((byte)123); testZero = new Byte((byte)0); validStrict = new String[] {"0", "123", ",123"}; validStrictCompare = new Number[] {testZero, testNumber, testNumber}; valid = new String[] {"0", "123", ",123", ",123.5", "123X"}; validCompare = new Number[] {testZero, testNumber, testNumber, testNumber, testNumber}; testStringUS = ",123"; testStringDE = ".123"; // Localized Pattern test localeValue = testStringDE; localePattern = "#.###"; testLocale = Locale.GERMANY; localeExpected = testNumber; } /** * Test ByteValidator validate Methods */ public void testByteValidatorMethods() { Locale locale = Locale.GERMAN; String pattern = "0,00"; String patternVal = "1,23"; String germanPatternVal = "1.23"; String localeVal = ".123"; String defaultVal = ",123"; String XXXX = "XXXX"; Byte expected = new Byte((byte)123); assertEquals("validate(A) default", expected, ByteValidator.getInstance().validate(defaultVal)); assertEquals("validate(A) locale ", expected, ByteValidator.getInstance().validate(localeVal, locale)); assertEquals("validate(A) pattern", expected, ByteValidator.getInstance().validate(patternVal, pattern)); assertEquals("validate(A) both", expected, ByteValidator.getInstance().validate(germanPatternVal, pattern, Locale.GERMAN)); assertTrue("isValid(A) default", ByteValidator.getInstance().isValid(defaultVal)); assertTrue("isValid(A) locale ", ByteValidator.getInstance().isValid(localeVal, locale)); assertTrue("isValid(A) pattern", ByteValidator.getInstance().isValid(patternVal, pattern)); assertTrue("isValid(A) both", ByteValidator.getInstance().isValid(germanPatternVal, pattern, Locale.GERMAN)); assertNull("validate(B) default", ByteValidator.getInstance().validate(XXXX)); assertNull("validate(B) locale ", ByteValidator.getInstance().validate(XXXX, locale)); assertNull("validate(B) pattern", ByteValidator.getInstance().validate(XXXX, pattern)); assertNull("validate(B) both", ByteValidator.getInstance().validate(patternVal, pattern, Locale.GERMAN)); assertFalse("isValid(B) default", ByteValidator.getInstance().isValid(XXXX)); assertFalse("isValid(B) locale ", ByteValidator.getInstance().isValid(XXXX, locale)); assertFalse("isValid(B) pattern", ByteValidator.getInstance().isValid(XXXX, pattern)); assertFalse("isValid(B) both", ByteValidator.getInstance().isValid(patternVal, pattern, Locale.GERMAN)); } /** * Test Byte Range/Min/Max */ public void testByteRangeMinMax() { ByteValidator validator = (ByteValidator)strictValidator; Byte number9 = validator.validate("9", "#"); Byte number10 = validator.validate("10", "#"); Byte number11 = validator.validate("11", "#"); Byte number19 = validator.validate("19", "#"); Byte number20 = validator.validate("20", "#"); Byte number21 = validator.validate("21", "#"); byte min = (byte)10; byte max = (byte)20; // Test isInRange() assertFalse("isInRange() < min", validator.isInRange(number9, min, max)); assertTrue("isInRange() = min", validator.isInRange(number10, min, max)); assertTrue("isInRange() in range", validator.isInRange(number11, min, max)); assertTrue("isInRange() = max", validator.isInRange(number20, min, max)); assertFalse("isInRange() > max", validator.isInRange(number21, min, max)); // Test minValue() assertFalse("minValue() < min", validator.minValue(number9, min)); assertTrue("minValue() = min", validator.minValue(number10, min)); assertTrue("minValue() > min", validator.minValue(number11, min)); // Test minValue() assertTrue("maxValue() < max", validator.maxValue(number19, max)); assertTrue("maxValue() = max", validator.maxValue(number20, max)); assertFalse("maxValue() > max", validator.maxValue(number21, max)); } } ././@LongLink100644 0 0 153 11711231552 10250 Lustar 0 0 commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/routines/CalendarValidatorTest.javacommons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/routines/CalendarValidatorTes100644 765 0 35464 11711227700 35022 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines; import java.text.Format; import java.text.DateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.TimeZone; /** * Test Case for CalendarValidator. * * @version $Revision: 1094751 $ $Date: 2011-04-18 23:17:40 +0200 (Mon, 18 Apr 2011) $ */ public class CalendarValidatorTest extends AbstractCalendarValidatorTest { private static final int DATE_2005_11_23 = 20051123; private static final int TIME_12_03_45 = 120345; private CalendarValidator calValidator; /** * Constructor * @param name test name */ public CalendarValidatorTest(String name) { super(name); } protected void setUp() throws Exception { super.setUp(); calValidator = new CalendarValidator(); validator = calValidator; } /** * Test CalendarValidator validate Methods */ public void testCalendarValidatorMethods() { Locale.setDefault(Locale.US); Locale locale = Locale.GERMAN; String pattern = "yyyy-MM-dd"; String patternVal = "2005-12-31"; String germanVal = "31 Dez 2005"; String germanPattern = "dd MMM yyyy"; String localeVal = "31.12.2005"; String defaultVal = "12/31/05"; String XXXX = "XXXX"; Date expected = createCalendar(null, 20051231, 0).getTime(); assertEquals("validate(A) default", expected, CalendarValidator.getInstance().validate(defaultVal).getTime()); assertEquals("validate(A) locale ", expected, CalendarValidator.getInstance().validate(localeVal, locale).getTime()); assertEquals("validate(A) pattern", expected, CalendarValidator.getInstance().validate(patternVal, pattern).getTime()); assertEquals("validate(A) both", expected, CalendarValidator.getInstance().validate(germanVal, germanPattern, Locale.GERMAN).getTime()); assertTrue("isValid(A) default", CalendarValidator.getInstance().isValid(defaultVal)); assertTrue("isValid(A) locale ", CalendarValidator.getInstance().isValid(localeVal, locale)); assertTrue("isValid(A) pattern", CalendarValidator.getInstance().isValid(patternVal, pattern)); assertTrue("isValid(A) both", CalendarValidator.getInstance().isValid(germanVal, germanPattern, Locale.GERMAN)); assertNull("validate(B) default", CalendarValidator.getInstance().validate(XXXX)); assertNull("validate(B) locale ", CalendarValidator.getInstance().validate(XXXX, locale)); assertNull("validate(B) pattern", CalendarValidator.getInstance().validate(XXXX, pattern)); assertNull("validate(B) both", CalendarValidator.getInstance().validate("31 Dec 2005", germanPattern, Locale.GERMAN)); assertFalse("isValid(B) default", CalendarValidator.getInstance().isValid(XXXX)); assertFalse("isValid(B) locale ", CalendarValidator.getInstance().isValid(XXXX, locale)); assertFalse("isValid(B) pattern", CalendarValidator.getInstance().isValid(XXXX, pattern)); assertFalse("isValid(B) both", CalendarValidator.getInstance().isValid("31 Dec 2005", germanPattern, Locale.GERMAN)); // Test Time Zone TimeZone zone = (TimeZone.getDefault().getRawOffset() == EET.getRawOffset() ? EST : EET); Date expectedZone = createCalendar(zone, 20051231, 0).getTime(); assertFalse("default/EET same ", expected.getTime() == expectedZone.getTime()); assertEquals("validate(C) default", expectedZone, CalendarValidator.getInstance().validate(defaultVal, zone).getTime()); assertEquals("validate(C) locale ", expectedZone, CalendarValidator.getInstance().validate(localeVal, locale, zone).getTime()); assertEquals("validate(C) pattern", expectedZone, CalendarValidator.getInstance().validate(patternVal, pattern, zone).getTime()); assertEquals("validate(C) both", expectedZone, CalendarValidator.getInstance().validate(germanVal, germanPattern, Locale.GERMAN, zone).getTime()); } /** * Test compare date methods */ public void testCompare() { int sameTime = 124522; int testDate = 20050823; Calendar diffHour = createCalendar(GMT, testDate, 115922); // same date, different time Calendar diffMin = createCalendar(GMT, testDate, 124422); // same date, different time Calendar diffSec = createCalendar(GMT, testDate, 124521); // same date, different time Calendar value = createCalendar(GMT, testDate, sameTime); // test value Calendar cal20050824 = createCalendar(GMT, 20050824, sameTime); // +1 day Calendar cal20050822 = createCalendar(GMT, 20050822, sameTime); // -1 day Calendar cal20050830 = createCalendar(GMT, 20050830, sameTime); // +1 week Calendar cal20050816 = createCalendar(GMT, 20050816, sameTime); // -1 week Calendar cal20050901 = createCalendar(GMT, 20050901, sameTime); // +1 month Calendar cal20050801 = createCalendar(GMT, 20050801, sameTime); // same month Calendar cal20050731 = createCalendar(GMT, 20050731, sameTime); // -1 month Calendar cal20051101 = createCalendar(GMT, 20051101, sameTime); // +1 quarter (Feb Start) Calendar cal20051001 = createCalendar(GMT, 20051001, sameTime); // +1 quarter Calendar cal20050701 = createCalendar(GMT, 20050701, sameTime); // same quarter Calendar cal20050630 = createCalendar(GMT, 20050630, sameTime); // -1 quarter Calendar cal20060101 = createCalendar(GMT, 20060101, sameTime); // +1 year Calendar cal20050101 = createCalendar(GMT, 20050101, sameTime); // same year Calendar cal20041231 = createCalendar(GMT, 20041231, sameTime); // -1 year assertEquals("hour GT", 1, calValidator.compare(value, diffHour, Calendar.HOUR_OF_DAY)); assertEquals("hour EQ", 0, calValidator.compare(value, diffMin, Calendar.HOUR_OF_DAY)); assertEquals("mins GT", 1, calValidator.compare(value, diffMin, Calendar.MINUTE)); assertEquals("mins EQ", 0, calValidator.compare(value, diffSec, Calendar.MINUTE)); assertEquals("secs GT", 1, calValidator.compare(value, diffSec, Calendar.SECOND)); assertEquals("date LT", -1, calValidator.compareDates(value, cal20050824)); // +1 day assertEquals("date EQ", 0, calValidator.compareDates(value, diffHour)); // same day, diff hour assertEquals("date(B)", 0, calValidator.compare(value, diffHour, Calendar.DAY_OF_YEAR)); // same day, diff hour assertEquals("date GT", 1, calValidator.compareDates(value, cal20050822)); // -1 day assertEquals("week LT", -1, calValidator.compareWeeks(value, cal20050830)); // +1 week assertEquals("week =1", 0, calValidator.compareWeeks(value, cal20050824)); // +1 day assertEquals("week =2", 0, calValidator.compareWeeks(value, cal20050822)); // same week assertEquals("week =3", 0, calValidator.compare(value, cal20050822, Calendar.WEEK_OF_MONTH)); // same week assertEquals("week =4", 0, calValidator.compareWeeks(value, cal20050822)); // -1 day assertEquals("week GT", 1, calValidator.compareWeeks(value, cal20050816)); // -1 week assertEquals("mnth LT", -1, calValidator.compareMonths(value, cal20050901)); // +1 month assertEquals("mnth =1", 0, calValidator.compareMonths(value, cal20050830)); // +1 week assertEquals("mnth =2", 0, calValidator.compareMonths(value, cal20050801)); // same month assertEquals("mnth =3", 0, calValidator.compareMonths(value, cal20050816)); // -1 week assertEquals("mnth GT", 1, calValidator.compareMonths(value, cal20050731)); // -1 month assertEquals("qtrA <1", -1, calValidator.compareQuarters(value, cal20051101)); // +1 quarter (Feb) assertEquals("qtrA <2", -1, calValidator.compareQuarters(value, cal20051001)); // +1 quarter assertEquals("qtrA =1", 0, calValidator.compareQuarters(value, cal20050901)); // +1 month assertEquals("qtrA =2", 0, calValidator.compareQuarters(value, cal20050701)); // same quarter assertEquals("qtrA =3", 0, calValidator.compareQuarters(value, cal20050731)); // -1 month assertEquals("qtrA GT", 1, calValidator.compareQuarters(value, cal20050630)); // -1 quarter // Change quarter 1 to start in Feb assertEquals("qtrB LT", -1, calValidator.compareQuarters(value, cal20051101, 2)); // +1 quarter (Feb) assertEquals("qtrB =1", 0, calValidator.compareQuarters(value, cal20051001, 2)); // same quarter assertEquals("qtrB =2", 0, calValidator.compareQuarters(value, cal20050901, 2)); // +1 month assertEquals("qtrB =3", 1, calValidator.compareQuarters(value, cal20050701, 2)); // same quarter assertEquals("qtrB =4", 1, calValidator.compareQuarters(value, cal20050731, 2)); // -1 month assertEquals("qtrB GT", 1, calValidator.compareQuarters(value, cal20050630, 2)); // -1 quarter assertEquals("year LT", -1, calValidator.compareYears(value, cal20060101)); // +1 year assertEquals("year EQ", 0, calValidator.compareYears(value, cal20050101)); // same year assertEquals("year GT", 1, calValidator.compareYears(value, cal20041231)); // -1 year // invalid compare try { calValidator.compare(value, value, -1); fail("Invalid Compare field - expected IllegalArgumentException to be thrown"); } catch (IllegalArgumentException e) { assertEquals("check message", "Invalid field: -1", e.getMessage()); } } /** * Test Date/Time style Validator (there isn't an implementation for this) */ public void testDateTimeStyle() { // Set the default Locale Locale origDefault = Locale.getDefault(); Locale.setDefault(Locale.UK); AbstractCalendarValidator dateTimeValidator = new AbstractCalendarValidator(true, DateFormat.SHORT, DateFormat.SHORT) { protected Object processParsedValue(Object value, Format formatter) { return value; } }; assertTrue("validate(A) default", dateTimeValidator.isValid("31/12/05 14:23")); assertTrue("validate(A) locale ", dateTimeValidator.isValid("12/31/05 2:23 PM", Locale.US)); // Restore the original default Locale.setDefault(origDefault); } /** * Test format methods */ public void testFormat() { // Set the default Locale Locale origDefault = Locale.getDefault(); Locale.setDefault(Locale.UK); Calendar cal20050101 = createCalendar(GMT, 20051231, 11500); assertNull("null", calValidator.format(null)); assertEquals("default", "31/12/05", calValidator.format(cal20050101)); assertEquals("locale", "12/31/05", calValidator.format(cal20050101, Locale.US)); assertEquals("patternA", "2005-12-31 01:15", calValidator.format(cal20050101, "yyyy-MM-dd HH:mm")); assertEquals("patternB", "2005-12-31 GMT", calValidator.format(cal20050101, "yyyy-MM-dd z")); assertEquals("both", "31 Dez 2005", calValidator.format(cal20050101, "dd MMM yyyy", Locale.GERMAN)); // EST Time Zone assertEquals("EST default", "30/12/05", calValidator.format(cal20050101, EST)); assertEquals("EST locale", "12/30/05", calValidator.format(cal20050101, Locale.US, EST)); assertEquals("EST patternA", "2005-12-30 20:15", calValidator.format(cal20050101, "yyyy-MM-dd HH:mm", EST)); assertEquals("EST patternB", "2005-12-30 EST", calValidator.format(cal20050101, "yyyy-MM-dd z", EST)); assertEquals("EST both", "30 Dez 2005", calValidator.format(cal20050101, "dd MMM yyyy", Locale.GERMAN, EST)); // Restore the original default Locale.setDefault(origDefault); } /** * Test adjustToTimeZone() method */ public void testAdjustToTimeZone() { Calendar calEST = createCalendar(EST, DATE_2005_11_23, TIME_12_03_45); Date dateEST = calEST.getTime(); Calendar calGMT = createCalendar(GMT, DATE_2005_11_23, TIME_12_03_45); Date dateGMT = calGMT.getTime(); Calendar calCET = createCalendar(EET, DATE_2005_11_23, TIME_12_03_45); Date dateCET = calCET.getTime(); // Check the dates don't match assertFalse("Check GMT != CET", dateGMT.getTime() == dateCET.getTime()); assertFalse("Check GMT != EST", dateGMT.getTime() == dateEST.getTime()); assertFalse("Check CET != EST", dateCET.getTime() == dateEST.getTime()); // EST to GMT and back CalendarValidator.adjustToTimeZone(calEST, GMT); assertEquals("EST to GMT", dateGMT, calEST.getTime()); assertFalse("Check EST = GMT", dateEST == calEST.getTime()); CalendarValidator.adjustToTimeZone(calEST, EST); assertEquals("back to EST", dateEST, calEST.getTime()); assertFalse("Check EST != GMT", dateGMT == calEST.getTime()); // CET to GMT and back CalendarValidator.adjustToTimeZone(calCET, GMT); assertEquals("CET to GMT", dateGMT, calCET.getTime()); assertFalse("Check CET = GMT", dateCET == calCET.getTime()); CalendarValidator.adjustToTimeZone(calCET, EET); assertEquals("back to CET", dateCET, calCET.getTime()); assertFalse("Check CET != GMT", dateGMT == calCET.getTime()); // Adjust to TimeZone with Same rules Calendar calUTC = createCalendar(UTC, DATE_2005_11_23, TIME_12_03_45); assertTrue("SAME: UTC = GMT", UTC.hasSameRules(GMT)); assertEquals("SAME: Check time (A)", calUTC.getTime(), calGMT.getTime()); assertFalse("SAME: Check GMT(A)", GMT.equals(calUTC.getTimeZone())); assertTrue("SAME: Check UTC(A)", UTC.equals(calUTC.getTimeZone())); CalendarValidator.adjustToTimeZone(calUTC, GMT); assertEquals("SAME: Check time (B)", calUTC.getTime(), calGMT.getTime()); assertTrue("SAME: Check GMT(B)", GMT.equals(calUTC.getTimeZone())); assertFalse("SAME: Check UTC(B)", UTC.equals(calUTC.getTimeZone())); } } ././@LongLink100644 0 0 147 11711231552 10253 Lustar 0 0 commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/routines/CodeValidatorTest.javacommons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/routines/CodeValidatorTest.ja100644 765 0 32130 11711227700 34723 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines; import org.apache.commons.validator.routines.checkdigit.CheckDigit; import org.apache.commons.validator.routines.checkdigit.EAN13CheckDigit; import junit.framework.TestCase; /** * CodeValidatorTest.java. * * @version $Revision: 1094799 $ $Date: 2011-04-19 00:40:24 +0200 (Tue, 19 Apr 2011) $ * @since Validator 1.4 */ public class CodeValidatorTest extends TestCase { /** * Construct a test with the specified name. * @param name The name of the test */ public CodeValidatorTest(String name) { super(name); } /** * @see junit.framework.TestCase#setUp() */ protected void setUp() throws Exception { super.setUp(); } /** * @see junit.framework.TestCase#tearDown() */ protected void tearDown() throws Exception { super.tearDown(); } /** * Test Check Digit. */ public void testCheckDigit() { CodeValidator validator = new CodeValidator((String)null, -1, -1, (CheckDigit)null); String invalidEAN = "9781930110992"; String validEAN = "9781930110991"; // Test no CheckDigit (i.e. null) assertNull("No CheckDigit", validator.getCheckDigit()); assertEquals("No CheckDigit invalid", invalidEAN, validator.validate(invalidEAN)); assertEquals("No CheckDigit valid", validEAN, validator.validate(validEAN)); assertEquals("No CheckDigit (is) invalid", true, validator.isValid(invalidEAN)); assertEquals("No CheckDigit (is) valid", true, validator.isValid(validEAN)); // Use the EAN-13 check digit routine validator = new CodeValidator((String)null, -1, EAN13CheckDigit.EAN13_CHECK_DIGIT); assertNotNull("EAN CheckDigit", validator.getCheckDigit()); assertEquals("EAN CheckDigit invalid", null, validator.validate(invalidEAN)); assertEquals("EAN CheckDigit valid", validEAN, validator.validate(validEAN)); assertEquals("EAN CheckDigit (is) invalid", false, validator.isValid(invalidEAN)); assertEquals("EAN CheckDigit (is) valid", true, validator.isValid(validEAN)); assertEquals("EAN CheckDigit ex", null, validator.validate("978193011099X")); } /** * Test the minimum/maximum length */ public void testLength() { CodeValidator validator = new CodeValidator((String)null, -1, -1, (CheckDigit)null); String length_10 = "1234567890"; String length_11 = "12345678901"; String length_12 = "123456789012"; String length_20 = "12345678901234567890"; String length_21 = "123456789012345678901"; String length_22 = "1234567890123456789012"; assertEquals("No min", -1, validator.getMinLength()); assertEquals("No max", -1, validator.getMaxLength()); assertEquals("No Length 10", length_10, validator.validate(length_10)); assertEquals("No Length 11", length_11, validator.validate(length_11)); assertEquals("No Length 12", length_12, validator.validate(length_12)); assertEquals("No Length 20", length_20, validator.validate(length_20)); assertEquals("No Length 21", length_21, validator.validate(length_21)); assertEquals("No Length 22", length_22, validator.validate(length_22)); validator = new CodeValidator((String)null, 11, -1, (CheckDigit)null); assertEquals("Min 11 - min", 11, validator.getMinLength()); assertEquals("Min 11 - max", -1, validator.getMaxLength()); assertEquals("Min 11 - 10", null, validator.validate(length_10)); assertEquals("Min 11 - 11", length_11, validator.validate(length_11)); assertEquals("Min 11 - 12", length_12, validator.validate(length_12)); assertEquals("Min 11 - 20", length_20, validator.validate(length_20)); assertEquals("Min 11 - 21", length_21, validator.validate(length_21)); assertEquals("Min 11 - 22", length_22, validator.validate(length_22)); validator = new CodeValidator((String)null, -1, 21, (CheckDigit)null); assertEquals("Max 21 - min", -1, validator.getMinLength()); assertEquals("Max 21 - max", 21, validator.getMaxLength()); assertEquals("Max 21 - 10", length_10, validator.validate(length_10)); assertEquals("Max 21 - 11", length_11, validator.validate(length_11)); assertEquals("Max 21 - 12", length_12, validator.validate(length_12)); assertEquals("Max 21 - 20", length_20, validator.validate(length_20)); assertEquals("Max 21 - 21", length_21, validator.validate(length_21)); assertEquals("Max 21 - 22", null, validator.validate(length_22)); validator = new CodeValidator((String)null, 11, 21, (CheckDigit)null); assertEquals("Min 11 / Max 21 - min", 11, validator.getMinLength()); assertEquals("Min 11 / Max 21 - max", 21, validator.getMaxLength()); assertEquals("Min 11 / Max 21 - 10", null, validator.validate(length_10)); assertEquals("Min 11 / Max 21 - 11", length_11, validator.validate(length_11)); assertEquals("Min 11 / Max 21 - 12", length_12, validator.validate(length_12)); assertEquals("Min 11 / Max 21 - 20", length_20, validator.validate(length_20)); assertEquals("Min 11 / Max 21 - 21", length_21, validator.validate(length_21)); assertEquals("Min 11 / Max 21 - 22", null, validator.validate(length_22)); validator = new CodeValidator((String)null, 11, 11, (CheckDigit)null); assertEquals("Exact 11 - min", 11, validator.getMinLength()); assertEquals("Exact 11 - max", 11, validator.getMaxLength()); assertEquals("Exact 11 - 10", null, validator.validate(length_10)); assertEquals("Exact 11 - 11", length_11, validator.validate(length_11)); assertEquals("Exact 11 - 12", null, validator.validate(length_12)); } /** * Test Regular Expression. */ public void testRegex() { CodeValidator validator = new CodeValidator((String)null, -1, -1, (CheckDigit)null); String value2 = "12"; String value3 = "123"; String value4 = "1234"; String value5 = "12345"; String invalid = "12a4"; // No Regular Expression assertNull("No Regex", validator.getRegexValidator()); assertEquals("No Regex 2", value2, validator.validate(value2)); assertEquals("No Regex 3", value3, validator.validate(value3)); assertEquals("No Regex 4", value4, validator.validate(value4)); assertEquals("No Regex 5", value5, validator.validate(value5)); assertEquals("No Regex invalid", invalid, validator.validate(invalid)); // Regular Expression String regex = "^([0-9]{3,4})$"; validator = new CodeValidator(regex, -1, -1, (CheckDigit)null); assertNotNull("No Regex", validator.getRegexValidator()); assertEquals("Regex 2", null, validator.validate(value2)); assertEquals("Regex 3", value3, validator.validate(value3)); assertEquals("Regex 4", value4, validator.validate(value4)); assertEquals("Regex 5", null, validator.validate(value5)); assertEquals("Regex invalid", null, validator.validate(invalid)); // Reformatted regex = "^([0-9]{3})(?:[-\\s])([0-9]{3})$"; validator = new CodeValidator(new RegexValidator(regex), 6, (CheckDigit)null); assertEquals("Reformat 123-456", "123456", validator.validate("123-456")); assertEquals("Reformat 123 456", "123456", validator.validate("123 456")); assertEquals("Reformat 123456", null, validator.validate("123456")); assertEquals("Reformat 123.456", null, validator.validate("123.456")); regex = "^(?:([0-9]{3})(?:[-\\s])([0-9]{3}))|([0-9]{6})$"; validator = new CodeValidator(new RegexValidator(regex), 6, (CheckDigit)null); assertEquals("Reformat 2 Regex", "RegexValidator{" + regex + "}", validator.getRegexValidator().toString()); assertEquals("Reformat 2 123-456", "123456", validator.validate("123-456")); assertEquals("Reformat 2 123 456", "123456", validator.validate("123 456")); assertEquals("Reformat 2 123456", "123456", validator.validate("123456")); } /** * Test Regular Expression. */ public void testNoInput() { CodeValidator validator = new CodeValidator((String)null, -1, -1, (CheckDigit)null); assertEquals("Null", null, validator.validate(null)); assertEquals("Zero Length", null, validator.validate("")); assertEquals("Spaces", null, validator.validate(" ")); assertEquals("Trimmed", "A", validator.validate(" A ")); } public void testValidator294_1() { CodeValidator validator = new CodeValidator((String)null, 0, -1, (CheckDigit)null); assertEquals("Null", null, validator.validate(null)); validator = new CodeValidator((String)null, -1, 0, (CheckDigit)null); assertEquals("Null", null, validator.validate(null)); } public void testValidator294_2() { CodeValidator validator = new CodeValidator((String)null, -1, 0, (CheckDigit)null); assertEquals("Null", null, validator.validate(null)); } /** * Test Regular Expression. */ public void testConstructors() { CodeValidator validator = null; RegexValidator regex = new RegexValidator("^[0-9]*$"); // Constructor 1 validator = new CodeValidator(regex, EAN13CheckDigit.EAN13_CHECK_DIGIT); assertEquals("Constructor 1 - regex", regex, validator.getRegexValidator()); assertEquals("Constructor 1 - min length", -1, validator.getMinLength()); assertEquals("Constructor 1 - max length", -1, validator.getMaxLength()); assertEquals("Constructor 1 - check digit", EAN13CheckDigit.EAN13_CHECK_DIGIT, validator.getCheckDigit()); // Constructor 2 validator = new CodeValidator(regex, 13, EAN13CheckDigit.EAN13_CHECK_DIGIT); assertEquals("Constructor 2 - regex", regex, validator.getRegexValidator()); assertEquals("Constructor 2 - min length", 13, validator.getMinLength()); assertEquals("Constructor 2 - max length", 13, validator.getMaxLength()); assertEquals("Constructor 2 - check digit", EAN13CheckDigit.EAN13_CHECK_DIGIT, validator.getCheckDigit()); // Constructor 3 validator = new CodeValidator(regex, 10, 20, EAN13CheckDigit.EAN13_CHECK_DIGIT); assertEquals("Constructor 3 - regex", regex, validator.getRegexValidator()); assertEquals("Constructor 3 - min length", 10, validator.getMinLength()); assertEquals("Constructor 3 - max length", 20, validator.getMaxLength()); assertEquals("Constructor 3 - check digit", EAN13CheckDigit.EAN13_CHECK_DIGIT, validator.getCheckDigit()); // Constructor 4 validator = new CodeValidator("^[0-9]*$", EAN13CheckDigit.EAN13_CHECK_DIGIT); assertEquals("Constructor 4 - regex", "RegexValidator{^[0-9]*$}", validator.getRegexValidator().toString()); assertEquals("Constructor 4 - min length", -1, validator.getMinLength()); assertEquals("Constructor 4 - max length", -1, validator.getMaxLength()); assertEquals("Constructor 4 - check digit", EAN13CheckDigit.EAN13_CHECK_DIGIT, validator.getCheckDigit()); // Constructor 5 validator = new CodeValidator("^[0-9]*$", 13, EAN13CheckDigit.EAN13_CHECK_DIGIT); assertEquals("Constructor 5 - regex", "RegexValidator{^[0-9]*$}", validator.getRegexValidator().toString()); assertEquals("Constructor 5 - min length", 13, validator.getMinLength()); assertEquals("Constructor 5 - max length", 13, validator.getMaxLength()); assertEquals("Constructor 5 - check digit", EAN13CheckDigit.EAN13_CHECK_DIGIT, validator.getCheckDigit()); // Constructor 6 validator = new CodeValidator("^[0-9]*$", 10, 20, EAN13CheckDigit.EAN13_CHECK_DIGIT); assertEquals("Constructor 6 - regex", "RegexValidator{^[0-9]*$}", validator.getRegexValidator().toString()); assertEquals("Constructor 6 - min length", 10, validator.getMinLength()); assertEquals("Constructor 6 - max length", 20, validator.getMaxLength()); assertEquals("Constructor 6 - check digit", EAN13CheckDigit.EAN13_CHECK_DIGIT, validator.getCheckDigit()); } } ././@LongLink100644 0 0 155 11711231552 10252 Lustar 0 0 commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/routines/CreditCardValidatorTest.javacommons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/routines/CreditCardValidatorT100644 765 0 63423 11711227700 34761 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines; import junit.framework.TestCase; import org.apache.commons.validator.routines.checkdigit.LuhnCheckDigit; /** * Test the CreditCardValidator class. * * @version $Revision: 1128380 $ $Date: 2011-05-27 18:15:02 +0200 (Fri, 27 May 2011) $ */ public class CreditCardValidatorTest extends TestCase { private static final String VALID_VISA = "4417123456789113"; private static final String ERROR_VISA = "4417123456789112"; private static final String VALID_SHORT_VISA = "4222222222222"; private static final String ERROR_SHORT_VISA = "4222222222229"; private static final String VALID_AMEX = "378282246310005"; private static final String ERROR_AMEX = "378282246310001"; private static final String VALID_MASTERCARD = "5105105105105100"; private static final String ERROR_MASTERCARD = "5105105105105105"; private static final String VALID_DISCOVER = "6011000990139424"; private static final String ERROR_DISCOVER = "6011000990139421"; private static final String VALID_DISCOVER65 = "6534567890123458"; // FIXME need verified test data for Discover with "65" prefix private static final String ERROR_DISCOVER65 = "6534567890123450"; // FIXME need verified test data for Discover with "65" prefix private static final String VALID_DINERS = "30569309025904"; private static final String ERROR_DINERS = "30569309025901"; /** * Constructor for CreditCardValidatorTest. */ public CreditCardValidatorTest(String name) { super(name); } public void testIsValid() { CreditCardValidator ccv = new CreditCardValidator(); assertNull(ccv.validate(null)); assertFalse(ccv.isValid(null)); assertFalse(ccv.isValid("")); assertFalse(ccv.isValid("123456789012")); // too short assertFalse(ccv.isValid("12345678901234567890")); // too long assertFalse(ccv.isValid("4417123456789112")); assertFalse(ccv.isValid("4417q23456w89113")); assertTrue(ccv.isValid(VALID_VISA)); assertTrue(ccv.isValid(VALID_SHORT_VISA)); assertTrue(ccv.isValid(VALID_AMEX)); assertTrue(ccv.isValid(VALID_MASTERCARD)); assertTrue(ccv.isValid(VALID_DISCOVER)); assertTrue(ccv.isValid(VALID_DISCOVER65)); assertFalse(ccv.isValid(ERROR_VISA)); assertFalse(ccv.isValid(ERROR_SHORT_VISA)); assertFalse(ccv.isValid(ERROR_AMEX)); assertFalse(ccv.isValid(ERROR_MASTERCARD)); assertFalse(ccv.isValid(ERROR_DISCOVER)); assertFalse(ccv.isValid(ERROR_DISCOVER65)); // disallow Visa so it should fail even with good number ccv = new CreditCardValidator(CreditCardValidator.AMEX); assertFalse(ccv.isValid("4417123456789113")); } public void testAddAllowedCardType() { CreditCardValidator ccv = new CreditCardValidator(CreditCardValidator.NONE); // Turned off all cards so even valid numbers should fail assertFalse(ccv.isValid(VALID_VISA)); assertFalse(ccv.isValid(VALID_AMEX)); assertFalse(ccv.isValid(VALID_MASTERCARD)); assertFalse(ccv.isValid(VALID_DISCOVER)); assertFalse(ccv.isValid(VALID_DINERS)); } /** * Test the CodeValidator array constructor */ public void testArrayConstructor() { CreditCardValidator ccv = new CreditCardValidator(new CodeValidator[] {CreditCardValidator.VISA_VALIDATOR, CreditCardValidator.AMEX_VALIDATOR}); assertTrue(ccv.isValid(VALID_VISA)); assertTrue(ccv.isValid(VALID_SHORT_VISA)); assertTrue(ccv.isValid(VALID_AMEX)); assertFalse(ccv.isValid(VALID_MASTERCARD)); assertFalse(ccv.isValid(VALID_DISCOVER)); assertFalse(ccv.isValid(ERROR_VISA)); assertFalse(ccv.isValid(ERROR_SHORT_VISA)); assertFalse(ccv.isValid(ERROR_AMEX)); assertFalse(ccv.isValid(ERROR_MASTERCARD)); assertFalse(ccv.isValid(ERROR_DISCOVER)); try { new CreditCardValidator((CodeValidator[]) null); fail("Expected IllegalArgumentException"); } catch(IllegalArgumentException iae) { // expected result } } /** * Test the Amex Card validator */ public void testAmexValidator() { CodeValidator validator = CreditCardValidator.AMEX_VALIDATOR; RegexValidator regex = validator.getRegexValidator(); // ****** Test Regular Expression ****** // length 15 and start with a "34" or "37" assertFalse("Length 12", regex.isValid("343456789012")); assertFalse("Length 13", regex.isValid("3434567890123")); assertFalse("Length 14", regex.isValid("34345678901234")); assertTrue("Length 15", regex.isValid("343456789012345")); assertFalse("Length 16", regex.isValid("3434567890123456")); assertFalse("Length 17", regex.isValid("34345678901234567")); assertFalse("Length 18", regex.isValid("343456789012345678")); assertFalse("Prefix 33", regex.isValid("333456789012345")); assertTrue("Prefix 34", regex.isValid("343456789012345")); assertFalse("Prefix 35", regex.isValid("353456789012345")); assertFalse("Prefix 36", regex.isValid("363456789012345")); assertTrue("Prefix 37", regex.isValid("373456789012345")); assertFalse("Prefix 38", regex.isValid("383456789012345")); assertFalse("Prefix 41", regex.isValid("413456789012345")); assertFalse("Invalid Char", regex.isValid("3434567x9012345")); // *********** Test Validator ********** assertTrue("Valid regex", regex.isValid(ERROR_AMEX)); assertFalse("Invalid", validator.isValid(ERROR_AMEX)); assertNull("validate()", validator.validate(ERROR_AMEX)); assertEquals(VALID_AMEX, validator.validate(VALID_AMEX)); assertTrue("Amex", validator.isValid(VALID_AMEX)); assertFalse("Diners", validator.isValid(VALID_DINERS)); assertFalse("Discover", validator.isValid(VALID_DISCOVER)); assertFalse("Mastercard", validator.isValid(VALID_MASTERCARD)); assertFalse("Visa", validator.isValid(VALID_VISA)); assertFalse("Visa Short", validator.isValid(VALID_SHORT_VISA)); assertTrue("Valid-A", validator.isValid("371449635398431")); assertTrue("Valid-B", validator.isValid("340000000000009")); assertTrue("Valid-C", validator.isValid("370000000000002")); assertTrue("Valid-D", validator.isValid("378734493671000")); } /** * Test the Amex Card option */ public void testAmexOption() { CreditCardValidator validator = new CreditCardValidator(CreditCardValidator.AMEX); assertFalse("Invalid", validator.isValid(ERROR_AMEX)); assertNull("validate()", validator.validate(ERROR_AMEX)); assertEquals(VALID_AMEX, validator.validate(VALID_AMEX)); assertTrue("Amex", validator.isValid(VALID_AMEX)); assertFalse("Diners", validator.isValid(VALID_DINERS)); assertFalse("Discover", validator.isValid(VALID_DISCOVER)); assertFalse("Mastercard", validator.isValid(VALID_MASTERCARD)); assertFalse("Visa", validator.isValid(VALID_VISA)); assertFalse("Visa Short", validator.isValid(VALID_SHORT_VISA)); } /** * Test the Diners Card validator */ public void testDinersValidator() { CodeValidator validator = CreditCardValidator.DINERS_VALIDATOR; RegexValidator regex = validator.getRegexValidator(); // ****** Test Regular Expression ****** // length 14 and start with a "300-305" or "3095" or "36" or "38" or "39" assertFalse("Length 12-300", regex.isValid("300456789012")); assertFalse("Length 12-36", regex.isValid("363456789012")); assertFalse("Length 13-300", regex.isValid("3004567890123")); assertFalse("Length 13-36", regex.isValid("3634567890123")); assertTrue("Length 14-300", regex.isValid("30045678901234")); assertTrue("Length 14-36", regex.isValid("36345678901234")); assertFalse("Length 15-300", regex.isValid("300456789012345")); assertFalse("Length 15-36", regex.isValid("363456789012345")); assertFalse("Length 16-300", regex.isValid("3004567890123456")); assertFalse("Length 16-36", regex.isValid("3634567890123456")); assertFalse("Length 17-300", regex.isValid("30045678901234567")); assertFalse("Length 17-36", regex.isValid("36345678901234567")); assertFalse("Length 18-300", regex.isValid("300456789012345678")); assertFalse("Length 18-36", regex.isValid("363456789012345678")); assertTrue("Prefix 300", regex.isValid("30045678901234")); assertTrue("Prefix 301", regex.isValid("30145678901234")); assertTrue("Prefix 302", regex.isValid("30245678901234")); assertTrue("Prefix 303", regex.isValid("30345678901234")); assertTrue("Prefix 304", regex.isValid("30445678901234")); assertTrue("Prefix 305", regex.isValid("30545678901234")); assertFalse("Prefix 306", regex.isValid("30645678901234")); assertFalse("Prefix 3094", regex.isValid("30945678901234")); assertTrue( "Prefix 3095", regex.isValid("30955678901234")); assertFalse("Prefix 3096", regex.isValid("30965678901234")); assertFalse("Prefix 35", regex.isValid("35345678901234")); assertTrue("Prefix 36", regex.isValid("36345678901234")); assertFalse("Prefix 37", regex.isValid("37345678901234")); assertTrue("Prefix 38", regex.isValid("38345678901234")); assertTrue("Prefix 39", regex.isValid("39345678901234")); assertFalse("Invalid Char-A", regex.isValid("3004567x901234")); assertFalse("Invalid Char-B", regex.isValid("3634567x901234")); // *********** Test Validator ********** assertTrue("Valid regex", regex.isValid(ERROR_DINERS)); assertFalse("Invalid", validator.isValid(ERROR_DINERS)); assertNull("validate()", validator.validate(ERROR_DINERS)); assertEquals(VALID_DINERS, validator.validate(VALID_DINERS)); assertFalse("Amex", validator.isValid(VALID_AMEX)); assertTrue("Diners", validator.isValid(VALID_DINERS)); assertFalse("Discover", validator.isValid(VALID_DISCOVER)); assertFalse("Mastercard", validator.isValid(VALID_MASTERCARD)); assertFalse("Visa", validator.isValid(VALID_VISA)); assertFalse("Visa Short", validator.isValid(VALID_SHORT_VISA)); assertTrue("Valid-A", validator.isValid("30000000000004")); assertTrue("Valid-B", validator.isValid("30123456789019")); assertTrue("Valid-C", validator.isValid("36432685260294")); } /** * Test the Diners Card option */ public void testDinersOption() { CreditCardValidator validator = new CreditCardValidator(CreditCardValidator.DINERS); assertFalse("Invalid", validator.isValid(ERROR_DINERS)); assertNull("validate()", validator.validate(ERROR_DINERS)); assertEquals(VALID_DINERS, validator.validate(VALID_DINERS)); assertFalse("Amex", validator.isValid(VALID_AMEX)); assertTrue("Diners", validator.isValid(VALID_DINERS)); assertFalse("Discover", validator.isValid(VALID_DISCOVER)); assertFalse("Mastercard", validator.isValid(VALID_MASTERCARD)); assertFalse("Visa", validator.isValid(VALID_VISA)); assertFalse("Visa Short", validator.isValid(VALID_SHORT_VISA)); } /** * Test the Discover Card validator */ public void testDiscoverValidator() { CodeValidator validator = CreditCardValidator.DISCOVER_VALIDATOR; RegexValidator regex = validator.getRegexValidator(); // ****** Test Regular Expression ****** // length 16 and start with either "6011" or or "64[4-9]" or "65" assertFalse("Length 12-6011", regex.isValid("601156789012")); assertFalse("Length 12-65", regex.isValid("653456789012")); assertFalse("Length 13-6011", regex.isValid("6011567890123")); assertFalse("Length 13-65", regex.isValid("6534567890123")); assertFalse("Length 14-6011", regex.isValid("60115678901234")); assertFalse("Length 14-65", regex.isValid("65345678901234")); assertFalse("Length 15-6011", regex.isValid("601156789012345")); assertFalse("Length 15-65", regex.isValid("653456789012345")); assertTrue("Length 16-6011", regex.isValid("6011567890123456")); assertTrue("Length 16-644", regex.isValid("6444567890123456")); assertTrue("Length 16-648", regex.isValid("6484567890123456")); assertTrue("Length 16-65", regex.isValid("6534567890123456")); assertFalse("Length 17-6011", regex.isValid("60115678901234567")); assertFalse("Length 17-65", regex.isValid("65345678901234567")); assertFalse("Length 18-6011", regex.isValid("601156789012345678")); assertFalse("Length 18-65", regex.isValid("653456789012345678")); assertFalse("Prefix 640", regex.isValid("6404567890123456")); assertFalse("Prefix 641", regex.isValid("6414567890123456")); assertFalse("Prefix 642", regex.isValid("6424567890123456")); assertFalse("Prefix 643", regex.isValid("6434567890123456")); assertFalse("Prefix 6010", regex.isValid("6010567890123456")); assertFalse("Prefix 6012", regex.isValid("6012567890123456")); assertFalse("Invalid Char", regex.isValid("6011567x90123456")); // *********** Test Validator ********** assertTrue("Valid regex", regex.isValid(ERROR_DISCOVER)); assertTrue("Valid regex65", regex.isValid(ERROR_DISCOVER65)); assertFalse("Invalid", validator.isValid(ERROR_DISCOVER)); assertFalse("Invalid65", validator.isValid(ERROR_DISCOVER65)); assertNull("validate()", validator.validate(ERROR_DISCOVER)); assertEquals(VALID_DISCOVER, validator.validate(VALID_DISCOVER)); assertEquals(VALID_DISCOVER65, validator.validate(VALID_DISCOVER65)); assertFalse("Amex", validator.isValid(VALID_AMEX)); assertFalse("Diners", validator.isValid(VALID_DINERS)); assertTrue("Discover", validator.isValid(VALID_DISCOVER)); assertTrue("Discover", validator.isValid(VALID_DISCOVER65)); assertFalse("Mastercard", validator.isValid(VALID_MASTERCARD)); assertFalse("Visa", validator.isValid(VALID_VISA)); assertFalse("Visa Short", validator.isValid(VALID_SHORT_VISA)); assertTrue("Valid-A", validator.isValid("6011111111111117")); assertTrue("Valid-B", validator.isValid("6011000000000004")); assertTrue("Valid-C", validator.isValid("6011000000000012")); } /** * Test the Discover Card option */ public void testDiscoverOption() { CreditCardValidator validator = new CreditCardValidator(CreditCardValidator.DISCOVER); assertFalse("Invalid", validator.isValid(ERROR_DISCOVER)); assertFalse("Invalid65", validator.isValid(ERROR_DISCOVER65)); assertNull("validate()", validator.validate(ERROR_DISCOVER)); assertEquals(VALID_DISCOVER, validator.validate(VALID_DISCOVER)); assertEquals(VALID_DISCOVER65, validator.validate(VALID_DISCOVER65)); assertFalse("Amex", validator.isValid(VALID_AMEX)); assertFalse("Diners", validator.isValid(VALID_DINERS)); assertTrue("Discover", validator.isValid(VALID_DISCOVER)); assertTrue("Discover", validator.isValid(VALID_DISCOVER65)); assertFalse("Mastercard", validator.isValid(VALID_MASTERCARD)); assertFalse("Visa", validator.isValid(VALID_VISA)); assertFalse("Visa Short", validator.isValid(VALID_SHORT_VISA)); } /** * Test the Mastercard Card validator */ public void testMastercardValidator() { CodeValidator validator = CreditCardValidator.MASTERCARD_VALIDATOR; RegexValidator regex = validator.getRegexValidator(); // ****** Test Regular Expression ****** // length 16 and start with a "51-55" assertFalse("Length 12", regex.isValid("513456789012")); assertFalse("Length 13", regex.isValid("5134567890123")); assertFalse("Length 14", regex.isValid("51345678901234")); assertFalse("Length 15", regex.isValid("513456789012345")); assertTrue("Length 16", regex.isValid("5134567890123456")); assertFalse("Length 17", regex.isValid("51345678901234567")); assertFalse("Length 18", regex.isValid("513456789012345678")); assertFalse("Prefix 41", regex.isValid("4134567890123456")); assertFalse("Prefix 50", regex.isValid("5034567890123456")); assertTrue("Prefix 51", regex.isValid("5134567890123456")); assertTrue("Prefix 52", regex.isValid("5234567890123456")); assertTrue("Prefix 53", regex.isValid("5334567890123456")); assertTrue("Prefix 54", regex.isValid("5434567890123456")); assertTrue("Prefix 55", regex.isValid("5534567890123456")); assertFalse("Prefix 56", regex.isValid("5634567890123456")); assertFalse("Prefix 61", regex.isValid("6134567890123456")); assertFalse("Invalid Char", regex.isValid("5134567x90123456")); // *********** Test Validator ********** assertTrue("Valid regex", regex.isValid(ERROR_MASTERCARD)); assertFalse("Invalid", validator.isValid(ERROR_MASTERCARD)); assertNull("validate()", validator.validate(ERROR_MASTERCARD)); assertEquals(VALID_MASTERCARD, validator.validate(VALID_MASTERCARD)); assertFalse("Amex", validator.isValid(VALID_AMEX)); assertFalse("Diners", validator.isValid(VALID_DINERS)); assertFalse("Discover", validator.isValid(VALID_DISCOVER)); assertTrue("Mastercard", validator.isValid(VALID_MASTERCARD)); assertFalse("Visa", validator.isValid(VALID_VISA)); assertFalse("Visa Short", validator.isValid(VALID_SHORT_VISA)); assertTrue("Valid-A", validator.isValid("5500000000000004")); assertTrue("Valid-B", validator.isValid("5424000000000015")); assertTrue("Valid-C", validator.isValid("5301250070000191")); assertTrue("Valid-D", validator.isValid("5123456789012346")); assertTrue("Valid-E", validator.isValid("5555555555554444")); } /** * Test the Mastercard Card option */ public void testMastercardOption() { CreditCardValidator validator = new CreditCardValidator(CreditCardValidator.MASTERCARD); assertFalse("Invalid", validator.isValid(ERROR_MASTERCARD)); assertNull("validate()", validator.validate(ERROR_MASTERCARD)); assertEquals(VALID_MASTERCARD, validator.validate(VALID_MASTERCARD)); assertFalse("Amex", validator.isValid(VALID_AMEX)); assertFalse("Diners", validator.isValid(VALID_DINERS)); assertFalse("Discover", validator.isValid(VALID_DISCOVER)); assertTrue("Mastercard", validator.isValid(VALID_MASTERCARD)); assertFalse("Visa", validator.isValid(VALID_VISA)); assertFalse("Visa Short", validator.isValid(VALID_SHORT_VISA)); } /** * Test the Visa Card validator */ public void testVisaValidator() { CodeValidator validator = CreditCardValidator.VISA_VALIDATOR; RegexValidator regex = validator.getRegexValidator(); // ****** Test Regular Expression ****** // length 13 or 16, must start with a "4" assertFalse("Length 12", regex.isValid("423456789012")); assertTrue("Length 13", regex.isValid("4234567890123")); assertFalse("Length 14", regex.isValid("42345678901234")); assertFalse("Length 15", regex.isValid("423456789012345")); assertTrue("Length 16", regex.isValid("4234567890123456")); assertFalse("Length 17", regex.isValid("42345678901234567")); assertFalse("Length 18", regex.isValid("423456789012345678")); assertFalse("Invalid Pref-A", regex.isValid("3234567890123")); assertFalse("Invalid Pref-B", regex.isValid("3234567890123456")); assertFalse("Invalid Char-A", regex.isValid("4234567x90123")); assertFalse("Invalid Char-B", regex.isValid("4234567x90123456")); // *********** Test Validator ********** assertTrue("Valid regex", regex.isValid(ERROR_VISA)); assertTrue("Valid regex-S", regex.isValid(ERROR_SHORT_VISA)); assertFalse("Invalid", validator.isValid(ERROR_VISA)); assertFalse("Invalid-S", validator.isValid(ERROR_SHORT_VISA)); assertNull("validate()", validator.validate(ERROR_VISA)); assertEquals(VALID_VISA, validator.validate(VALID_VISA)); assertEquals(VALID_SHORT_VISA, validator.validate(VALID_SHORT_VISA)); assertFalse("Amex", validator.isValid(VALID_AMEX)); assertFalse("Diners", validator.isValid(VALID_DINERS)); assertFalse("Discover", validator.isValid(VALID_DISCOVER)); assertFalse("Mastercard", validator.isValid(VALID_MASTERCARD)); assertTrue("Visa", validator.isValid(VALID_VISA)); assertTrue("Visa Short", validator.isValid(VALID_SHORT_VISA)); assertTrue("Valid-A", validator.isValid("4111111111111111")); assertTrue("Valid-C", validator.isValid("4543059999999982")); assertTrue("Valid-B", validator.isValid("4462000000000003")); assertTrue("Valid-D", validator.isValid("4508750000000009")); // Electron assertTrue("Valid-E", validator.isValid("4012888888881881")); } /** * Test the Visa Card option */ public void testVisaOption() { CreditCardValidator validator = new CreditCardValidator(CreditCardValidator.VISA); assertFalse("Invalid", validator.isValid(ERROR_VISA)); assertFalse("Invalid-S", validator.isValid(ERROR_SHORT_VISA)); assertNull("validate()", validator.validate(ERROR_VISA)); assertEquals(VALID_VISA, validator.validate(VALID_VISA)); assertEquals(VALID_SHORT_VISA, validator.validate(VALID_SHORT_VISA)); assertFalse("Amex", validator.isValid(VALID_AMEX)); assertFalse("Diners", validator.isValid(VALID_DINERS)); assertFalse("Discover", validator.isValid(VALID_DISCOVER)); assertFalse("Mastercard", validator.isValid(VALID_MASTERCARD)); assertTrue("Visa", validator.isValid(VALID_VISA)); assertTrue("Visa Short", validator.isValid(VALID_SHORT_VISA)); } /** * Test using separators */ public void testMastercardUsingSeparators() { String MASTERCARD_REGEX_SEP = "^(5[1-5]\\d{2})(?:[- ])?(\\d{4})(?:[- ])?(\\d{4})(?:[- ])?(\\d{4})$"; CodeValidator validator = new CodeValidator(MASTERCARD_REGEX_SEP, LuhnCheckDigit.LUHN_CHECK_DIGIT); RegexValidator regex = validator.getRegexValidator(); // ****** Test Regular Expression ****** // length 16 and start with a "51-55" assertEquals("Number", "5134567890123456", regex.validate("5134567890123456")); assertEquals("Hyphen", "5134567890123456", regex.validate("5134-5678-9012-3456")); assertEquals("Space", "5134567890123456", regex.validate("5134 5678 9012 3456")); assertEquals("MixedA", "5134567890123456", regex.validate("5134-5678 9012-3456")); assertEquals("MixedB", "5134567890123456", regex.validate("5134 5678-9012 3456")); assertFalse("Invalid Separator A", regex.isValid("5134.5678.9012.3456")); assertFalse("Invalid Separator B", regex.isValid("5134_5678_9012_3456")); assertFalse("Invalid Grouping A", regex.isValid("513-45678-9012-3456")); assertFalse("Invalid Grouping B", regex.isValid("5134-567-89012-3456")); assertFalse("Invalid Grouping C", regex.isValid("5134-5678-901-23456")); // *********** Test Validator ********** assertEquals("Valid-A", "5500000000000004", validator.validate("5500-0000-0000-0004")); assertEquals("Valid-B", "5424000000000015", validator.validate("5424 0000 0000 0015")); assertEquals("Valid-C", "5301250070000191", validator.validate("5301-250070000191")); assertEquals("Valid-D", "5123456789012346", validator.validate("5123456789012346")); } } ././@LongLink100644 0 0 153 11711231552 10250 Lustar 0 0 commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/routines/CurrencyValidatorTest.javacommons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/routines/CurrencyValidatorTes100644 765 0 20411 11711227700 35065 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines; import junit.framework.TestCase; import java.util.Locale; import java.math.BigDecimal; import java.text.DecimalFormatSymbols; /** * Test Case for CurrencyValidator. * * @version $Revision: 1094751 $ $Date: 2011-04-18 23:17:40 +0200 (Mon, 18 Apr 2011) $ */ public class CurrencyValidatorTest extends TestCase { private static final char CURRENCY_SYMBOL = '\u00A4'; private String US_DOLLAR; private String UK_POUND; /** * Constructor * @param name test name */ public CurrencyValidatorTest(String name) { super(name); } protected void setUp() throws Exception { super.setUp(); US_DOLLAR = (new DecimalFormatSymbols(Locale.US)).getCurrencySymbol(); UK_POUND = (new DecimalFormatSymbols(Locale.UK)).getCurrencySymbol(); } /** * Tear down * @throws Exception */ protected void tearDown() throws Exception { super.tearDown(); } /** * Test Format Type */ public void testFormatType() { assertEquals("Format Type A", 1, CurrencyValidator.getInstance().getFormatType()); assertEquals("Format Type B", CurrencyValidator.CURRENCY_FORMAT, CurrencyValidator.getInstance().getFormatType()); } /** * Test Valid currency values */ public void testValid() { // Set the default Locale Locale origDefault = Locale.getDefault(); Locale.setDefault(Locale.UK); BigDecimalValidator validator = CurrencyValidator.getInstance(); BigDecimal expected = new BigDecimal("1234.56"); BigDecimal negative = new BigDecimal("-1234.56"); BigDecimal noDecimal = new BigDecimal("1234.00"); BigDecimal oneDecimal = new BigDecimal("1234.50"); assertEquals("Default locale", expected, validator.validate(UK_POUND + "1,234.56")); assertEquals("UK locale", expected, validator.validate(UK_POUND + "1,234.56", Locale.UK)); assertEquals("UK negative", negative, validator.validate("-" + UK_POUND + "1,234.56", Locale.UK)); assertEquals("UK no decimal", noDecimal, validator.validate(UK_POUND + "1,234", Locale.UK)); assertEquals("UK 1 decimal", oneDecimal, validator.validate(UK_POUND + "1,234.5", Locale.UK)); assertEquals("UK 3 decimal", expected, validator.validate(UK_POUND + "1,234.567", Locale.UK)); assertEquals("UK no symbol", expected, validator.validate("1,234.56", Locale.UK)); assertEquals("US locale", expected, validator.validate(US_DOLLAR + "1,234.56", Locale.US)); assertEquals("US negative", negative, validator.validate("(" + US_DOLLAR + "1,234.56)", Locale.US)); assertEquals("US no decimal", noDecimal, validator.validate(US_DOLLAR + "1,234", Locale.US)); assertEquals("US 1 decimal", oneDecimal, validator.validate(US_DOLLAR + "1,234.5", Locale.US)); assertEquals("US 3 decimal", expected, validator.validate(US_DOLLAR + "1,234.567", Locale.US)); assertEquals("US no symbol", expected, validator.validate("1,234.56", Locale.US)); // Restore the original default Locale.setDefault(origDefault); } /** * Test Invalid currency values */ public void testInvalid() { BigDecimalValidator validator = CurrencyValidator.getInstance(); // Invalid Missing assertFalse("isValid() Null Value", validator.isValid(null)); assertFalse("isValid() Empty Value", validator.isValid("")); assertNull("validate() Null Value", validator.validate(null)); assertNull("validate() Empty Value", validator.validate("")); // Invalid UK assertFalse("UK wrong symbol", validator.isValid(US_DOLLAR + "1,234.56", Locale.UK)); assertFalse("UK wrong negative", validator.isValid("(" + UK_POUND + "1,234.56)", Locale.UK)); // Invalid US assertFalse("US wrong symbol", validator.isValid(UK_POUND + "1,234.56", Locale.US)); assertFalse("US wrong negative", validator.isValid("-" + US_DOLLAR + "1,234.56", Locale.US)); } /** * Test Valid integer (non-decimal) currency values */ public void testIntegerValid() { // Set the default Locale Locale origDefault = Locale.getDefault(); Locale.setDefault(Locale.UK); CurrencyValidator validator = new CurrencyValidator(); BigDecimal expected = new BigDecimal("1234.00"); BigDecimal negative = new BigDecimal("-1234.00"); assertEquals("Default locale", expected, validator.validate(UK_POUND +"1,234")); assertEquals("UK locale", expected, validator.validate(UK_POUND + "1,234", Locale.UK)); assertEquals("UK negative", negative, validator.validate("-" + UK_POUND + "1,234", Locale.UK)); assertEquals("US locale", expected, validator.validate(US_DOLLAR + "1,234", Locale.US)); assertEquals("US negative", negative, validator.validate("(" + US_DOLLAR + "1,234)", Locale.US)); // Restore the original default Locale.setDefault(origDefault); } /** * Test Invalid integer (non decimal) currency values */ public void testIntegerInvalid() { CurrencyValidator validator = new CurrencyValidator(true, false); // Invalid UK - has decimals assertFalse("UK positive", validator.isValid(UK_POUND + "1,234.56", Locale.UK)); assertFalse("UK negative", validator.isValid("-" + UK_POUND + "1,234.56", Locale.UK)); // Invalid US - has decimals assertFalse("US positive", validator.isValid(US_DOLLAR + "1,234.56", Locale.US)); assertFalse("US negative", validator.isValid("(" + US_DOLLAR + "1,234.56)", Locale.US)); } /** * Test currency values with a pattern */ public void testPattern() { // Set the default Locale Locale origDefault = Locale.getDefault(); Locale.setDefault(Locale.UK); BigDecimalValidator validator = CurrencyValidator.getInstance(); String basicPattern = CURRENCY_SYMBOL + "#,##0.000"; String pattern = basicPattern + ";[" + basicPattern +"]"; BigDecimal expected = new BigDecimal("1234.567"); BigDecimal negative = new BigDecimal("-1234.567"); // Test Pattern assertEquals("default", expected, validator.validate(UK_POUND + "1,234.567", pattern)); assertEquals("negative", negative, validator.validate("[" + UK_POUND + "1,234.567]", pattern)); assertEquals("no symbol +ve", expected, validator.validate("1,234.567", pattern)); assertEquals("no symbol -ve", negative, validator.validate("[1,234.567]", pattern)); // Test Pattern & Locale assertEquals("default", expected, validator.validate(US_DOLLAR + "1,234.567", pattern, Locale.US)); assertEquals("negative", negative, validator.validate("[" + US_DOLLAR + "1,234.567]", pattern, Locale.US)); assertEquals("no symbol +ve", expected, validator.validate("1,234.567", pattern, Locale.US)); assertEquals("no symbol -ve", negative, validator.validate("[1,234.567]", pattern, Locale.US)); // invalid assertFalse("invalid symbol", validator.isValid(US_DOLLAR + "1,234.567", pattern)); assertFalse("invalid symbol", validator.isValid(UK_POUND + "1,234.567", pattern, Locale.US)); // Restore the original default Locale.setDefault(origDefault); } } ././@LongLink100644 0 0 147 11711231552 10253 Lustar 0 0 commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/routines/DateValidatorTest.javacommons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/routines/DateValidatorTest.ja100644 765 0 23172 11711227700 34734 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines; import java.util.Date; import java.util.Locale; import java.util.TimeZone; /** * Test Case for DateValidator. * * @version $Revision: 1094751 $ $Date: 2011-04-18 23:17:40 +0200 (Mon, 18 Apr 2011) $ */ public class DateValidatorTest extends AbstractCalendarValidatorTest { private DateValidator dateValidator; /** * Constructor * @param name test name */ public DateValidatorTest(String name) { super(name); } /** * Set Up. * @throws Exception */ protected void setUp() throws Exception { super.setUp(); dateValidator = new DateValidator(); validator = dateValidator; } /** * Test DateValidator validate Methods */ public void testDateValidatorMethods() { Locale.setDefault(Locale.US); Locale locale = Locale.GERMAN; String pattern = "yyyy-MM-dd"; String patternVal = "2005-12-31"; String germanVal = "31 Dez 2005"; String germanPattern = "dd MMM yyyy"; String localeVal = "31.12.2005"; String defaultVal = "12/31/05"; String XXXX = "XXXX"; Date expected = createCalendar(null, 20051231, 0).getTime(); assertEquals("validate(A) default", expected, DateValidator.getInstance().validate(defaultVal)); assertEquals("validate(A) locale ", expected, DateValidator.getInstance().validate(localeVal, locale)); assertEquals("validate(A) pattern", expected, DateValidator.getInstance().validate(patternVal, pattern)); assertEquals("validate(A) both", expected, DateValidator.getInstance().validate(germanVal, germanPattern, Locale.GERMAN)); assertTrue("isValid(A) default", DateValidator.getInstance().isValid(defaultVal)); assertTrue("isValid(A) locale ", DateValidator.getInstance().isValid(localeVal, locale)); assertTrue("isValid(A) pattern", DateValidator.getInstance().isValid(patternVal, pattern)); assertTrue("isValid(A) both", DateValidator.getInstance().isValid(germanVal, germanPattern, Locale.GERMAN)); assertNull("validate(B) default", DateValidator.getInstance().validate(XXXX)); assertNull("validate(B) locale ", DateValidator.getInstance().validate(XXXX, locale)); assertNull("validate(B) pattern", DateValidator.getInstance().validate(XXXX, pattern)); assertNull("validate(B) both", DateValidator.getInstance().validate("31 Dec 2005", germanPattern, Locale.GERMAN)); assertFalse("isValid(B) default", DateValidator.getInstance().isValid(XXXX)); assertFalse("isValid(B) locale ", DateValidator.getInstance().isValid(XXXX, locale)); assertFalse("isValid(B) pattern", DateValidator.getInstance().isValid(XXXX, pattern)); assertFalse("isValid(B) both", DateValidator.getInstance().isValid("31 Dec 2005", germanPattern, Locale.GERMAN)); // Test Time Zone TimeZone zone = (TimeZone.getDefault().getRawOffset() == EET.getRawOffset() ? EST : EET); Date expectedZone = createCalendar(zone, 20051231, 0).getTime(); assertFalse("default/zone same "+zone, expected.getTime() == expectedZone.getTime()); assertEquals("validate(C) default", expectedZone, DateValidator.getInstance().validate(defaultVal, zone)); assertEquals("validate(C) locale ", expectedZone, DateValidator.getInstance().validate(localeVal, locale, zone)); assertEquals("validate(C) pattern", expectedZone, DateValidator.getInstance().validate(patternVal, pattern, zone)); assertEquals("validate(C) both", expectedZone, DateValidator.getInstance().validate(germanVal, germanPattern, Locale.GERMAN, zone)); } /** * Test compare date methods */ public void testCompare() { int sameTime = 124522; int testDate = 20050823; Date diffHour = createDate(GMT, testDate, 115922); // same date, different time Date value = createDate(GMT, testDate, sameTime); // test value Date date20050824 = createDate(GMT, 20050824, sameTime); // +1 day Date date20050822 = createDate(GMT, 20050822, sameTime); // -1 day Date date20050830 = createDate(GMT, 20050830, sameTime); // +1 week Date date20050816 = createDate(GMT, 20050816, sameTime); // -1 week Date date20050901 = createDate(GMT, 20050901, sameTime); // +1 month Date date20050801 = createDate(GMT, 20050801, sameTime); // same month Date date20050731 = createDate(GMT, 20050731, sameTime); // -1 month Date date20051101 = createDate(GMT, 20051101, sameTime); // +1 quarter (Feb Start) Date date20051001 = createDate(GMT, 20051001, sameTime); // +1 quarter Date date20050701 = createDate(GMT, 20050701, sameTime); // same quarter Date date20050630 = createDate(GMT, 20050630, sameTime); // -1 quarter Date date20050110 = createDate(GMT, 20050110, sameTime); // Previous Year qtr (Fen start) Date date20060101 = createDate(GMT, 20060101, sameTime); // +1 year Date date20050101 = createDate(GMT, 20050101, sameTime); // same year Date date20041231 = createDate(GMT, 20041231, sameTime); // -1 year assertEquals("date LT", -1, dateValidator.compareDates(value, date20050824, null)); // +1 day assertEquals("date EQ", 0, dateValidator.compareDates(value, diffHour, null)); // same day, diff hour assertEquals("date GT", 1, dateValidator.compareDates(value, date20050822, null)); // -1 day assertEquals("week LT", -1, dateValidator.compareWeeks(value, date20050830, null)); // +1 week assertEquals("week =1", 0, dateValidator.compareWeeks(value, date20050824, null)); // +1 day assertEquals("week =2", 0, dateValidator.compareWeeks(value, date20050822, null)); // same week assertEquals("week =3", 0, dateValidator.compareWeeks(value, date20050822, null)); // -1 day assertEquals("week GT", 1, dateValidator.compareWeeks(value, date20050816, null)); // -1 week assertEquals("mnth LT", -1, dateValidator.compareMonths(value, date20050901, null)); // +1 month assertEquals("mnth =1", 0, dateValidator.compareMonths(value, date20050830, null)); // +1 week assertEquals("mnth =2", 0, dateValidator.compareMonths(value, date20050801, null)); // same month assertEquals("mnth =3", 0, dateValidator.compareMonths(value, date20050816, null)); // -1 week assertEquals("mnth GT", 1, dateValidator.compareMonths(value, date20050731, null)); // -1 month assertEquals("qtrA <1", -1, dateValidator.compareQuarters(value, date20051101, null)); // +1 quarter (Feb) assertEquals("qtrA <2", -1, dateValidator.compareQuarters(value, date20051001, null)); // +1 quarter assertEquals("qtrA =1", 0, dateValidator.compareQuarters(value, date20050901, null)); // +1 month assertEquals("qtrA =2", 0, dateValidator.compareQuarters(value, date20050701, null)); // same quarter assertEquals("qtrA =3", 0, dateValidator.compareQuarters(value, date20050731, null)); // -1 month assertEquals("qtrA GT", 1, dateValidator.compareQuarters(value, date20050630, null)); // -1 quarter // Change quarter 1 to start in Feb assertEquals("qtrB LT", -1, dateValidator.compareQuarters(value, date20051101, null, 2)); // +1 quarter (Feb) assertEquals("qtrB =1", 0, dateValidator.compareQuarters(value, date20051001, null, 2)); // same quarter assertEquals("qtrB =2", 0, dateValidator.compareQuarters(value, date20050901, null, 2)); // +1 month assertEquals("qtrB =3", 1, dateValidator.compareQuarters(value, date20050701, null, 2)); // same quarter assertEquals("qtrB =4", 1, dateValidator.compareQuarters(value, date20050731, null, 2)); // -1 month assertEquals("qtrB GT", 1, dateValidator.compareQuarters(value, date20050630, null, 2)); // -1 quarter assertEquals("qtrB prev", 1, dateValidator.compareQuarters(value, date20050110, null, 2)); // Jan Prev year qtr assertEquals("year LT", -1, dateValidator.compareYears(value, date20060101, null)); // +1 year assertEquals("year EQ", 0, dateValidator.compareYears(value, date20050101, null)); // same year assertEquals("year GT", 1, dateValidator.compareYears(value, date20041231, null)); // -1 year // Compare using alternative TimeZone Date sameDayTwoAm = createDate(GMT, testDate, 20000); assertEquals("date LT", -1, dateValidator.compareDates(value, date20050824, EST)); // +1 day assertEquals("date EQ", 0, dateValidator.compareDates(value, diffHour, EST)); // same day, diff hour assertEquals("date EQ", 1, dateValidator.compareDates(value, sameDayTwoAm, EST)); // same day, diff hour assertEquals("date GT", 1, dateValidator.compareDates(value, date20050822, EST)); // -1 day } } ././@LongLink100644 0 0 151 11711231552 10246 Lustar 0 0 commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/routines/DomainValidatorTest.javacommons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/routines/DomainValidatorTest.100644 765 0 13165 11711227700 34754 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines; import junit.framework.TestCase; /** * Tests for the DomainValidator. * * @version $Revision: 1128456 $ $Date: 2011-05-27 23:04:29 +0200 (Fri, 27 May 2011) $ */ public class DomainValidatorTest extends TestCase { private DomainValidator validator; public void setUp() { validator = DomainValidator.getInstance(); } public void testValidDomains() { assertTrue("apache.org should validate", validator.isValid("apache.org")); assertTrue("www.google.com should validate", validator.isValid("www.google.com")); assertTrue("test-domain.com should validate", validator.isValid("test-domain.com")); assertTrue("test---domain.com should validate", validator.isValid("test---domain.com")); assertTrue("test-d-o-m-ain.com should validate", validator.isValid("test-d-o-m-ain.com")); assertTrue("two-letter domain label should validate", validator.isValid("as.uk")); assertTrue("case-insensitive ApAchE.Org should validate", validator.isValid("ApAchE.Org")); assertTrue("single-character domain label should validate", validator.isValid("z.com")); assertTrue("i.have.an-example.domain.name should validate", validator.isValid("i.have.an-example.domain.name")); } public void testInvalidDomains() { assertFalse("bare TLD .org shouldn't validate", validator.isValid(".org")); assertFalse("domain name with spaces shouldn't validate", validator.isValid(" apache.org ")); assertFalse("domain name containing spaces shouldn't validate", validator.isValid("apa che.org")); assertFalse("domain name starting with dash shouldn't validate", validator.isValid("-testdomain.name")); assertFalse("domain name ending with dash shouldn't validate", validator.isValid("testdomain-.name")); assertFalse("domain name starting with multiple dashes shouldn't validate", validator.isValid("---c.com")); assertFalse("domain name ending with multiple dashes shouldn't validate", validator.isValid("c--.com")); assertFalse("domain name with invalid TLD shouldn't validate", validator.isValid("apache.rog")); assertFalse("URL shouldn't validate", validator.isValid("http://www.apache.org")); assertFalse("Empty string shouldn't validate as domain name", validator.isValid(" ")); assertFalse("Null shouldn't validate as domain name", validator.isValid(null)); } public void testTopLevelDomains() { // infrastructure TLDs assertTrue(".arpa should validate as iTLD", validator.isValidInfrastructureTld(".arpa")); assertFalse(".com shouldn't validate as iTLD", validator.isValidInfrastructureTld(".com")); // generic TLDs assertTrue(".name should validate as gTLD", validator.isValidGenericTld(".name")); assertFalse(".us shouldn't validate as gTLD", validator.isValidGenericTld(".us")); // country code TLDs assertTrue(".uk should validate as ccTLD", validator.isValidCountryCodeTld(".uk")); assertFalse(".org shouldn't validate as ccTLD", validator.isValidCountryCodeTld(".org")); // case-insensitive assertTrue(".COM should validate as TLD", validator.isValidTld(".COM")); assertTrue(".BiZ should validate as TLD", validator.isValidTld(".BiZ")); // corner cases assertFalse("invalid TLD shouldn't validate", validator.isValid(".nope")); assertFalse("empty string shouldn't validate as TLD", validator.isValid("")); assertFalse("null shouldn't validate as TLD", validator.isValid(null)); } public void testAllowLocal() { DomainValidator noLocal = DomainValidator.getInstance(false); DomainValidator allowLocal = DomainValidator.getInstance(true); // Default is false, and should use singletons assertEquals(noLocal, validator); // Default won't allow local assertFalse("localhost.localdomain should validate", noLocal.isValid("localhost.localdomain")); assertFalse("localhost should validate", noLocal.isValid("localhost")); // But it may be requested assertTrue("localhost.localdomain should validate", allowLocal.isValid("localhost.localdomain")); assertTrue("localhost should validate", allowLocal.isValid("localhost")); assertTrue("hostname should validate", allowLocal.isValid("hostname")); assertTrue("machinename should validate", allowLocal.isValid("machinename")); // Check the localhost one with a few others assertTrue("apache.org should validate", allowLocal.isValid("apache.org")); assertFalse("domain name with spaces shouldn't validate", allowLocal.isValid(" apache.org ")); } public void testIDN() { assertTrue("b\u00fccher.ch in IDN should validate", validator.isValid("www.xn--bcher-kva.ch")); } } ././@LongLink100644 0 0 151 11711231552 10246 Lustar 0 0 commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/routines/DoubleValidatorTest.javacommons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/routines/DoubleValidatorTest.100644 765 0 13711 11711227700 34754 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines; import java.util.Locale; /** * Test Case for DoubleValidator. * * @version $Revision: 1094751 $ $Date: 2011-04-18 23:17:40 +0200 (Mon, 18 Apr 2011) $ */ public class DoubleValidatorTest extends AbstractNumberValidatorTest { /** * Constructor * @param name test name */ public DoubleValidatorTest(String name) { super(name); } protected void setUp() throws Exception { super.setUp(); validator = new DoubleValidator(false, 0); strictValidator = new DoubleValidator(); testPattern = "#,###.#"; // testValidateMinMax() max = null; maxPlusOne = null; min = null; minMinusOne = null; // testInvalidStrict() invalidStrict = new String[] {null, "", "X", "X12", "12X", "1X2"}; // testInvalidNotStrict() invalid = new String[] {null, "", "X", "X12"}; // testValid() testNumber = new Double(1234.5); testZero = new Double(0); validStrict = new String[] {"0", "1234.5", "1,234.5"}; validStrictCompare = new Number[] {testZero, testNumber, testNumber}; valid = new String[] {"0", "1234.5", "1,234.5", "1,234.5", "1234.5X"}; validCompare = new Number[] {testZero, testNumber, testNumber, testNumber, testNumber}; testStringUS = "1,234.5"; testStringDE = "1.234,5"; // Localized Pattern test localeValue = testStringDE; localePattern = "#.###,#"; testLocale = Locale.GERMANY; localeExpected = testNumber; } /** * Test DoubleValidator validate Methods */ public void testDoubleValidatorMethods() { Locale locale = Locale.GERMAN; String pattern = "0,00,00"; String patternVal = "1,23,45"; String germanPatternVal = "1.23.45"; String localeVal = "12.345"; String defaultVal = "12,345"; String XXXX = "XXXX"; Double expected = new Double(12345); assertEquals("validate(A) default", expected, DoubleValidator.getInstance().validate(defaultVal)); assertEquals("validate(A) locale ", expected, DoubleValidator.getInstance().validate(localeVal, locale)); assertEquals("validate(A) pattern", expected, DoubleValidator.getInstance().validate(patternVal, pattern)); assertEquals("validate(A) both", expected, DoubleValidator.getInstance().validate(germanPatternVal, pattern, Locale.GERMAN)); assertTrue("isValid(A) default", DoubleValidator.getInstance().isValid(defaultVal)); assertTrue("isValid(A) locale ", DoubleValidator.getInstance().isValid(localeVal, locale)); assertTrue("isValid(A) pattern", DoubleValidator.getInstance().isValid(patternVal, pattern)); assertTrue("isValid(A) both", DoubleValidator.getInstance().isValid(germanPatternVal, pattern, Locale.GERMAN)); assertNull("validate(B) default", DoubleValidator.getInstance().validate(XXXX)); assertNull("validate(B) locale ", DoubleValidator.getInstance().validate(XXXX, locale)); assertNull("validate(B) pattern", DoubleValidator.getInstance().validate(XXXX, pattern)); assertNull("validate(B) both", DoubleValidator.getInstance().validate(patternVal, pattern, Locale.GERMAN)); assertFalse("isValid(B) default", DoubleValidator.getInstance().isValid(XXXX)); assertFalse("isValid(B) locale ", DoubleValidator.getInstance().isValid(XXXX, locale)); assertFalse("isValid(B) pattern", DoubleValidator.getInstance().isValid(XXXX, pattern)); assertFalse("isValid(B) both", DoubleValidator.getInstance().isValid(patternVal, pattern, Locale.GERMAN)); } /** * Test Double Range/Min/Max */ public void testDoubleRangeMinMax() { DoubleValidator validator = (DoubleValidator)strictValidator; Double number9 = validator.validate("9", "#"); Double number10 = validator.validate("10", "#"); Double number11 = validator.validate("11", "#"); Double number19 = validator.validate("19", "#"); Double number20 = validator.validate("20", "#"); Double number21 = validator.validate("21", "#"); // Test isInRange() assertFalse("isInRange() < min", validator.isInRange(number9, 10, 20)); assertTrue("isInRange() = min", validator.isInRange(number10, 10, 20)); assertTrue("isInRange() in range", validator.isInRange(number11, 10, 20)); assertTrue("isInRange() = max", validator.isInRange(number20, 10, 20)); assertFalse("isInRange() > max", validator.isInRange(number21, 10, 20)); // Test minValue() assertFalse("minValue() < min", validator.minValue(number9, 10)); assertTrue("minValue() = min", validator.minValue(number10, 10)); assertTrue("minValue() > min", validator.minValue(number11, 10)); // Test minValue() assertTrue("maxValue() < max", validator.maxValue(number19, 20)); assertTrue("maxValue() = max", validator.maxValue(number20, 20)); assertFalse("maxValue() > max", validator.maxValue(number21, 20)); } } ././@LongLink100644 0 0 150 11711231552 10245 Lustar 0 0 commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/routines/EmailValidatorTest.javacommons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/routines/EmailValidatorTest.j100644 765 0 40605 11711227700 34745 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines; import junit.framework.TestCase; import org.apache.commons.validator.ResultPair; /** * Performs Validation Test for e-mail validations. * * * @version $Revision: 1207110 $ $Date: 2011-11-28 13:42:01 +0100 (Mon, 28 Nov 2011) $ */ public class EmailValidatorTest extends TestCase { /** * The key used to retrieve the set of validation * rules from the xml file. */ protected static String FORM_KEY = "emailForm"; /** * The key used to retrieve the validator action. */ protected static String ACTION = "email"; private EmailValidator validator; public EmailValidatorTest(String name) { super(name); } protected void setUp() { validator = EmailValidator.getInstance(); } protected void tearDown() { } /** * Tests the e-mail validation. */ public void testEmail() { assertTrue(validator.isValid("jsmith@apache.org")); } /** * Tests the email validation with numeric domains. */ public void testEmailWithNumericAddress() { assertTrue(validator.isValid("someone@[216.109.118.76]")); assertTrue(validator.isValid("someone@yahoo.com")); } /** * Tests the e-mail validation. */ public void testEmailExtension() { assertTrue(validator.isValid("jsmith@apache.org")); assertTrue(validator.isValid("jsmith@apache.com")); assertTrue(validator.isValid("jsmith@apache.net")); assertTrue(validator.isValid("jsmith@apache.info")); assertFalse(validator.isValid("jsmith@apache.")); assertFalse(validator.isValid("jsmith@apache.c")); assertTrue(validator.isValid("someone@yahoo.museum")); assertFalse(validator.isValid("someone@yahoo.mu-seum")); } /** *

    Tests the e-mail validation with a dash in * the address.

    */ public void testEmailWithDash() { assertTrue(validator.isValid("andy.noble@data-workshop.com")); assertFalse(validator.isValid("andy-noble@data-workshop.-com")); assertFalse(validator.isValid("andy-noble@data-workshop.c-om")); assertFalse(validator.isValid("andy-noble@data-workshop.co-m")); } /** * Tests the e-mail validation with a dot at the end of * the address. */ public void testEmailWithDotEnd() { assertFalse(validator.isValid("andy.noble@data-workshop.com.")); } /** * Tests the e-mail validation with an RCS-noncompliant character in * the address. */ public void testEmailWithBogusCharacter() { assertFalse(validator.isValid("andy.noble@\u008fdata-workshop.com")); // The ' character is valid in an email username. assertTrue(validator.isValid("andy.o'reilly@data-workshop.com")); // But not in the domain name. assertFalse(validator.isValid("andy@o'reilly.data-workshop.com")); // The + character is valid in an email username. assertTrue(validator.isValid("foo+bar@i.am.not.in.us.example.com")); // But not in the domain name assertFalse(validator.isValid("foo+bar@example+3.com")); // Domains with only special characters aren't allowed (VALIDATOR-286) assertFalse(validator.isValid("test@%*.com")); assertFalse(validator.isValid("test@^&#.com")); } /** * Tests the email validation with commas. */ public void testEmailWithCommas() { assertFalse(validator.isValid("joeblow@apa,che.org")); assertFalse(validator.isValid("joeblow@apache.o,rg")); assertFalse(validator.isValid("joeblow@apache,org")); } /** * Tests the email validation with spaces. */ public void testEmailWithSpaces() { assertFalse(validator.isValid("joeblow @apache.org")); // TODO - this should be valid? assertFalse(validator.isValid("joeblow@ apache.org")); assertTrue(validator.isValid(" joeblow@apache.org")); // TODO - this should be valid? assertTrue(validator.isValid("joeblow@apache.org ")); assertFalse(validator.isValid("joe blow@apache.org ")); assertFalse(validator.isValid("joeblow@apa che.org ")); } /** * Tests the email validation with ascii control characters. * (i.e. Ascii chars 0 - 31 and 127) */ public void testEmailWithControlChars() { for (char c = 0; c < 32; c++) { assertFalse("Test control char " + ((int)c), validator.isValid("foo" + c + "bar@domain.com")); } assertFalse("Test control char 127", validator.isValid("foo" + ((char)127) + "bar@domain.com")); } /** * Test that @localhost and @localhost.localdomain * addresses are declared as valid when requested. */ public void testEmailLocalhost() { // Check the default is not to allow EmailValidator noLocal = EmailValidator.getInstance(false); EmailValidator allowLocal = EmailValidator.getInstance(true); assertEquals(validator, noLocal); // Depends on the validator assertTrue( "@localhost.localdomain should be accepted but wasn't", allowLocal.isValid("joe@localhost.localdomain") ); assertTrue( "@localhost should be accepted but wasn't", allowLocal.isValid("joe@localhost") ); assertFalse( "@localhost.localdomain should be accepted but wasn't", noLocal.isValid("joe@localhost.localdomain") ); assertFalse( "@localhost should be accepted but wasn't", noLocal.isValid("joe@localhost") ); } /** * VALIDATOR-296 - A / or a ! is valid in the user part, * but not in the domain part */ public void testEmailWithSlashes() { assertTrue( "/ and ! valid in username", validator.isValid("joe!/blow@apache.org") ); assertFalse( "/ not valid in domain", validator.isValid("joe@ap/ache.org") ); assertFalse( "! not valid in domain", validator.isValid("joe@apac!he.org") ); } /** * Write this test according to parts of RFC, as opposed to the type of character * that is being tested. */ public void testEmailUserName() { assertTrue(validator.isValid("joe1blow@apache.org")); assertTrue(validator.isValid("joe$blow@apache.org")); assertTrue(validator.isValid("joe-@apache.org")); assertTrue(validator.isValid("joe_@apache.org")); assertTrue(validator.isValid("joe+@apache.org")); // + is valid unquoted assertTrue(validator.isValid("joe!@apache.org")); // ! is valid unquoted assertTrue(validator.isValid("joe*@apache.org")); // * is valid unquoted assertTrue(validator.isValid("joe'@apache.org")); // ' is valid unquoted assertTrue(validator.isValid("joe%45@apache.org")); // % is valid unquoted assertTrue(validator.isValid("joe?@apache.org")); // ? is valid unquoted assertTrue(validator.isValid("joe&@apache.org")); // & ditto assertTrue(validator.isValid("joe=@apache.org")); // = ditto assertTrue(validator.isValid("+joe@apache.org")); // + is valid unquoted assertTrue(validator.isValid("!joe@apache.org")); // ! is valid unquoted assertTrue(validator.isValid("*joe@apache.org")); // * is valid unquoted assertTrue(validator.isValid("'joe@apache.org")); // ' is valid unquoted assertTrue(validator.isValid("%joe45@apache.org")); // % is valid unquoted assertTrue(validator.isValid("?joe@apache.org")); // ? is valid unquoted assertTrue(validator.isValid("&joe@apache.org")); // & ditto assertTrue(validator.isValid("=joe@apache.org")); // = ditto assertTrue(validator.isValid("+@apache.org")); // + is valid unquoted assertTrue(validator.isValid("!@apache.org")); // ! is valid unquoted assertTrue(validator.isValid("*@apache.org")); // * is valid unquoted assertTrue(validator.isValid("'@apache.org")); // ' is valid unquoted assertTrue(validator.isValid("%@apache.org")); // % is valid unquoted assertTrue(validator.isValid("?@apache.org")); // ? is valid unquoted assertTrue(validator.isValid("&@apache.org")); // & ditto assertTrue(validator.isValid("=@apache.org")); // = ditto //UnQuoted Special characters are invalid assertFalse(validator.isValid("joe.@apache.org")); // . not allowed at end of local part assertFalse(validator.isValid(".joe@apache.org")); // . not allowed at start of local part assertFalse(validator.isValid(".@apache.org")); // . not allowed alone assertTrue(validator.isValid("joe.ok@apache.org")); // . allowed embedded assertFalse(validator.isValid("joe..ok@apache.org")); // .. not allowed embedded assertFalse(validator.isValid("..@apache.org")); // .. not allowed alone assertFalse(validator.isValid("joe(@apache.org")); assertFalse(validator.isValid("joe)@apache.org")); assertFalse(validator.isValid("joe,@apache.org")); assertFalse(validator.isValid("joe;@apache.org")); //Quoted Special characters are valid assertTrue(validator.isValid("\"joe.\"@apache.org")); assertTrue(validator.isValid("\".joe\"@apache.org")); assertTrue(validator.isValid("\"joe+\"@apache.org")); assertTrue(validator.isValid("\"joe!\"@apache.org")); assertTrue(validator.isValid("\"joe*\"@apache.org")); assertTrue(validator.isValid("\"joe'\"@apache.org")); assertTrue(validator.isValid("\"joe(\"@apache.org")); assertTrue(validator.isValid("\"joe)\"@apache.org")); assertTrue(validator.isValid("\"joe,\"@apache.org")); assertTrue(validator.isValid("\"joe%45\"@apache.org")); assertTrue(validator.isValid("\"joe;\"@apache.org")); assertTrue(validator.isValid("\"joe?\"@apache.org")); assertTrue(validator.isValid("\"joe&\"@apache.org")); assertTrue(validator.isValid("\"joe=\"@apache.org")); assertTrue(validator.isValid("\"..\"@apache.org")); } /** * These test values derive directly from RFC 822 & * Mail::RFC822::Address & RFC::RFC822::Address perl test.pl * For traceability don't combine these test values with other tests. */ private static final ResultPair[] testEmailFromPerl = { new ResultPair("abigail@example.com", true), new ResultPair("abigail@example.com ", true), new ResultPair(" abigail@example.com", true), new ResultPair("abigail @example.com ", true), new ResultPair("*@example.net", true), new ResultPair("\"\\\"\"@foo.bar", true), new ResultPair("fred&barny@example.com", true), new ResultPair("---@example.com", true), new ResultPair("foo-bar@example.net", true), new ResultPair("\"127.0.0.1\"@[127.0.0.1]", true), new ResultPair("Abigail ", true), new ResultPair("Abigail", true), new ResultPair("Abigail<@a,@b,@c:abigail@example.com>", true), new ResultPair("\"This is a phrase\"", true), new ResultPair("\"Abigail \"", true), new ResultPair("\"Joe & J. Harvey\" ", true), new ResultPair("Abigail ", true), new ResultPair("Abigail made this < abigail @ example . com >", true), new ResultPair("Abigail(the bitch)@example.com", true), new ResultPair("Abigail ", true), new ResultPair("Abigail < (one) abigail (two) @(three)example . (bar) com (quz) >", true), new ResultPair("Abigail (foo) (((baz)(nested) (comment)) ! ) < (one) abigail (two) @(three)example . (bar) com (quz) >", true), new ResultPair("Abigail ", true), new ResultPair("Abigail ", true), new ResultPair("(foo) abigail@example.com", true), new ResultPair("abigail@example.com (foo)", true), new ResultPair("\"Abi\\\"gail\" ", true), new ResultPair("abigail@[example.com]", true), new ResultPair("abigail@[exa\\[ple.com]", true), new ResultPair("abigail@[exa\\]ple.com]", true), new ResultPair("\":sysmail\"@ Some-Group. Some-Org", true), new ResultPair("Muhammed.(I am the greatest) Ali @(the)Vegas.WBA", true), new ResultPair("mailbox.sub1.sub2@this-domain", true), new ResultPair("sub-net.mailbox@sub-domain.domain", true), new ResultPair("name:;", true), new ResultPair("':;", true), new ResultPair("name: ;", true), new ResultPair("Alfred Neuman ", true), new ResultPair("Neuman@BBN-TENEXA", true), new ResultPair("\"George, Ted\" ", true), new ResultPair("Wilt . (the Stilt) Chamberlain@NBA.US", true), new ResultPair("Cruisers: Port@Portugal, Jones@SEA;", true), new ResultPair("$@[]", true), new ResultPair("*()@[]", true), new ResultPair("\"quoted ( brackets\" ( a comment )@example.com", true), new ResultPair("\"Joe & J. Harvey\"\\x0D\\x0A ", true), new ResultPair("\"Joe &\\x0D\\x0A J. Harvey\" ", true), new ResultPair("Gourmets: Pompous Person ,\\x0D\\x0A" + " Childs\\@WGBH.Boston, \"Galloping Gourmet\"\\@\\x0D\\x0A" + " ANT.Down-Under (Australian National Television),\\x0D\\x0A" + " Cheapie\\@Discount-Liquors;", true), new ResultPair(" Just a string", false), new ResultPair("string", false), new ResultPair("(comment)", false), new ResultPair("()@example.com", false), new ResultPair("fred(&)barny@example.com", false), new ResultPair("fred\\ barny@example.com", false), new ResultPair("Abigail ", false), new ResultPair("Abigail ", false), new ResultPair("Abigail ", false), new ResultPair("\"Abi\"gail\" ", false), new ResultPair("abigail@[exa]ple.com]", false), new ResultPair("abigail@[exa[ple.com]", false), new ResultPair("abigail@[exaple].com]", false), new ResultPair("abigail@", false), new ResultPair("@example.com", false), new ResultPair("phrase: abigail@example.com abigail@example.com ;", false), new ResultPair("invalid�char@example.com", false) }; /** * Write this test based on perl Mail::RFC822::Address * which takes its example email address directly from RFC822 * * FIXME This test fails so disable it with a leading _ for 1.1.4 release. * The real solution is to fix the email parsing. */ public void _testEmailFromPerl() { for (int index = 0; index < testEmailFromPerl.length; index++) { String item = testEmailFromPerl[index].item; if (testEmailFromPerl[index].valid) { assertTrue("Should be OK: "+item, validator.isValid(item)); } else { assertFalse("Should fail: "+item, validator.isValid(item)); } } } public void testValidator293(){ assertTrue(validator.isValid("abc-@abc.com")); assertTrue(validator.isValid("abc_@abc.com")); assertTrue(validator.isValid("abc-def@abc.com")); assertTrue(validator.isValid("abc_def@abc.com")); assertFalse(validator.isValid("abc@abc_def.com")); } } ././@LongLink100644 0 0 150 11711231552 10245 Lustar 0 0 commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/routines/FloatValidatorTest.javacommons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/routines/FloatValidatorTest.j100644 765 0 17052 11711227700 34763 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines; import java.text.DecimalFormat; import java.util.Locale; /** * Test Case for FloatValidator. * * @version $Revision: 1094808 $ $Date: 2011-04-19 00:57:51 +0200 (Tue, 19 Apr 2011) $ */ public class FloatValidatorTest extends AbstractNumberValidatorTest { /** * Constructor * @param name test name */ public FloatValidatorTest(String name) { super(name); } protected void setUp() throws Exception { super.setUp(); validator = new FloatValidator(false, 0); strictValidator = new FloatValidator(); testPattern = "#,###.#"; // testValidateMinMax() max = new Float(Float.MAX_VALUE); maxPlusOne = new Double(max.doubleValue() * 10); min = new Float(Float.MAX_VALUE * -1); minMinusOne = new Double(min.doubleValue() * 10); // testInvalidStrict() invalidStrict = new String[] {null, "", "X", "X12", "12X", "1X2"}; // testInvalidNotStrict() invalid = new String[] {null, "", "X", "X12"}; // testValid() testNumber = new Float(1234.5); testZero = new Float(0); validStrict = new String[] {"0", "1234.5", "1,234.5"}; validStrictCompare = new Number[] {testZero, testNumber, testNumber}; valid = new String[] {"0", "1234.5", "1,234.5", "1,234.5", "1234.5X"}; validCompare = new Number[] {testZero, testNumber, testNumber, testNumber, testNumber}; testStringUS = "1,234.5"; testStringDE = "1.234,5"; // Localized Pattern test localeValue = testStringDE; localePattern = "#.###,#"; testLocale = Locale.GERMANY; localeExpected = testNumber; } /** * Test FloatValidator validate Methods */ public void testFloatValidatorMethods() { Locale locale = Locale.GERMAN; String pattern = "0,00,00"; String patternVal = "1,23,45"; String localeVal = "12.345"; String germanPatternVal = "1.23.45"; String defaultVal = "12,345"; String XXXX = "XXXX"; Float expected = new Float(12345); assertEquals("validate(A) default", expected, FloatValidator.getInstance().validate(defaultVal)); assertEquals("validate(A) locale ", expected, FloatValidator.getInstance().validate(localeVal, locale)); assertEquals("validate(A) pattern", expected, FloatValidator.getInstance().validate(patternVal, pattern)); assertEquals("validate(A) both", expected, FloatValidator.getInstance().validate(germanPatternVal, pattern, Locale.GERMAN)); assertTrue("isValid(A) default", FloatValidator.getInstance().isValid(defaultVal)); assertTrue("isValid(A) locale ", FloatValidator.getInstance().isValid(localeVal, locale)); assertTrue("isValid(A) pattern", FloatValidator.getInstance().isValid(patternVal, pattern)); assertTrue("isValid(A) both", FloatValidator.getInstance().isValid(germanPatternVal, pattern, Locale.GERMAN)); assertNull("validate(B) default", FloatValidator.getInstance().validate(XXXX)); assertNull("validate(B) locale ", FloatValidator.getInstance().validate(XXXX, locale)); assertNull("validate(B) pattern", FloatValidator.getInstance().validate(XXXX, pattern)); assertNull("validate(B) both", FloatValidator.getInstance().validate(patternVal, pattern, Locale.GERMAN)); assertFalse("isValid(B) default", FloatValidator.getInstance().isValid(XXXX)); assertFalse("isValid(B) locale ", FloatValidator.getInstance().isValid(XXXX, locale)); assertFalse("isValid(B) pattern", FloatValidator.getInstance().isValid(XXXX, pattern)); assertFalse("isValid(B) both", FloatValidator.getInstance().isValid(patternVal, pattern, Locale.GERMAN)); } /** * Test Float validation for values too small to handle. * (slightly different from max/min which are the largest +ve/-ve */ public void testFloatSmallestValues() { String pattern = "#.#################################################################"; DecimalFormat fmt = new DecimalFormat(pattern); // Validate Smallest +ve value Float smallestPositive = new Float(Float.MIN_VALUE); String strSmallestPositive = fmt.format(smallestPositive); assertEquals("Smallest +ve", smallestPositive, FloatValidator.getInstance().validate(strSmallestPositive, pattern)); // Validate Smallest -ve value Float smallestNegative = new Float(Float.MIN_VALUE * -1); String strSmallestNegative = fmt.format(smallestNegative); assertEquals("Smallest -ve", smallestNegative, FloatValidator.getInstance().validate(strSmallestNegative, pattern)); // Validate Too Small +ve Double tooSmallPositive = new Double(((double)Float.MIN_VALUE / (double)10)); String strTooSmallPositive = fmt.format(tooSmallPositive); assertFalse("Too small +ve", FloatValidator.getInstance().isValid(strTooSmallPositive, pattern)); // Validate Too Small -ve Double tooSmallNegative = new Double(tooSmallPositive.doubleValue() * -1); String strTooSmallNegative = fmt.format(tooSmallNegative); assertFalse("Too small -ve", FloatValidator.getInstance().isValid(strTooSmallNegative, pattern)); } /** * Test Float Range/Min/Max */ public void testFloatRangeMinMax() { FloatValidator validator = (FloatValidator)strictValidator; Float number9 = validator.validate("9", "#"); Float number10 = validator.validate("10", "#"); Float number11 = validator.validate("11", "#"); Float number19 = validator.validate("19", "#"); Float number20 = validator.validate("20", "#"); Float number21 = validator.validate("21", "#"); // Test isInRange() assertFalse("isInRange() < min", validator.isInRange(number9, 10, 20)); assertTrue("isInRange() = min", validator.isInRange(number10, 10, 20)); assertTrue("isInRange() in range", validator.isInRange(number11, 10, 20)); assertTrue("isInRange() = max", validator.isInRange(number20, 10, 20)); assertFalse("isInRange() > max", validator.isInRange(number21, 10, 20)); // Test minValue() assertFalse("minValue() < min", validator.minValue(number9, 10)); assertTrue("minValue() = min", validator.minValue(number10, 10)); assertTrue("minValue() > min", validator.minValue(number11, 10)); // Test minValue() assertTrue("maxValue() < max", validator.maxValue(number19, 20)); assertTrue("maxValue() = max", validator.maxValue(number20, 20)); assertFalse("maxValue() > max", validator.maxValue(number21, 20)); } } ././@LongLink100644 0 0 147 11711231552 10253 Lustar 0 0 commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/routines/ISBNValidatorTest.javacommons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/routines/ISBNValidatorTest.ja100644 765 0 36441 11711227700 34615 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines; import java.util.regex.Pattern; import junit.framework.TestCase; /** * ISBNValidator Test Case. * * @version $Revision: 493905 $ $Date: 2007-01-08 03:11:38 +0100 (Mon, 08 Jan 2007) $ */ public class ISBNValidatorTest extends TestCase { private String[] validISBN10Format = new String[] { "1234567890", "123456789X", "12345-1234567-123456-X", "12345 1234567 123456 X", "1-2-3-4", "1 2 3 4", }; private String[] invalidISBN10Format = new String[] { "", // empty " ", // empty "1", // too short "123456789", // too short "12345678901", // too long "12345678X0", // X not at end "123456-1234567-123456-X", // Group too long "12345-12345678-123456-X", // Publisher too long "12345-1234567-1234567-X", // Title too long "12345-1234567-123456-X2", // Check Digit too long "--1 930110 99 5", // format "1 930110 99 5--", // format "1 930110-99 5-", // format "1.2.3.4", // Invalid Separator "1=2=3=4", // Invalid Separator "1_2_3_4", // Invalid Separator "123456789Y", // Other character at the end "dsasdsadsa", // invalid characters "I love sparrows!", // invalid characters "068-556-98-45" // format }; private String[] validISBN13Format = new String[] { "9781234567890", "9791234567890", "978-12345-1234567-123456-1", "979-12345-1234567-123456-1", "978 12345 1234567 123456 1", "979 12345 1234567 123456 1", "978-1-2-3-4", "979-1-2-3-4", "978 1 2 3 4", "979 1 2 3 4", }; private String[] invalidISBN13Format = new String[] { "", // empty " ", // empty "1", // too short "978123456789", // too short "97812345678901", // too long "978-123456-1234567-123456-1", // Group too long "978-12345-12345678-123456-1", // Publisher too long "978-12345-1234567-1234567-1", // Title too long "978-12345-1234567-123456-12", // Check Digit too long "--978 1 930110 99 1", // format "978 1 930110 99 1--", // format "978 1 930110-99 1-", // format "123-4-567890-12-8", // format "978.1.2.3.4", // Invalid Separator "978=1=2=3=4", // Invalid Separator "978_1_2_3_4", // Invalid Separator "978123456789X", // invalid character "978-0-201-63385-X", // invalid character "dsasdsadsadsa", // invalid characters "I love sparrows!", // invalid characters "979-1-234-567-89-6" // format }; /** * Create a test case with the specified name. * @param name The name of the test */ public ISBNValidatorTest(String name) { super(name); } /** * Test Valid ISBN-10 formats. */ public void testValidISBN10Format() { Pattern pattern = Pattern.compile(ISBNValidator.ISBN10_REGEX); for (int i = 0; i < validISBN10Format.length; i++) { assertTrue("Pattern[" + i + "]=" + validISBN10Format[i], pattern.matcher(validISBN10Format[i]).matches()); } } /** * Test Invalid ISBN-10 formats. */ public void testInvalidISBN10Format() { ISBNValidator validator = ISBNValidator.getInstance(); Pattern pattern = Pattern.compile(ISBNValidator.ISBN10_REGEX); for (int i = 0; i < invalidISBN10Format.length; i++) { assertFalse("Pattern[" + i + "]=" + invalidISBN10Format[i], pattern.matcher(invalidISBN10Format[i]).matches()); assertFalse("isValidISBN10[" + i + "]=" + invalidISBN10Format[i], validator.isValidISBN10(invalidISBN10Format[i])); assertNull("validateISBN10[" + i + "]=" + invalidISBN10Format[i], validator.validateISBN10(invalidISBN10Format[i])); } } /** * Test Valid ISBN-13 formats. */ public void testValidISBN13Format() { Pattern pattern = Pattern.compile(ISBNValidator.ISBN13_REGEX); for (int i = 0; i < validISBN13Format.length; i++) { assertTrue("Pattern[" + i + "]=" + validISBN13Format[i], pattern.matcher(validISBN13Format[i]).matches()); } } /** * Test Invalid ISBN-13 formats. */ public void testInvalidISBN13Format() { Pattern pattern = Pattern.compile(ISBNValidator.ISBN13_REGEX); ISBNValidator validator = ISBNValidator.getInstance(); for (int i = 0; i < invalidISBN13Format.length; i++) { assertFalse("Pattern[" + i + "]=" + invalidISBN13Format[i], pattern.matcher(invalidISBN13Format[i]).matches()); assertFalse("isValidISBN13[" + i + "]=" + invalidISBN13Format[i], validator.isValidISBN13(invalidISBN13Format[i])); assertNull("validateISBN13[" + i + "]=" + invalidISBN13Format[i], validator.validateISBN13(invalidISBN13Format[i])); } } /** * Test isValid() ISBN-10 codes */ public void testIsValidISBN10() { ISBNValidator validator = ISBNValidator.getInstance(); assertTrue("isValidISBN10-1", validator.isValidISBN10("1930110995")); assertTrue("isValidISBN10-2", validator.isValidISBN10("1-930110-99-5")); assertTrue("isValidISBN10-3", validator.isValidISBN10("1 930110 99 5")); assertTrue("isValidISBN10-4", validator.isValidISBN10("020163385X")); assertTrue("isValidISBN10-5", validator.isValidISBN10("0-201-63385-X")); assertTrue("isValidISBN10-6", validator.isValidISBN10("0 201 63385 X")); assertTrue("isValid-1", validator.isValid("1930110995")); assertTrue("isValid-2", validator.isValid("1-930110-99-5")); assertTrue("isValid-3", validator.isValid("1 930110 99 5")); assertTrue("isValid-4", validator.isValid("020163385X")); assertTrue("isValid-5", validator.isValid("0-201-63385-X")); assertTrue("isValid-6", validator.isValid("0 201 63385 X")); } /** * Test isValid() ISBN-13 codes */ public void testIsValidISBN13() { ISBNValidator validator = ISBNValidator.getInstance(); assertTrue("isValidISBN13-1", validator.isValidISBN13("9781930110991")); assertTrue("isValidISBN13-2", validator.isValidISBN13("978-1-930110-99-1")); assertTrue("isValidISBN13-3", validator.isValidISBN13("978 1 930110 99 1")); assertTrue("isValidISBN13-4", validator.isValidISBN13("9780201633856")); assertTrue("isValidISBN13-5", validator.isValidISBN13("978-0-201-63385-6")); assertTrue("isValidISBN13-6", validator.isValidISBN13("978 0 201 63385 6")); assertTrue("isValid-1", validator.isValid("9781930110991")); assertTrue("isValid-2", validator.isValid("978-1-930110-99-1")); assertTrue("isValid-3", validator.isValid("978 1 930110 99 1")); assertTrue("isValid-4", validator.isValid("9780201633856")); assertTrue("isValid-5", validator.isValid("978-0-201-63385-6")); assertTrue("isValid-6", validator.isValid("978 0 201 63385 6")); } /** * Test validate() ISBN-10 codes (don't convert) */ public void testValidateISBN10() { ISBNValidator validator = ISBNValidator.getInstance(false); assertEquals("validateISBN10-1", "1930110995", validator.validateISBN10("1930110995")); assertEquals("validateISBN10-2", "1930110995", validator.validateISBN10("1-930110-99-5")); assertEquals("validateISBN10-3", "1930110995", validator.validateISBN10("1 930110 99 5")); assertEquals("validateISBN10-4", "020163385X", validator.validateISBN10("020163385X")); assertEquals("validateISBN10-5", "020163385X", validator.validateISBN10("0-201-63385-X")); assertEquals("validateISBN10-6", "020163385X", validator.validateISBN10("0 201 63385 X")); assertEquals("validate-1", "1930110995", validator.validate("1930110995")); assertEquals("validate-2", "1930110995", validator.validate("1-930110-99-5")); assertEquals("validate-3", "1930110995", validator.validate("1 930110 99 5")); assertEquals("validate-4", "020163385X", validator.validate("020163385X")); assertEquals("validate-5", "020163385X", validator.validate("0-201-63385-X")); assertEquals("validate-6", "020163385X", validator.validate("0 201 63385 X")); } /** * Test validate() ISBN-10 codes (convert) */ public void testValidateISBN10Convert() { ISBNValidator validator = ISBNValidator.getInstance(); assertEquals("validate-1", "9781930110991", validator.validate("1930110995")); assertEquals("validate-2", "9781930110991", validator.validate("1-930110-99-5")); assertEquals("validate-3", "9781930110991", validator.validate("1 930110 99 5")); assertEquals("validate-4", "9780201633856", validator.validate("020163385X")); assertEquals("validate-5", "9780201633856", validator.validate("0-201-63385-X")); assertEquals("validate-6", "9780201633856", validator.validate("0 201 63385 X")); } /** * Test validate() ISBN-13 codes */ public void testValidateISBN13() { ISBNValidator validator = ISBNValidator.getInstance(); assertEquals("validateISBN13-1", "9781930110991", validator.validateISBN13("9781930110991")); assertEquals("validateISBN13-2", "9781930110991", validator.validateISBN13("978-1-930110-99-1")); assertEquals("validateISBN13-3", "9781930110991", validator.validateISBN13("978 1 930110 99 1")); assertEquals("validateISBN13-4", "9780201633856", validator.validateISBN13("9780201633856")); assertEquals("validateISBN13-5", "9780201633856", validator.validateISBN13("978-0-201-63385-6")); assertEquals("validateISBN13-6", "9780201633856", validator.validateISBN13("978 0 201 63385 6")); assertEquals("validate-1", "9781930110991", validator.validate("9781930110991")); assertEquals("validate-2", "9781930110991", validator.validate("978-1-930110-99-1")); assertEquals("validate-3", "9781930110991", validator.validate("978 1 930110 99 1")); assertEquals("validate-4", "9780201633856", validator.validate("9780201633856")); assertEquals("validate-5", "9780201633856", validator.validate("978-0-201-63385-6")); assertEquals("validate-6", "9780201633856", validator.validate("978 0 201 63385 6")); } /** * Test null values */ public void testNull() { ISBNValidator validator = ISBNValidator.getInstance(); assertFalse("isValid", validator.isValid(null)); assertFalse("isValidISBN10", validator.isValidISBN10(null)); assertFalse("isValidISBN13", validator.isValidISBN13(null)); assertNull("validate", validator.validate(null)); assertNull("validateISBN10", validator.validateISBN10(null)); assertNull("validateISBN13", validator.validateISBN13(null)); assertNull("convertToISBN13", validator.convertToISBN13(null)); } /** * Test Invalid ISBN-10 codes */ public void testInvalid() { ISBNValidator validator = ISBNValidator.getInstance(); String baseCode = "193011099"; assertFalse("ISBN10-0", validator.isValid(baseCode + "0")); assertFalse("ISBN10-1", validator.isValid(baseCode + "1")); assertFalse("ISBN10-2", validator.isValid(baseCode + "2")); assertFalse("ISBN10-3", validator.isValid(baseCode + "3")); assertFalse("ISBN10-4", validator.isValid(baseCode + "4")); assertTrue("ISBN10-5", validator.isValid(baseCode + "5")); // valid check digit assertFalse("ISBN10-6", validator.isValid(baseCode + "6")); assertFalse("ISBN10-7", validator.isValid(baseCode + "7")); assertFalse("ISBN10-8", validator.isValid(baseCode + "8")); assertFalse("ISBN10-9", validator.isValid(baseCode + "9")); assertFalse("ISBN10-X", validator.isValid(baseCode + "X")); baseCode = "978193011099"; assertFalse("ISBN13-0", validator.isValid(baseCode + "0")); assertTrue("ISBN13-1", validator.isValid(baseCode + "1")); // valid check digit assertFalse("ISBN13-2", validator.isValid(baseCode + "2")); assertFalse("ISBN13-3", validator.isValid(baseCode + "3")); assertFalse("ISBN13-4", validator.isValid(baseCode + "4")); assertFalse("ISBN13-5", validator.isValid(baseCode + "5")); assertFalse("ISBN13-6", validator.isValid(baseCode + "6")); assertFalse("ISBN13-7", validator.isValid(baseCode + "7")); assertFalse("ISBN13-8", validator.isValid(baseCode + "8")); assertFalse("ISBN13-9", validator.isValid(baseCode + "9")); } /** * Test method for {@link org.apache.commons.validator.routines.ISBNValidator#convertToISBN13(java.lang.String)}. */ public void testConversionErrors() { ISBNValidator validator = ISBNValidator.getInstance(); String input = null; try { input = "123456789 "; validator.convertToISBN13(input); fail("Expected IllegalArgumentException for '" + input + "'"); } catch (IllegalArgumentException e) { // expected result } try { input = "12345678901"; validator.convertToISBN13(input); fail("Expected IllegalArgumentException for '" + input + "'"); } catch (IllegalArgumentException e) { // expected result } try { input = ""; validator.convertToISBN13(input); fail("Expected IllegalArgumentException for '" + input + "'"); } catch (IllegalArgumentException e) { // expected result } try { input = "X234567890"; validator.convertToISBN13(input); fail("Expected IllegalArgumentException for '" + input + "'"); } catch (IllegalArgumentException e) { // expected result } } } ././@LongLink100644 0 0 156 11711231552 10253 Lustar 0 0 commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/routines/InetAddressValidatorTest.javacommons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/routines/InetAddressValidator100644 765 0 7106 11711227700 35012 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines; import junit.framework.TestCase; /** * Test cases for InetAddressValidator. * * @version $Revision: 1094751 $ */ public class InetAddressValidatorTest extends TestCase { private InetAddressValidator validator; /** * Constructor. * @param name */ public InetAddressValidatorTest(String name) { super(name); } protected void setUp() { validator = new InetAddressValidator(); } /** * Test IPs that point to real, well-known hosts (without actually looking them up). */ public void testInetAddressesFromTheWild() { assertTrue("www.apache.org IP should be valid", validator.isValid("140.211.11.130")); assertTrue("www.l.google.com IP should be valid", validator.isValid("72.14.253.103")); assertTrue("fsf.org IP should be valid", validator.isValid("199.232.41.5")); assertTrue("appscs.ign.com IP should be valid", validator.isValid("216.35.123.87")); } /** * Test valid and invalid IPs from each address class. */ public void testInetAddressesByClass() { assertTrue("class A IP should be valid", validator.isValid("24.25.231.12")); assertFalse("illegal class A IP should be invalid", validator.isValid("2.41.32.324")); assertTrue("class B IP should be valid", validator.isValid("135.14.44.12")); assertFalse("illegal class B IP should be invalid", validator.isValid("154.123.441.123")); assertTrue("class C IP should be valid", validator.isValid("213.25.224.32")); assertFalse("illegal class C IP should be invalid", validator.isValid("201.543.23.11")); assertTrue("class D IP should be valid", validator.isValid("229.35.159.6")); assertFalse("illegal class D IP should be invalid", validator.isValid("231.54.11.987")); assertTrue("class E IP should be valid", validator.isValid("248.85.24.92")); assertFalse("illegal class E IP should be invalid", validator.isValid("250.21.323.48")); } /** * Test reserved IPs. */ public void testReservedInetAddresses() { assertTrue("localhost IP should be valid", validator.isValid("127.0.0.1")); assertTrue("broadcast IP should be valid", validator.isValid("255.255.255.255")); } /** * Test obviously broken IPs. */ public void testBrokenInetAddresses() { assertFalse("IP with characters should be invalid", validator.isValid("124.14.32.abc")); assertFalse("IP with three groups should be invalid", validator.isValid("23.64.12")); assertFalse("IP with five groups should be invalid", validator.isValid("26.34.23.77.234")); } } ././@LongLink100644 0 0 152 11711231552 10247 Lustar 0 0 commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/routines/IntegerValidatorTest.javacommons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/routines/IntegerValidatorTest100644 765 0 14106 11711227700 35060 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines; import java.util.Locale; /** * Test Case for IntegerValidator. * * @version $Revision: 1094751 $ $Date: 2011-04-18 23:17:40 +0200 (Mon, 18 Apr 2011) $ */ public class IntegerValidatorTest extends AbstractNumberValidatorTest { /** * Constructor * @param name test name */ public IntegerValidatorTest(String name) { super(name); } protected void setUp() throws Exception { super.setUp(); validator = new IntegerValidator(false, 0); strictValidator = new IntegerValidator(); testPattern = "#,###"; // testValidateMinMax() max = new Integer(Integer.MAX_VALUE); maxPlusOne = new Long(max.longValue() + 1); min = new Integer(Integer.MIN_VALUE); minMinusOne = new Long(min.longValue() - 1); // testInvalidStrict() invalidStrict = new String[] {null, "", "X", "X12", "12X", "1X2", "1.2"}; // testInvalidNotStrict() invalid = new String[] {null, "", "X", "X12"}; // testValid() testNumber = new Integer(1234); testZero = new Integer(0); validStrict = new String[] {"0", "1234", "1,234"}; validStrictCompare = new Number[] {testZero, testNumber, testNumber}; valid = new String[] {"0", "1234", "1,234", "1,234.5", "1234X"}; validCompare = new Number[] {testZero, testNumber, testNumber, testNumber, testNumber}; testStringUS = "1,234"; testStringDE = "1.234"; // Localized Pattern test localeValue = testStringDE; localePattern = "#.###"; testLocale = Locale.GERMANY; localeExpected = testNumber; } /** * Test IntegerValidator validate Methods */ public void testIntegerValidatorMethods() { Locale locale = Locale.GERMAN; String pattern = "0,00,00"; String patternVal = "1,23,45"; String germanPatternVal = "1.23.45"; String localeVal = "12.345"; String defaultVal = "12,345"; String XXXX = "XXXX"; Integer expected = new Integer(12345); assertEquals("validate(A) default", expected, IntegerValidator.getInstance().validate(defaultVal)); assertEquals("validate(A) locale ", expected, IntegerValidator.getInstance().validate(localeVal, locale)); assertEquals("validate(A) pattern", expected, IntegerValidator.getInstance().validate(patternVal, pattern)); assertEquals("validate(A) both", expected, IntegerValidator.getInstance().validate(germanPatternVal, pattern, Locale.GERMAN)); assertTrue("isValid(A) default", IntegerValidator.getInstance().isValid(defaultVal)); assertTrue("isValid(A) locale ", IntegerValidator.getInstance().isValid(localeVal, locale)); assertTrue("isValid(A) pattern", IntegerValidator.getInstance().isValid(patternVal, pattern)); assertTrue("isValid(A) both", IntegerValidator.getInstance().isValid(germanPatternVal, pattern, Locale.GERMAN)); assertNull("validate(B) default", IntegerValidator.getInstance().validate(XXXX)); assertNull("validate(B) locale ", IntegerValidator.getInstance().validate(XXXX, locale)); assertNull("validate(B) pattern", IntegerValidator.getInstance().validate(XXXX, pattern)); assertNull("validate(B) both", IntegerValidator.getInstance().validate(patternVal, pattern, Locale.GERMAN)); assertFalse("isValid(B) default", IntegerValidator.getInstance().isValid(XXXX)); assertFalse("isValid(B) locale ", IntegerValidator.getInstance().isValid(XXXX, locale)); assertFalse("isValid(B) pattern", IntegerValidator.getInstance().isValid(XXXX, pattern)); assertFalse("isValid(B) both", IntegerValidator.getInstance().isValid(patternVal, pattern, Locale.GERMAN)); } /** * Test Integer Range/Min/Max */ public void testIntegerRangeMinMax() { IntegerValidator validator = (IntegerValidator)strictValidator; Integer number9 = validator.validate("9", "#"); Integer number10 = validator.validate("10", "#"); Integer number11 = validator.validate("11", "#"); Integer number19 = validator.validate("19", "#"); Integer number20 = validator.validate("20", "#"); Integer number21 = validator.validate("21", "#"); // Test isInRange() assertFalse("isInRange() < min", validator.isInRange(number9, 10, 20)); assertTrue("isInRange() = min", validator.isInRange(number10, 10, 20)); assertTrue("isInRange() in range", validator.isInRange(number11, 10, 20)); assertTrue("isInRange() = max", validator.isInRange(number20, 10, 20)); assertFalse("isInRange() > max", validator.isInRange(number21, 10, 20)); // Test minValue() assertFalse("minValue() < min", validator.minValue(number9, 10)); assertTrue("minValue() = min", validator.minValue(number10, 10)); assertTrue("minValue() > min", validator.minValue(number11, 10)); // Test minValue() assertTrue("maxValue() < max", validator.maxValue(number19, 20)); assertTrue("maxValue() = max", validator.maxValue(number20, 20)); assertFalse("maxValue() > max", validator.maxValue(number21, 20)); } } ././@LongLink100644 0 0 147 11711231552 10253 Lustar 0 0 commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/routines/LongValidatorTest.javacommons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/routines/LongValidatorTest.ja100644 765 0 13563 11711227700 34761 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines; import java.util.Locale; /** * Test Case for LongValidator. * * @version $Revision: 1094751 $ $Date: 2011-04-18 23:17:40 +0200 (Mon, 18 Apr 2011) $ */ public class LongValidatorTest extends AbstractNumberValidatorTest { /** * Constructor * @param name test name */ public LongValidatorTest(String name) { super(name); } protected void setUp() throws Exception { super.setUp(); validator = new LongValidator(false, 0); strictValidator = new LongValidator(); testPattern = "#,###"; // testValidateMinMax() max = null; maxPlusOne = null; min = null; minMinusOne = null; // testInvalidStrict() invalidStrict = new String[] {null, "", "X", "X12", "12X", "1X2", "1.2"}; // testInvalidNotStrict() invalid = new String[] {null, "", "X", "X12"}; // testValid() testNumber = new Long(1234); testZero = new Long(0); validStrict = new String[] {"0", "1234", "1,234"}; validStrictCompare = new Number[] {testZero, testNumber, testNumber}; valid = new String[] {"0", "1234", "1,234", "1,234.5", "1234X"}; validCompare = new Number[] {testZero, testNumber, testNumber, testNumber, testNumber}; testStringUS = "1,234"; testStringDE = "1.234"; // Localized Pattern test localeValue = testStringDE; localePattern = "#.###"; testLocale = Locale.GERMANY; localeExpected = testNumber; } /** * Test LongValidator validate Methods */ public void testLongValidatorMethods() { Locale locale = Locale.GERMAN; String pattern = "0,00,00"; String patternVal = "1,23,45"; String germanPatternVal = "1.23.45"; String localeVal = "12.345"; String defaultVal = "12,345"; String XXXX = "XXXX"; Long expected = new Long(12345); assertEquals("validate(A) default", expected, LongValidator.getInstance().validate(defaultVal)); assertEquals("validate(A) locale ", expected, LongValidator.getInstance().validate(localeVal, locale)); assertEquals("validate(A) pattern", expected, LongValidator.getInstance().validate(patternVal, pattern)); assertEquals("validate(A) both", expected, LongValidator.getInstance().validate(germanPatternVal, pattern, Locale.GERMAN)); assertTrue("isValid(A) default", LongValidator.getInstance().isValid(defaultVal)); assertTrue("isValid(A) locale ", LongValidator.getInstance().isValid(localeVal, locale)); assertTrue("isValid(A) pattern", LongValidator.getInstance().isValid(patternVal, pattern)); assertTrue("isValid(A) both", LongValidator.getInstance().isValid(germanPatternVal, pattern, Locale.GERMAN)); assertNull("validate(B) default", LongValidator.getInstance().validate(XXXX)); assertNull("validate(B) locale ", LongValidator.getInstance().validate(XXXX, locale)); assertNull("validate(B) pattern", LongValidator.getInstance().validate(XXXX, pattern)); assertNull("validate(B) both", LongValidator.getInstance().validate(patternVal, pattern, Locale.GERMAN)); assertFalse("isValid(B) default", LongValidator.getInstance().isValid(XXXX)); assertFalse("isValid(B) locale ", LongValidator.getInstance().isValid(XXXX, locale)); assertFalse("isValid(B) pattern", LongValidator.getInstance().isValid(XXXX, pattern)); assertFalse("isValid(B) both", LongValidator.getInstance().isValid(patternVal, pattern, Locale.GERMAN)); } /** * Test Long Range/Min/Max */ public void testLongRangeMinMax() { LongValidator validator = (LongValidator)strictValidator; Long number9 = validator.validate("9", "#"); Long number10 = validator.validate("10", "#"); Long number11 = validator.validate("11", "#"); Long number19 = validator.validate("19", "#"); Long number20 = validator.validate("20", "#"); Long number21 = validator.validate("21", "#"); // Test isInRange() assertFalse("isInRange() < min", validator.isInRange(number9, 10, 20)); assertTrue("isInRange() = min", validator.isInRange(number10, 10, 20)); assertTrue("isInRange() in range", validator.isInRange(number11, 10, 20)); assertTrue("isInRange() = max", validator.isInRange(number20, 10, 20)); assertFalse("isInRange() > max", validator.isInRange(number21, 10, 20)); // Test minValue() assertFalse("minValue() < min", validator.minValue(number9, 10)); assertTrue("minValue() = min", validator.minValue(number10, 10)); assertTrue("minValue() > min", validator.minValue(number11, 10)); // Test minValue() assertTrue("maxValue() < max", validator.maxValue(number19, 20)); assertTrue("maxValue() = max", validator.maxValue(number20, 20)); assertFalse("maxValue() > max", validator.maxValue(number21, 20)); } } ././@LongLink100644 0 0 152 11711231552 10247 Lustar 0 0 commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/routines/PercentValidatorTest.javacommons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/routines/PercentValidatorTest100644 765 0 10150 11711227700 35056 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines; import junit.framework.TestCase; import java.util.Locale; import java.math.BigDecimal; /** * Test Case for PercentValidator. * * @version $Revision: 1094751 $ $Date: 2011-04-18 23:17:40 +0200 (Mon, 18 Apr 2011) $ */ public class PercentValidatorTest extends TestCase { protected PercentValidator validator; /** * Constructor * @param name test name */ public PercentValidatorTest(String name) { super(name); } protected void setUp() throws Exception { super.setUp(); validator = new PercentValidator(); } /** * Tear down * @throws Exception */ protected void tearDown() throws Exception { super.tearDown(); validator = null; } /** * Test Format Type */ public void testFormatType() { assertEquals("Format Type A", 2, PercentValidator.getInstance().getFormatType()); assertEquals("Format Type B", PercentValidator.PERCENT_FORMAT, PercentValidator.getInstance().getFormatType()); } /** * Test Valid percentage values */ public void testValid() { // Set the default Locale Locale origDefault = Locale.getDefault(); Locale.setDefault(Locale.UK); BigDecimalValidator validator = PercentValidator.getInstance(); BigDecimal expected = new BigDecimal("0.12"); BigDecimal negative = new BigDecimal("-0.12"); BigDecimal hundred = new BigDecimal("1.00"); assertEquals("Default locale", expected, validator.validate("12%")); assertEquals("Default negtve", negative, validator.validate("-12%")); // Invalid UK assertEquals("UK locale", expected, validator.validate("12%", Locale.UK)); assertEquals("UK negative", negative, validator.validate("-12%", Locale.UK)); assertEquals("UK No symbol", expected, validator.validate("12", Locale.UK)); // Invalid US - can't find a Locale with different symbols! assertEquals("US locale", expected, validator.validate("12%", Locale.US)); assertEquals("US negative", negative, validator.validate("-12%", Locale.US)); assertEquals("US No symbol", expected, validator.validate("12", Locale.US)); assertEquals("100%", hundred, validator.validate("100%")); // Restore the original default Locale.setDefault(origDefault); } /** * Test Invalid percentage values */ public void testInvalid() { BigDecimalValidator validator = PercentValidator.getInstance(); // Invalid Missing assertFalse("isValid() Null Value", validator.isValid(null)); assertFalse("isValid() Empty Value", validator.isValid("")); assertNull("validate() Null Value", validator.validate(null)); assertNull("validate() Empty Value", validator.validate("")); // Invalid UK assertFalse("UK wrong symbol", validator.isValid("12@", Locale.UK)); // ??? assertFalse("UK wrong negative", validator.isValid("(12%)", Locale.UK)); // Invalid US - can't find a Locale with different symbols! assertFalse("US wrong symbol", validator.isValid("12@", Locale.US)); // ??? assertFalse("US wrong negative", validator.isValid("(12%)", Locale.US)); } } ././@LongLink100644 0 0 150 11711231552 10245 Lustar 0 0 commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/routines/RegexValidatorTest.javacommons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/routines/RegexValidatorTest.j100644 765 0 27523 11711227700 34774 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines; import java.util.regex.PatternSyntaxException; import junit.framework.TestCase; /** * Test Case for RegexValidatorTest. * * @version $Revision: 595023 $ $Date: 2007-11-14 20:49:23 +0100 (Wed, 14 Nov 2007) $ * @since Validator 1.4 */ public class RegexValidatorTest extends TestCase { private static final String REGEX = "^([abc]*)(?:\\-)([DEF]*)(?:\\-)([123]*)$"; private static final String COMPONENT_1 = "([abc]{3})"; private static final String COMPONENT_2 = "([DEF]{3})"; private static final String COMPONENT_3 = "([123]{3})"; private static final String SEPARATOR_1 = "(?:\\-)"; private static final String SEPARATOR_2 = "(?:\\s)"; private static final String REGEX_1 = "^" + COMPONENT_1 + SEPARATOR_1 + COMPONENT_2 + SEPARATOR_1 + COMPONENT_3 + "$"; private static final String REGEX_2 = "^" + COMPONENT_1 + SEPARATOR_2 + COMPONENT_2 + SEPARATOR_2 + COMPONENT_3 + "$"; private static final String REGEX_3 = "^" + COMPONENT_1 + COMPONENT_2 + COMPONENT_3 + "$"; private static final String[] MULTIPLE_REGEX = new String[] {REGEX_1, REGEX_2, REGEX_3}; /** * Constrct a new test case. * @param name The name of the test */ public RegexValidatorTest(String name) { super(name); } /** * Set Up. */ protected void setUp() throws Exception { super.setUp(); } /** * Tear Down. */ protected void tearDown() throws Exception { super.tearDown(); } /** * Test instance methods with single regular expression. */ public void testSingle() { RegexValidator sensitive = new RegexValidator(REGEX); RegexValidator insensitive = new RegexValidator(REGEX, false); // isValid() assertEquals("Sensitive isValid() valid", true, sensitive.isValid("ac-DE-1")); assertEquals("Sensitive isValid() invalid", false, sensitive.isValid("AB-de-1")); assertEquals("Insensitive isValid() valid", true, insensitive.isValid("AB-de-1")); assertEquals("Insensitive isValid() invalid", false, insensitive.isValid("ABd-de-1")); // validate() assertEquals("Sensitive validate() valid", "acDE1", sensitive.validate("ac-DE-1")); assertEquals("Sensitive validate() invalid", null, sensitive.validate("AB-de-1")); assertEquals("Insensitive validate() valid", "ABde1", insensitive.validate("AB-de-1")); assertEquals("Insensitive validate() invalid", null, insensitive.validate("ABd-de-1")); // match() checkArray("Sensitive match() valid", new String[] {"ac", "DE", "1"}, sensitive.match("ac-DE-1")); checkArray("Sensitive match() invalid", null, sensitive.match("AB-de-1")); checkArray("Insensitive match() valid", new String[] {"AB", "de", "1"}, insensitive.match("AB-de-1")); checkArray("Insensitive match() invalid", null, insensitive.match("ABd-de-1")); assertEquals("validate one", "ABC", (new RegexValidator("^([A-Z]*)$")).validate("ABC")); checkArray("match one", new String[] {"ABC"}, (new RegexValidator("^([A-Z]*)$")).match("ABC")); } /** * Test with multiple regular expressions (case sensitive). */ public void testMultipleSensitive() { // ------------ Set up Sensitive Validators RegexValidator multiple = new RegexValidator(MULTIPLE_REGEX); RegexValidator single1 = new RegexValidator(REGEX_1); RegexValidator single2 = new RegexValidator(REGEX_2); RegexValidator single3 = new RegexValidator(REGEX_3); // ------------ Set up test values String value = "aac FDE 321"; String expect = "aacFDE321"; String[] array = new String[] {"aac", "FDE", "321"}; // isValid() assertEquals("Sensitive isValid() Multiple", true, multiple.isValid(value)); assertEquals("Sensitive isValid() 1st", false, single1.isValid(value)); assertEquals("Sensitive isValid() 2nd", true, single2.isValid(value)); assertEquals("Sensitive isValid() 3rd", false, single3.isValid(value)); // validate() assertEquals("Sensitive validate() Multiple", expect, multiple.validate(value)); assertEquals("Sensitive validate() 1st", null, single1.validate(value)); assertEquals("Sensitive validate() 2nd", expect, single2.validate(value)); assertEquals("Sensitive validate() 3rd", null, single3.validate(value)); // match() checkArray("Sensitive match() Multiple", array, multiple.match(value)); checkArray("Sensitive match() 1st", null, single1.match(value)); checkArray("Sensitive match() 2nd", array, single2.match(value)); checkArray("Sensitive match() 3rd", null, single3.match(value)); // All invalid value = "AAC*FDE*321"; assertEquals("isValid() Invalid", false, multiple.isValid(value)); assertEquals("validate() Invalid", null, multiple.validate(value)); assertEquals("match() Multiple", null, multiple.match(value)); } /** * Test with multiple regular expressions (case in-sensitive). */ public void testMultipleInsensitive() { // ------------ Set up In-sensitive Validators RegexValidator multiple = new RegexValidator(MULTIPLE_REGEX, false); RegexValidator single1 = new RegexValidator(REGEX_1, false); RegexValidator single2 = new RegexValidator(REGEX_2, false); RegexValidator single3 = new RegexValidator(REGEX_3, false); // ------------ Set up test values String value = "AAC FDE 321"; String expect = "AACFDE321"; String[] array = new String[] {"AAC", "FDE", "321"}; // isValid() assertEquals("isValid() Multiple", true, multiple.isValid(value)); assertEquals("isValid() 1st", false, single1.isValid(value)); assertEquals("isValid() 2nd", true, single2.isValid(value)); assertEquals("isValid() 3rd", false, single3.isValid(value)); // validate() assertEquals("validate() Multiple", expect, multiple.validate(value)); assertEquals("validate() 1st", null, single1.validate(value)); assertEquals("validate() 2nd", expect, single2.validate(value)); assertEquals("validate() 3rd", null, single3.validate(value)); // match() checkArray("match() Multiple", array, multiple.match(value)); checkArray("match() 1st", null, single1.match(value)); checkArray("match() 2nd", array, single2.match(value)); checkArray("match() 3rd", null, single3.match(value)); // All invalid value = "AAC*FDE*321"; assertEquals("isValid() Invalid", false, multiple.isValid(value)); assertEquals("validate() Invalid", null, multiple.validate(value)); assertEquals("match() Multiple", null, multiple.match(value)); } /** * Test Null value */ public void testNullValue() { RegexValidator validator = new RegexValidator(REGEX); assertEquals("Instance isValid()", false, validator.isValid(null)); assertEquals("Instance validate()", null, validator.validate(null)); assertEquals("Instance match()", null, validator.match(null)); } /** * Test exceptions */ public void testMissingRegex() { // Single Regular Expression - null try { new RegexValidator((String)null); fail("Single Null - expected IllegalArgumentException"); } catch (IllegalArgumentException e) { assertEquals("Single Null", "Regular expression[0] is missing", e.getMessage()); } // Single Regular Expression - Zero Length try { new RegexValidator(""); fail("Single Zero Length - expected IllegalArgumentException"); } catch (IllegalArgumentException e) { assertEquals("Single Zero Length", "Regular expression[0] is missing", e.getMessage()); } // Multiple Regular Expression - Null array try { new RegexValidator((String[])null); fail("Null Array - expected IllegalArgumentException"); } catch (IllegalArgumentException e) { assertEquals("Null Array", "Regular expressions are missing", e.getMessage()); } // Multiple Regular Expression - Zero Length array try { new RegexValidator(new String[0]); fail("Zero Length Array - expected IllegalArgumentException"); } catch (IllegalArgumentException e) { assertEquals("Zero Length Array", "Regular expressions are missing", e.getMessage()); } // Multiple Regular Expression - Array has Null String[] expressions = new String[] {"ABC", null}; try { new RegexValidator(expressions); fail("Array has Null - expected IllegalArgumentException"); } catch (IllegalArgumentException e) { assertEquals("Array has Null", "Regular expression[1] is missing", e.getMessage()); } // Multiple Regular Expression - Array has Zero Length expressions = new String[] {"", "ABC"}; try { new RegexValidator(expressions); fail("Array has Zero Length - expected IllegalArgumentException"); } catch (IllegalArgumentException e) { assertEquals("Array has Zero Length", "Regular expression[0] is missing", e.getMessage()); } } /** * Test exceptions */ public void testExceptions() { String invalidRegex = "^([abCD12]*$"; try { new RegexValidator(invalidRegex); } catch (PatternSyntaxException e) { // expected } } /** * Test toString() method */ public void testToString() { RegexValidator single = new RegexValidator(REGEX); assertEquals("Single", "RegexValidator{" + REGEX + "}", single.toString()); RegexValidator multiple = new RegexValidator(new String[] {REGEX, REGEX}); assertEquals("Multiple", "RegexValidator{" + REGEX + "," + REGEX + "}", multiple.toString()); } /** * Compare two arrays * @param label Label for the test * @param expect Expected array * @param result Actual array */ private void checkArray(String label, String[] expect, String[] result) { // Handle nulls if (expect == null || result == null) { if (expect == null && result == null) { return; // valid, both null } else { fail(label + " Null expect=" + expect + " result=" + result); } } // Check Length if (expect.length != result.length) { fail(label + " Length expect=" + expect.length + " result=" + result.length); } // Check Values for (int i = 0; i < expect.length; i++) { assertEquals(label +" value[" + i + "]", expect[i], result[i]); } } } ././@LongLink100644 0 0 150 11711231552 10245 Lustar 0 0 commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/routines/ShortValidatorTest.javacommons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/routines/ShortValidatorTest.j100644 765 0 14130 11711227700 35007 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines; import java.util.Locale; /** * Test Case for ShortValidator. * * @version $Revision: 1094751 $ $Date: 2011-04-18 23:17:40 +0200 (Mon, 18 Apr 2011) $ */ public class ShortValidatorTest extends AbstractNumberValidatorTest { /** * Constructor * @param name test name */ public ShortValidatorTest(String name) { super(name); } protected void setUp() throws Exception { super.setUp(); validator = new ShortValidator(false, 0); strictValidator = new ShortValidator(); testPattern = "#,###"; // testValidateMinMax() max = new Short(Short.MAX_VALUE); maxPlusOne = new Long(max.longValue() + 1); min = new Short(Short.MIN_VALUE); minMinusOne = new Long(min.longValue() - 1); // testInvalidStrict() invalidStrict = new String[] {null, "", "X", "X12", "12X", "1X2", "1.2"}; // testInvalidNotStrict() invalid = new String[] {null, "", "X", "X12"}; // testValid() testNumber = new Short((short)1234); testZero = new Short((short)0); validStrict = new String[] {"0", "1234", "1,234"}; validStrictCompare = new Number[] {testZero, testNumber, testNumber}; valid = new String[] {"0", "1234", "1,234", "1,234.5", "1234X"}; validCompare = new Number[] {testZero, testNumber, testNumber, testNumber, testNumber}; testStringUS = "1,234"; testStringDE = "1.234"; // Localized Pattern test localeValue = testStringDE; localePattern = "#.###"; testLocale = Locale.GERMANY; localeExpected = testNumber; } /** * Test ShortValidator validate Methods */ public void testShortValidatorMethods() { Locale locale = Locale.GERMAN; String pattern = "0,00,00"; String patternVal = "1,23,45"; String germanPatternVal = "1.23.45"; String localeVal = "12.345"; String defaultVal = "12,345"; String XXXX = "XXXX"; Short expected = new Short((short)12345); assertEquals("validate(A) default", expected, ShortValidator.getInstance().validate(defaultVal)); assertEquals("validate(A) locale ", expected, ShortValidator.getInstance().validate(localeVal, locale)); assertEquals("validate(A) pattern", expected, ShortValidator.getInstance().validate(patternVal, pattern)); assertEquals("validate(A) both", expected, ShortValidator.getInstance().validate(germanPatternVal, pattern, Locale.GERMAN)); assertTrue("isValid(A) default", ShortValidator.getInstance().isValid(defaultVal)); assertTrue("isValid(A) locale ", ShortValidator.getInstance().isValid(localeVal, locale)); assertTrue("isValid(A) pattern", ShortValidator.getInstance().isValid(patternVal, pattern)); assertTrue("isValid(A) both", ShortValidator.getInstance().isValid(germanPatternVal, pattern, Locale.GERMAN)); assertNull("validate(B) default", ShortValidator.getInstance().validate(XXXX)); assertNull("validate(B) locale ", ShortValidator.getInstance().validate(XXXX, locale)); assertNull("validate(B) pattern", ShortValidator.getInstance().validate(XXXX, pattern)); assertNull("validate(B) both", ShortValidator.getInstance().validate(patternVal, pattern, Locale.GERMAN)); assertFalse("isValid(B) default", ShortValidator.getInstance().isValid(XXXX)); assertFalse("isValid(B) locale ", ShortValidator.getInstance().isValid(XXXX, locale)); assertFalse("isValid(B) pattern", ShortValidator.getInstance().isValid(XXXX, pattern)); assertFalse("isValid(B) both", ShortValidator.getInstance().isValid(patternVal, pattern, Locale.GERMAN)); } /** * Test Short Range/Min/Max */ public void testShortRangeMinMax() { ShortValidator validator = (ShortValidator)strictValidator; Short number9 = validator.validate("9", "#"); Short number10 = validator.validate("10", "#"); Short number11 = validator.validate("11", "#"); Short number19 = validator.validate("19", "#"); Short number20 = validator.validate("20", "#"); Short number21 = validator.validate("21", "#"); short min = (short)10; short max = (short)20; // Test isInRange() assertFalse("isInRange() < min", validator.isInRange(number9, min, max)); assertTrue("isInRange() = min", validator.isInRange(number10, min, max)); assertTrue("isInRange() in range", validator.isInRange(number11, min, max)); assertTrue("isInRange() = max", validator.isInRange(number20, min, max)); assertFalse("isInRange() > max", validator.isInRange(number21, min, max)); // Test minValue() assertFalse("minValue() < min", validator.minValue(number9, min)); assertTrue("minValue() = min", validator.minValue(number10, min)); assertTrue("minValue() > min", validator.minValue(number11, min)); // Test minValue() assertTrue("maxValue() < max", validator.maxValue(number19, max)); assertTrue("maxValue() = max", validator.maxValue(number20, max)); assertFalse("maxValue() > max", validator.maxValue(number21, max)); } } ././@LongLink100644 0 0 147 11711231552 10253 Lustar 0 0 commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/routines/TimeValidatorTest.javacommons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/routines/TimeValidatorTest.ja100644 765 0 34536 11711227700 34763 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines; import junit.framework.TestCase; import java.util.Date; import java.util.Calendar; import java.util.Locale; import java.util.TimeZone; /** * Test Case for TimeValidator. * * @version $Revision: 1094751 $ $Date: 2011-04-18 23:17:40 +0200 (Mon, 18 Apr 2011) $ */ public class TimeValidatorTest extends TestCase { protected static final TimeZone GMT = TimeZone.getTimeZone("GMT"); // 0 offset protected static final TimeZone EST = TimeZone.getTimeZone("EST"); // - 5 hours protected TimeValidator validator; protected String[] patternValid = new String[] { "23-59-59" ,"00-00-00" ,"00-00-01" ,"0-0-0" ,"1-12-1" ,"10-49-18" ,"16-23-46"}; protected Date[] patternExpect = new Date[] { createDate(null, 235959, 0) ,createDate(null, 0, 0) ,createDate(null, 1, 0) ,createDate(null, 0, 0) ,createDate(null, 11201, 0) ,createDate(null, 104918, 0) ,createDate(null, 162346, 0)}; protected String[] localeValid = new String[] { "23:59" ,"00:00" ,"00:01" ,"0:0" ,"1:12" ,"10:49" ,"16:23"}; protected Date[] localeExpect = new Date[] { createDate(null, 235900, 0) ,createDate(null, 0, 0) ,createDate(null, 100, 0) ,createDate(null, 0, 0) ,createDate(null, 11200, 0) ,createDate(null, 104900, 0) ,createDate(null, 162300, 0)}; protected String[] patternInvalid = new String[] { "24-00-00" // midnight ,"24-00-01" // past midnight ,"25-02-03" // invalid hour ,"10-61-31" // invalid minute ,"10-01-61" // invalid second ,"05:02-29" // invalid sep ,"0X-01:01" // invalid sep ,"05-0X-01" // invalid char ,"10-01-0X" // invalid char ,"01:01:05" // invalid pattern ,"10-10" // invalid pattern ,"10--10" // invalid pattern ,"10-10-"}; // invalid pattern protected String[] localeInvalid = new String[] { "24:00" // midnight ,"24:00" // past midnight ,"25:02" // invalid hour ,"10:61" // invalid minute ,"05-02" // invalid sep ,"0X:01" // invalid sep ,"05:0X" // invalid char ,"01-01" // invalid pattern ,"10:" // invalid pattern ,"10::1" // invalid pattern ,"10:1:"}; // invalid pattern /** * Constructor * @param name test name */ public TimeValidatorTest(String name) { super(name); } protected void setUp() throws Exception { super.setUp(); validator = new TimeValidator(); } /** * Tear down * @throws Exception */ protected void tearDown() throws Exception { super.tearDown(); validator = null; } /** * Test Valid Dates with "pattern" validation */ public void testPatternValid() { for (int i = 0; i < patternValid.length; i++) { String text = i + " value=[" +patternValid[i]+"] failed "; Calendar calendar = validator.validate(patternValid[i], "HH-mm-ss"); assertNotNull("validateObj() " + text, calendar); Date date = calendar.getTime(); assertTrue("isValid() " + text, validator.isValid(patternValid[i], "HH-mm-ss")); assertEquals("compare " + text, patternExpect[i], date); } } /** * Test Invalid Dates with "pattern" validation */ public void testPatternInvalid() { for (int i = 0; i < patternInvalid.length; i++) { String text = i + " value=[" +patternInvalid[i]+"] passed "; Object date = validator.validate(patternInvalid[i], "HH-mm-ss"); assertNull("validate() " + text + date, date); assertFalse("isValid() " + text, validator.isValid(patternInvalid[i], "HH-mm-ss")); } } /** * Test Valid Dates with "locale" validation */ public void testLocaleValid() { for (int i = 0; i < localeValid.length; i++) { String text = i + " value=[" +localeValid[i]+"] failed "; Calendar calendar = validator.validate(localeValid[i], Locale.UK); assertNotNull("validate() " + text, calendar); Date date = calendar.getTime(); assertTrue("isValid() " + text, validator.isValid(localeValid[i], Locale.UK)); assertEquals("compare " + text, localeExpect[i], date); } } /** * Test Invalid Dates with "locale" validation */ public void testLocaleInvalid() { for (int i = 0; i < localeInvalid.length; i++) { String text = i + " value=[" +localeInvalid[i]+"] passed "; Object date = validator.validate(localeInvalid[i], Locale.US); assertNull("validate() " + text + date, date); assertFalse("isValid() " + text, validator.isValid(localeInvalid[i], Locale.UK)); } } /** * Test time zone methods. */ public void testTimeZone() { // Set the default Locale & TimeZone Locale origDefault = Locale.getDefault(); Locale.setDefault(Locale.UK); TimeZone defaultZone = TimeZone.getDefault(); TimeZone.setDefault(GMT); Calendar result = null; // Default Locale, Default TimeZone result = validator.validate("18:01"); assertNotNull("default result", result); assertEquals("default zone", GMT, result.getTimeZone()); assertEquals("default hour", 18, result.get(Calendar.HOUR_OF_DAY)); assertEquals("default minute", 01, result.get(Calendar.MINUTE)); result = null; // Default Locale, diff TimeZone result = validator.validate("16:49", EST); assertNotNull("zone result", result); assertEquals("zone zone", EST, result.getTimeZone()); assertEquals("zone hour", 16, result.get(Calendar.HOUR_OF_DAY)); assertEquals("zone minute", 49, result.get(Calendar.MINUTE)); result = null; // Pattern, diff TimeZone result = validator.validate("14-34", "HH-mm", EST); assertNotNull("pattern result", result); assertEquals("pattern zone", EST, result.getTimeZone()); assertEquals("pattern hour", 14, result.get(Calendar.HOUR_OF_DAY)); assertEquals("pattern minute", 34, result.get(Calendar.MINUTE)); result = null; // Locale, diff TimeZone result = validator.validate("7:18 PM", Locale.US, EST); assertNotNull("locale result", result); assertEquals("locale zone", EST, result.getTimeZone()); assertEquals("locale hour", 19, result.get(Calendar.HOUR_OF_DAY)); assertEquals("locale minute", 18, result.get(Calendar.MINUTE)); result = null; // Locale & Pattern, diff TimeZone result = validator.validate("31/Dez/05 21-05", "dd/MMM/yy HH-mm", Locale.GERMAN, EST); assertNotNull("pattern result", result); assertEquals("pattern zone", EST, result.getTimeZone()); assertEquals("pattern day", 2005, result.get(Calendar.YEAR)); assertEquals("pattern day", 11, result.get(Calendar.MONTH)); // months are 0-11 assertEquals("pattern day", 31, result.get(Calendar.DATE)); assertEquals("pattern hour", 21, result.get(Calendar.HOUR_OF_DAY)); assertEquals("pattern minute", 05, result.get(Calendar.MINUTE)); result = null; // Locale & Pattern, default TimeZone result = validator.validate("31/Dez/05 21-05", "dd/MMM/yy HH-mm", Locale.GERMAN); assertNotNull("pattern result", result); assertEquals("pattern zone", GMT, result.getTimeZone()); assertEquals("pattern day", 2005, result.get(Calendar.YEAR)); assertEquals("pattern day", 11, result.get(Calendar.MONTH)); // months are 0-11 assertEquals("pattern day", 31, result.get(Calendar.DATE)); assertEquals("pattern hour", 21, result.get(Calendar.HOUR_OF_DAY)); assertEquals("pattern minute", 05, result.get(Calendar.MINUTE)); result = null; // Restore the original default Locale.setDefault(origDefault); TimeZone.setDefault(defaultZone); } /** * Test Invalid Dates with "locale" validation */ public void testFormat() { // Set the default Locale Locale origDefault = Locale.getDefault(); Locale.setDefault(Locale.UK); Object test = TimeValidator.getInstance().validate("16:49:23", "HH:mm:ss"); assertNotNull("Test Date ", test); assertEquals("Format pattern", "16-49-23", validator.format(test, "HH-mm-ss")); assertEquals("Format locale", "4:49 PM", validator.format(test, Locale.US)); assertEquals("Format default", "16:49", validator.format(test)); // Restore the original default Locale.setDefault(origDefault); } /** * Test compare date methods */ public void testCompare() { int testTime = 154523; int min = 100; int hour = 10000; Calendar milliGreater = createTime(GMT, testTime, 500); // > milli sec Calendar value = createTime(GMT, testTime, 400); // test value Calendar milliLess = createTime(GMT, testTime, 300); // < milli sec Calendar secGreater = createTime(GMT, testTime + 1, 100); // +1 sec Calendar secLess = createTime(GMT, testTime - 1, 100); // -1 sec Calendar minGreater = createTime(GMT, testTime + min, 100); // +1 min Calendar minLess = createTime(GMT, testTime - min, 100); // -1 min Calendar hourGreater = createTime(GMT, testTime + hour, 100); // +1 hour Calendar hourLess = createTime(GMT, testTime - hour, 100); // -1 hour assertEquals("mili LT", -1, validator.compareTime(value, milliGreater)); // > milli assertEquals("mili EQ", 0, validator.compareTime(value, value)); // same time assertEquals("mili GT", 1, validator.compareTime(value, milliLess)); // < milli assertEquals("secs LT", -1, validator.compareSeconds(value, secGreater)); // +1 sec assertEquals("secs =1", 0, validator.compareSeconds(value, milliGreater)); // > milli assertEquals("secs =2", 0, validator.compareSeconds(value, value)); // same time assertEquals("secs =3", 0, validator.compareSeconds(value, milliLess)); // < milli assertEquals("secs GT", 1, validator.compareSeconds(value, secLess)); // -1 sec assertEquals("mins LT", -1, validator.compareMinutes(value, minGreater)); // +1 min assertEquals("mins =1", 0, validator.compareMinutes(value, secGreater)); // +1 sec assertEquals("mins =2", 0, validator.compareMinutes(value, value)); // same time assertEquals("mins =3", 0, validator.compareMinutes(value, secLess)); // -1 sec assertEquals("mins GT", 1, validator.compareMinutes(value, minLess)); // -1 min assertEquals("hour LT", -1, validator.compareHours(value, hourGreater)); // +1 hour assertEquals("hour =1", 0, validator.compareHours(value, minGreater)); // +1 min assertEquals("hour =2", 0, validator.compareHours(value, value)); // same time assertEquals("hour =3", 0, validator.compareHours(value, minLess)); // -1 min assertEquals("hour GT", 1, validator.compareHours(value, hourLess)); // -1 hour } /** * Create a calendar instance for a specified time zone, date and time. * * @param zone The time zone * @param time the time in HH:mm:ss format * @param millisecond the milliseconds * @return the new Calendar instance. */ protected static Calendar createTime(TimeZone zone, int time, int millisecond) { Calendar calendar = zone == null ? Calendar.getInstance() : Calendar.getInstance(zone); int hour = ((time / 10000) * 10000); int min = ((time / 100) * 100) - hour; int sec = time - (hour + min); calendar.set(Calendar.YEAR, 1970); calendar.set(Calendar.MONTH, 0); calendar.set(Calendar.DATE, 1); calendar.set(Calendar.HOUR_OF_DAY, (hour / 10000)); calendar.set(Calendar.MINUTE, (min / 100)); calendar.set(Calendar.SECOND, sec); calendar.set(Calendar.MILLISECOND, millisecond); return calendar; } /** * Create a date instance for a specified time zone, date and time. * * @param zone The time zone * @param time the time in HH:mm:ss format * @param millisecond the milliseconds * @return the new Date instance. */ protected static Date createDate(TimeZone zone, int time, int millisecond) { Calendar calendar = createTime(zone, time, millisecond); return calendar.getTime(); } } ././@LongLink100644 0 0 146 11711231552 10252 Lustar 0 0 commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/routines/UrlValidatorTest.javacommons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/routines/UrlValidatorTest.jav100644 765 0 42412 11711227700 35005 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines; import junit.framework.TestCase; import org.apache.commons.validator.ResultPair; /** * Performs Validation Test for url validations. * * @version $Revision: 1128446 $ $Date: 2011-05-27 22:29:27 +0200 (Fri, 27 May 2011) $ */ public class UrlValidatorTest extends TestCase { private boolean printStatus = false; private boolean printIndex = false;//print index that indicates current scheme,host,port,path, query test were using. public UrlValidatorTest(String testName) { super(testName); } protected void setUp() { for (int index = 0; index < testPartsIndex.length - 1; index++) { testPartsIndex[index] = 0; } } public void testIsValid() { testIsValid(testUrlParts, UrlValidator.ALLOW_ALL_SCHEMES); setUp(); long options = UrlValidator.ALLOW_2_SLASHES + UrlValidator.ALLOW_ALL_SCHEMES + UrlValidator.NO_FRAGMENTS; testIsValid(testUrlPartsOptions, options); } public void testIsValidScheme() { if (printStatus) { System.out.print("\n testIsValidScheme() "); } String[] schemes = {"http", "gopher"}; //UrlValidator urlVal = new UrlValidator(schemes,false,false,false); UrlValidator urlVal = new UrlValidator(schemes, 0); for (int sIndex = 0; sIndex < testScheme.length; sIndex++) { ResultPair testPair = testScheme[sIndex]; boolean result = urlVal.isValidScheme(testPair.item); assertEquals(testPair.item, testPair.valid, result); if (printStatus) { if (result == testPair.valid) { System.out.print('.'); } else { System.out.print('X'); } } } if (printStatus) { System.out.println(); } } /** * Create set of tests by taking the testUrlXXX arrays and * running through all possible permutations of their combinations. * * @param testObjects Used to create a url. */ public void testIsValid(Object[] testObjects, long options) { UrlValidator urlVal = new UrlValidator(null, null, options); assertTrue(urlVal.isValid("http://www.google.com")); assertTrue(urlVal.isValid("http://www.google.com/")); int statusPerLine = 60; int printed = 0; if (printIndex) { statusPerLine = 6; } do { StringBuffer testBuffer = new StringBuffer(); boolean expected = true; for (int testPartsIndexIndex = 0; testPartsIndexIndex < testPartsIndex.length; ++testPartsIndexIndex) { int index = testPartsIndex[testPartsIndexIndex]; ResultPair[] part = (ResultPair[]) testObjects[testPartsIndexIndex]; testBuffer.append(part[index].item); expected &= part[index].valid; } String url = testBuffer.toString(); boolean result = urlVal.isValid(url); assertEquals(url, expected, result); if (printStatus) { if (printIndex) { System.out.print(testPartsIndextoString()); } else { if (result == expected) { System.out.print('.'); } else { System.out.print('X'); } } printed++; if (printed == statusPerLine) { System.out.println(); printed = 0; } } } while (incrementTestPartsIndex(testPartsIndex, testObjects)); if (printStatus) { System.out.println(); } } public void testValidator202() { String[] schemes = {"http","https"}; UrlValidator urlValidator = new UrlValidator(schemes, UrlValidator.NO_FRAGMENTS); assertTrue(urlValidator.isValid("http://www.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.logoworks.comwww.org")); } public void testValidator204() { String[] schemes = {"http","https"}; UrlValidator urlValidator = new UrlValidator(schemes); assertTrue(urlValidator.isValid("http://tech.yahoo.com/rc/desktops/102;_ylt=Ao8yevQHlZ4On0O3ZJGXLEQFLZA5")); } public void testValidator218() { UrlValidator validator = new UrlValidator(UrlValidator.ALLOW_2_SLASHES); assertTrue("parentheses should be valid in URLs", validator.isValid("http://somewhere.com/pathxyz/file(1).html")); } public void testValidator248() { RegexValidator regex = new RegexValidator(new String[] {"localhost", ".*\\.my-testing"}); UrlValidator validator = new UrlValidator(regex, 0); assertTrue("localhost URL should validate", validator.isValid("http://localhost/test/index.html")); assertTrue("first.my-testing should validate", validator.isValid("http://first.my-testing/test/index.html")); assertTrue("sup3r.my-testing should validate", validator.isValid("http://sup3r.my-testing/test/index.html")); assertFalse("broke.my-test should not validate", validator.isValid("http://broke.my-test/test/index.html")); assertTrue("www.apache.org should still validate", validator.isValid("http://www.apache.org/test/index.html")); // Now check using options validator = new UrlValidator(UrlValidator.ALLOW_LOCAL_URLS); assertTrue("localhost URL should validate", validator.isValid("http://localhost/test/index.html")); assertTrue("machinename URL should validate", validator.isValid("http://machinename/test/index.html")); assertTrue("www.apache.org should still validate", validator.isValid("http://www.apache.org/test/index.html")); } public void testValidator288() { UrlValidator validator = new UrlValidator(UrlValidator.ALLOW_LOCAL_URLS); assertTrue("hostname should validate", validator.isValid("http://hostname")); assertTrue("hostname with path should validate", validator.isValid("http://hostname/test/index.html")); assertTrue("localhost URL should validate", validator.isValid("http://localhost/test/index.html")); assertFalse("first.my-testing should not validate", validator.isValid("http://first.my-testing/test/index.html")); assertFalse("broke.hostname should not validate", validator.isValid("http://broke.hostname/test/index.html")); assertTrue("www.apache.org should still validate", validator.isValid("http://www.apache.org/test/index.html")); // Turn it off, and check validator = new UrlValidator(0); assertFalse("hostname should no longer validate", validator.isValid("http://hostname")); assertFalse("localhost URL should no longer validate", validator.isValid("http://localhost/test/index.html")); assertTrue("www.apache.org should still validate", validator.isValid("http://www.apache.org/test/index.html")); } public void testValidator276() { // file:// isn't allowed by default UrlValidator validator = new UrlValidator(); assertTrue("http://apache.org/ should be allowed by default", validator.isValid("http://www.apache.org/test/index.html")); assertFalse("file:///c:/ shouldn't be allowed by default", validator.isValid("file:///C:/some.file")); assertFalse("file:///c:\\ shouldn't be allowed by default", validator.isValid("file:///C:\\some.file")); assertFalse("file:///etc/ shouldn't be allowed by default", validator.isValid("file:///etc/hosts")); assertFalse("file://localhost/etc/ shouldn't be allowed by default", validator.isValid("file://localhost/etc/hosts")); assertFalse("file://localhost/c:/ shouldn't be allowed by default", validator.isValid("file://localhost/c:/some.file")); // Turn it on, and check // Note - we need to enable local urls when working with file: validator = new UrlValidator(new String[] {"http","file"}, UrlValidator.ALLOW_LOCAL_URLS); assertTrue("http://apache.org/ should be allowed by default", validator.isValid("http://www.apache.org/test/index.html")); assertTrue("file:///c:/ should now be allowed", validator.isValid("file:///C:/some.file")); // Currently, we don't support the c:\ form assertFalse("file:///c:\\ shouldn't be allowed", validator.isValid("file:///C:\\some.file")); assertTrue("file:///etc/ should now be allowed", validator.isValid("file:///etc/hosts")); assertTrue("file://localhost/etc/ should now be allowed", validator.isValid("file://localhost/etc/hosts")); assertTrue("file://localhost/c:/ should now be allowed", validator.isValid("file://localhost/c:/some.file")); // These are never valid assertFalse("file://c:/ shouldn't ever be allowed, needs file:///c:/", validator.isValid("file://C:/some.file")); assertFalse("file://c:\\ shouldn't ever be allowed, needs file:///c:/", validator.isValid("file://C:\\some.file")); } static boolean incrementTestPartsIndex(int[] testPartsIndex, Object[] testParts) { boolean carry = true; //add 1 to lowest order part. boolean maxIndex = true; for (int testPartsIndexIndex = testPartsIndex.length - 1; testPartsIndexIndex >= 0; --testPartsIndexIndex) { int index = testPartsIndex[testPartsIndexIndex]; ResultPair[] part = (ResultPair[]) testParts[testPartsIndexIndex]; if (carry) { if (index < part.length - 1) { index++; testPartsIndex[testPartsIndexIndex] = index; carry = false; } else { testPartsIndex[testPartsIndexIndex] = 0; carry = true; } } maxIndex &= (index == (part.length - 1)); } return (!maxIndex); } private String testPartsIndextoString() { StringBuffer carryMsg = new StringBuffer("{"); for (int testPartsIndexIndex = 0; testPartsIndexIndex < testPartsIndex.length; ++testPartsIndexIndex) { carryMsg.append(testPartsIndex[testPartsIndexIndex]); if (testPartsIndexIndex < testPartsIndex.length - 1) { carryMsg.append(','); } else { carryMsg.append('}'); } } return carryMsg.toString(); } public void testValidateUrl() { assertTrue(true); } /** * Only used to debug the unit tests. * @param argv */ public static void main(String[] argv) { UrlValidatorTest fct = new UrlValidatorTest("url test"); fct.setUp(); fct.testIsValid(); fct.testIsValidScheme(); } //-------------------- Test data for creating a composite URL /** * The data given below approximates the 4 parts of a URL * ://? except that the port number * is broken out of authority to increase the number of permutations. * A complete URL is composed of a scheme+authority+port+path+query, * all of which must be individually valid for the entire URL to be considered * valid. */ ResultPair[] testUrlScheme = {new ResultPair("http://", true), new ResultPair("ftp://", true), new ResultPair("h3t://", true), new ResultPair("3ht://", false), new ResultPair("http:/", false), new ResultPair("http:", false), new ResultPair("http/", false), new ResultPair("://", false), new ResultPair("", true)}; ResultPair[] testUrlAuthority = {new ResultPair("www.google.com", true), new ResultPair("go.com", true), new ResultPair("go.au", true), new ResultPair("0.0.0.0", true), new ResultPair("255.255.255.255", true), new ResultPair("256.256.256.256", false), new ResultPair("255.com", true), new ResultPair("1.2.3.4.5", false), new ResultPair("1.2.3.4.", false), new ResultPair("1.2.3", false), new ResultPair(".1.2.3.4", false), new ResultPair("go.a", false), new ResultPair("go.a1a", false), new ResultPair("go.cc", true), new ResultPair("go.1aa", false), new ResultPair("aaa.", false), new ResultPair(".aaa", false), new ResultPair("aaa", false), new ResultPair("", false) }; ResultPair[] testUrlPort = {new ResultPair(":80", true), new ResultPair(":65535", true), new ResultPair(":0", true), new ResultPair("", true), new ResultPair(":-1", false), new ResultPair(":65636", true), new ResultPair(":65a", false) }; ResultPair[] testPath = {new ResultPair("/test1", true), new ResultPair("/t123", true), new ResultPair("/$23", true), new ResultPair("/..", false), new ResultPair("/../", false), new ResultPair("/test1/", true), new ResultPair("", true), new ResultPair("/test1/file", true), new ResultPair("/..//file", false), new ResultPair("/test1//file", false) }; //Test allow2slash, noFragment ResultPair[] testUrlPathOptions = {new ResultPair("/test1", true), new ResultPair("/t123", true), new ResultPair("/$23", true), new ResultPair("/..", false), new ResultPair("/../", false), new ResultPair("/test1/", true), new ResultPair("/#", false), new ResultPair("", true), new ResultPair("/test1/file", true), new ResultPair("/t123/file", true), new ResultPair("/$23/file", true), new ResultPair("/../file", false), new ResultPair("/..//file", false), new ResultPair("/test1//file", true), new ResultPair("/#/file", false) }; ResultPair[] testUrlQuery = {new ResultPair("?action=view", true), new ResultPair("?action=edit&mode=up", true), new ResultPair("", true) }; Object[] testUrlParts = {testUrlScheme, testUrlAuthority, testUrlPort, testPath, testUrlQuery}; Object[] testUrlPartsOptions = {testUrlScheme, testUrlAuthority, testUrlPort, testUrlPathOptions, testUrlQuery}; int[] testPartsIndex = {0, 0, 0, 0, 0}; //---------------- Test data for individual url parts ---------------- ResultPair[] testScheme = {new ResultPair("http", true), new ResultPair("ftp", false), new ResultPair("httpd", false), new ResultPair("telnet", false)}; } ././@LongLink100644 0 0 170 11711231552 10247 Lustar 0 0 commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/routines/checkdigit/ABANumberCheckDigitTest.javacommons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/routines/checkdigit/ABANumber100644 765 0 3061 11711227677 34602 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines.checkdigit; /** * ABA Number Check Digit Test. * * @version $Revision: 909009 $ * @since Validator 1.4 */ public class ABANumberCheckDigitTest extends AbstractCheckDigitTest { /** * Constructor * @param name test name */ public ABANumberCheckDigitTest(String name) { super(name); } /** * Set up routine & valid codes. */ protected void setUp() throws Exception { super.setUp(); routine = ABANumberCheckDigit.ABAN_CHECK_DIGIT; valid = new String[] { "123456780", "123123123", "011000015", "111000038", "231381116", "121181976" }; } } ././@LongLink100644 0 0 167 11711231552 10255 Lustar 0 0 commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/routines/checkdigit/AbstractCheckDigitTest.javacommons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/routines/checkdigit/AbstractC100644 765 0 22055 11711227677 34740 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines.checkdigit; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.List; import java.util.ArrayList; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import junit.framework.TestCase; /** * Luhn Check Digit Test. * * @version $Revision: 909004 $ * @since Validator 1.4 */ public abstract class AbstractCheckDigitTest extends TestCase { /** logging instance */ protected Log log = LogFactory.getLog(getClass()); /** Check digit routine being tested */ protected int checkDigitLth = 1; /** Check digit routine being tested */ protected CheckDigit routine; /** Array of valid code values */ protected String[] valid; /** Array of invalid code values */ protected String[] invalid = new String[] {"12345678A"}; /** code value which sums to zero */ protected String zeroSum = "0000000000"; /** Prefix for error messages */ protected String missingMessage = "Code is missing"; /** * Constructor * @param name test name */ public AbstractCheckDigitTest(String name) { super(name); } /** * Tear Down - clears routine and valid codes. */ protected void tearDown() throws Exception { super.tearDown(); valid = null; routine = null; } /** * Test isValid() for valid values. */ public void testIsValidTrue() { if (log.isDebugEnabled()) { log.debug("testIsValidTrue() for " + routine.getClass().getName()); } // test valid values for (int i = 0; i < valid.length; i++) { if (log.isDebugEnabled()) { log.debug(" " + i + " Testing Valid Code=[" + valid[i] + "]"); } assertTrue("valid[" + i +"]: " + valid[i], routine.isValid(valid[i])); } } /** * Test isValid() for invalid values. */ public void testIsValidFalse() { if (log.isDebugEnabled()) { log.debug("testIsValidFalse() for " + routine.getClass().getName()); } // test invalid code values for (int i = 0; i < invalid.length; i++) { if (log.isDebugEnabled()) { log.debug(" " + i + " Testing Invalid Code=[" + invalid[i] + "]"); } assertFalse("invalid[" + i +"]: " + invalid[i], routine.isValid(invalid[i])); } // test invalid check digit values String[] invalidCheckDigits = createInvalidCodes(valid); for (int i = 0; i < invalidCheckDigits.length; i++) { if (log.isDebugEnabled()) { log.debug(" " + i + " Testing Invalid Check Digit, Code=[" + invalidCheckDigits[i] + "]"); } assertFalse("invalid check digit[" + i +"]: " + invalidCheckDigits[i], routine.isValid(invalidCheckDigits[i])); } } /** * Test calculate() for valid values. */ public void testCalculateValid() { if (log.isDebugEnabled()) { log.debug("testCalculateValid() for " + routine.getClass().getName()); } // test valid values for (int i = 0; i < valid.length; i++) { String code = removeCheckDigit(valid[i]); String expected = checkDigit(valid[i]); try { if (log.isDebugEnabled()) { log.debug(" " + i + " Testing Valid Check Digit, Code=[" + code + "] expected=[" + expected + "]"); } assertEquals("valid[" + i +"]: " + valid[i], expected, routine.calculate(code)); } catch (Exception e) { fail("valid[" + i +"] threw " + e); } } } /** * Test calculate() for invalid values. */ public void testCalculateInvalid() { if (log.isDebugEnabled()) { log.debug("testCalculateInvalid() for " + routine.getClass().getName()); } // test invalid code values for (int i = 0; i < invalid.length; i++) { try { if (log.isDebugEnabled()) { log.debug(" " + i + " Testing Invalid Check Digit, Code=[" + invalid[i] + "]"); } routine.calculate(invalid[i]); fail("Invalid Characters[" + i + "]=" + invalid[i] + " - expected exception"); } catch (Exception e) { assertTrue("Invalid Character[" +i +"]=" + e.getMessage(), e.getMessage().startsWith("Invalid Character[")); } } } /** * Test missing code */ public void testMissingCode() { // isValid() null assertFalse("isValid() Null", routine.isValid(null)); // isValid() zero length assertFalse("isValid() Zero Length", routine.isValid("")); // calculate() null try { routine.calculate(null); fail("calculate() Null - expected exception"); } catch (Exception e) { assertEquals("calculate() Null", missingMessage, e.getMessage()); } // calculate() zero length try { routine.calculate(""); fail("calculate() Zero Length - expected exception"); } catch (Exception e) { assertEquals("calculate() Zero Length", missingMessage, e.getMessage()); } } /** * Test zero sum */ public void testZeroSum() { assertFalse("isValid() Zero Sum", routine.isValid(zeroSum)); try { routine.calculate(zeroSum); fail("Zero Sum - expected exception"); } catch (Exception e) { assertEquals("isValid() Zero Sum", "Invalid code, sum is zero", e.getMessage()); } } /** * Test check digit serialization. */ public void testSerialization() { // Serialize the check digit routine ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(routine); oos.flush(); oos.close(); } catch (Exception e) { fail(routine.getClass().getName() + " error during serialization: " + e); } // Deserialize the test object Object result = null; try { ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bais); result = ois.readObject(); bais.close(); } catch (Exception e) { fail(routine.getClass().getName() + " error during deserialization: " + e); } assertNotNull(result); } /** * Returns an array of codes with invalid check digits. * * @param codes Codes with valid check digits * @return Codes with invalid check digits */ protected String[] createInvalidCodes(String[] codes) { List list = new ArrayList(); // create invalid check digit values for (int i = 0; i < codes.length; i++) { String code = removeCheckDigit(codes[i]); String check = checkDigit(codes[i]); for (int j = 0; j < 10; j++) { String curr = "" + Character.forDigit(j, 10); if (!curr.equals(check)) { list.add(code + curr); } } } return (String[])list.toArray(new String[list.size()]); } /** * Returns a code with the Check Digit (i.e. last character) removed. * * @param code The code * @return The code without the check digit */ protected String removeCheckDigit(String code) { if (code == null || code.length() <= checkDigitLth) { return null; } return code.substring(0, code.length() - checkDigitLth); } /** * Returns the check digit (i.e. last character) for a code. * * @param code The code * @return The check digit */ protected String checkDigit(String code) { if (code == null || code.length() <= checkDigitLth) { return ""; } int start = code.length() - checkDigitLth; return code.substring(start); } } ././@LongLink100644 0 0 164 11711231552 10252 Lustar 0 0 commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/routines/checkdigit/CUSIPCheckDigitTest.javacommons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/routines/checkdigit/CUSIPChec100644 765 0 3362 11711227677 34520 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines.checkdigit; /** * CUSIP Check Digit Test. * * @version $Revision: 909009 $ * @since Validator 1.4 */ public class CUSIPCheckDigitTest extends AbstractCheckDigitTest { /** * Construct a new test. * @param name test name */ public CUSIPCheckDigitTest(String name) { super(name); } /** * Set up routine & valid codes. */ protected void setUp() throws Exception { super.setUp(); routine = CUSIPCheckDigit.CUSIP_CHECK_DIGIT; valid = new String[] {"037833100", "931142103", "837649128", "392690QT3", "594918104", "86770G101", "Y8295N109", "G8572F100" }; invalid = new String[] {"0378#3100"}; } } ././@LongLink100644 0 0 164 11711231552 10252 Lustar 0 0 commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/routines/checkdigit/EAN13CheckDigitTest.javacommons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/routines/checkdigit/EAN13Chec100644 765 0 2747 11711227677 34412 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines.checkdigit; /** * EAN-13 Check Digit Test. * * @version $Revision: 909009 $ * @since Validator 1.4 */ public class EAN13CheckDigitTest extends AbstractCheckDigitTest { /** * Constructor * @param name test name */ public EAN13CheckDigitTest(String name) { super(name); } /** * Set up routine & valid codes. */ protected void setUp() throws Exception { super.setUp(); routine = EAN13CheckDigit.EAN13_CHECK_DIGIT; valid = new String[] { "9780072129519", "9780764558313", "4025515373438", "0095673400332"}; } } ././@LongLink100644 0 0 163 11711231552 10251 Lustar 0 0 commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/routines/checkdigit/IBANCheckDigitTest.javacommons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/routines/checkdigit/IBANCheck100644 765 0 10570 11711227677 34540 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines.checkdigit; import java.util.ArrayList; import java.util.List; /** * EAN-13 Check Digit Test. * * @version $Revision: 909009 $ * @since Validator 1.4 */ public class IBANCheckDigitTest extends AbstractCheckDigitTest { /** * Constructor * @param name test name */ public IBANCheckDigitTest(String name) { super(name); checkDigitLth = 2; } /** * Set up routine & valid codes. */ protected void setUp() throws Exception { super.setUp(); routine = IBANCheckDigit.IBAN_CHECK_DIGIT; valid = new String[] { "AD1200012030200359100100", "AT611904300234573201", "AT611904300234573201", "BE68539007547034", "BE62510007547061", "CY17002001280000001200527600", "CZ6508000000192000145399", "DK5000400440116243", "EE382200221020145685", "FI2112345600000785", "FR1420041010050500013M02606", "DE89370400440532013000", "GI75NWBK000000007099453", "GR1601101250000000012300695", "HU42117730161111101800000000", "IS140159260076545510730339", "IE29AIBK93115212345678", "IT60X0542811101000000123456", "LV80BANK0000435195001", "LT121000011101001000", "LU280019400644750000", "NL91ABNA0417164300", "NO9386011117947", "PL27114020040000300201355387", "PT50000201231234567890154", "SK3112000000198742637541", "SI56191000000123438", "ES8023100001180000012345", "SE3550000000054910000003", "CH3900700115201849173", "GB29NWBK60161331926819" }; invalid = new String[] {"510007+47061BE63"}; zeroSum = null; missingMessage = "Invalid Code length=0"; } /** * Test zero sum */ public void testZeroSum() { // ignore, don't run this test } /** * Returns an array of codes with invalid check digits. * * @param codes Codes with valid check digits * @return Codes with invalid check digits */ protected String[] createInvalidCodes(String[] codes) { List list = new ArrayList(); // create invalid check digit values for (int i = 0; i < codes.length; i++) { String code = removeCheckDigit(codes[i]); String check = checkDigit(codes[i]); for (int j = 0; j < 96; j++) { String curr = j > 9 ? "" + j : "0" + j; if (!curr.equals(check)) { list.add(code.substring(0, 2) + curr + code.substring(4)); } } } return (String[])list.toArray(new String[list.size()]); } /** * Returns a code with the Check Digit (i.e. last character) removed. * * @param code The code * @return The code without the check digit */ protected String removeCheckDigit(String code) { return code.substring(0, 2) + "00" + code.substring(4); } /** * Returns the check digit (i.e. last character) for a code. * * @param code The code * @return The check digit */ protected String checkDigit(String code) { if (code == null || code.length() <= checkDigitLth) { return ""; } return code.substring(2, 4); } } ././@LongLink100644 0 0 165 11711231552 10253 Lustar 0 0 commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/routines/checkdigit/ISBN10CheckDigitTest.javacommons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/routines/checkdigit/ISBN10Che100644 765 0 2761 11711227677 34370 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines.checkdigit; /** * ISBN-10 Check Digit Test. * * @version $Revision: 909009 $ * @since Validator 1.4 */ public class ISBN10CheckDigitTest extends AbstractCheckDigitTest { /** * Constructor * @param name test name */ public ISBN10CheckDigitTest(String name) { super(name); } /** * Set up routine & valid codes. */ protected void setUp() throws Exception { super.setUp(); routine = ISBN10CheckDigit.ISBN10_CHECK_DIGIT; valid = new String[] { "1930110995", "020163385X", "1932394354", "1590596277" }; } } ././@LongLink100644 0 0 163 11711231552 10251 Lustar 0 0 commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/routines/checkdigit/ISBNCheckDigitTest.javacommons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/routines/checkdigit/ISBNCheck100644 765 0 6107 11711227677 34543 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines.checkdigit; /** * ISBN-10/ISBN-13 Check Digit Test. * * @version $Revision: 909009 $ * @since Validator 1.4 */ public class ISBNCheckDigitTest extends AbstractCheckDigitTest { /** * Constructor * @param name test name */ public ISBNCheckDigitTest(String name) { super(name); } /** * Set up routine & valid codes. */ protected void setUp() throws Exception { super.setUp(); routine = ISBNCheckDigit.ISBN_CHECK_DIGIT; valid = new String[] { "9780072129519", "9780764558313", "1930110995", "020163385X", "1590596277", // ISBN-10 Ubuntu Book "9781590596272" // ISBN-13 Ubuntu Book }; missingMessage = "ISBN Code is missing"; zeroSum = "000000000000"; } /** * Set up routine & valid codes. */ public void testInvalidLength() { assertFalse("isValid() Lth 9 ", routine.isValid("123456789")); assertFalse("isValid() Lth 11", routine.isValid("12345678901")); assertFalse("isValid() Lth 12", routine.isValid("123456789012")); assertFalse("isValid() Lth 14", routine.isValid("12345678901234")); try { routine.calculate("12345678"); fail("calculate() Lth 8 - expected exception"); } catch (Exception e) { assertEquals("calculate() Lth 8", "Invalid ISBN Length = 8", e.getMessage()); } try { routine.calculate("1234567890"); fail("calculate() Lth 10 - expected exception"); } catch (Exception e) { assertEquals("calculate() Lth 10", "Invalid ISBN Length = 10", e.getMessage()); } try { routine.calculate("12345678901"); fail("calculate() Lth 11 - expected exception"); } catch (Exception e) { assertEquals("calculate() Lth 11", "Invalid ISBN Length = 11", e.getMessage()); } try { routine.calculate("1234567890123"); fail("calculate() Lth 13 - expected exception"); } catch (Exception e) { assertEquals("calculate() Lth 13", "Invalid ISBN Length = 13", e.getMessage()); } } } ././@LongLink100644 0 0 163 11711231552 10251 Lustar 0 0 commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/routines/checkdigit/ISINCheckDigitTest.javacommons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/routines/checkdigit/ISINCheck100644 765 0 3236 11711227677 34552 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines.checkdigit; /** * ISIN Check Digit Test. * * @version $Revision: 909009 $ * @since Validator 1.4 */ public class ISINCheckDigitTest extends AbstractCheckDigitTest { /** * Constructor * @param name test name */ public ISINCheckDigitTest(String name) { super(name); } /** * Set up routine & valid codes. */ protected void setUp() throws Exception { super.setUp(); routine = ISINCheckDigit.ISIN_CHECK_DIGIT; valid = new String[] {"US0378331005", "BMG8571G1096", "AU0000XVGZA3", "GB0002634946", "FR0004026250", "DK0009763344" }; invalid = new String[] {"0378#3100"}; } } ././@LongLink100644 0 0 163 11711231552 10251 Lustar 0 0 commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/routines/checkdigit/LuhnCheckDigitTest.javacommons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/routines/checkdigit/LuhnCheck100644 765 0 3675 11711227677 34725 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines.checkdigit; /** * Luhn Check Digit Test. * * @version $Revision: 909009 $ * @since Validator 1.4 */ public class LuhnCheckDigitTest extends AbstractCheckDigitTest { private static final String VALID_VISA = "4417123456789113"; private static final String VALID_SHORT_VISA = "4222222222222"; private static final String VALID_AMEX = "378282246310005"; private static final String VALID_MASTERCARD = "5105105105105100"; private static final String VALID_DISCOVER = "6011000990139424"; private static final String VALID_DINERS = "30569309025904"; /** * Constructor * @param name test name */ public LuhnCheckDigitTest(String name) { super(name); } /** * Set up routine & valid codes. */ protected void setUp() throws Exception { super.setUp(); routine = LuhnCheckDigit.LUHN_CHECK_DIGIT; valid = new String[] { VALID_VISA, VALID_SHORT_VISA, VALID_AMEX, VALID_MASTERCARD, VALID_DISCOVER, VALID_DINERS}; } } ././@LongLink100644 0 0 164 11711231552 10252 Lustar 0 0 commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/routines/checkdigit/SedolCheckDigitTest.javacommons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/routines/checkdigit/SedolChec100644 765 0 3102 11711227677 34673 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines.checkdigit; /** * ISIN Check Digit Test. * * @version $Revision: 909009 $ * @since Validator 1.4 */ public class SedolCheckDigitTest extends AbstractCheckDigitTest { /** * Constructor * @param name test name */ public SedolCheckDigitTest(String name) { super(name); } /** * Set up routine & valid codes. */ protected void setUp() throws Exception { super.setUp(); routine = SedolCheckDigit.SEDOL_CHECK_DIGIT; valid = new String[] { "0263494", "0870612", "B06LQ97", "3437575", "B07LF55", }; invalid = new String[] {"123#567"}; zeroSum = "0000000"; } } ././@LongLink100644 0 0 167 11711231552 10255 Lustar 0 0 commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/routines/checkdigit/VerhoeffCheckDigitTest.javacommons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/routines/checkdigit/VerhoeffC100644 765 0 3115 11711227677 34715 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.routines.checkdigit; /** * Verhoeff Check Digit Test. * * @version $Revision: 909009 $ * @since Validator 1.4 */ public class VerhoeffCheckDigitTest extends AbstractCheckDigitTest { /** * Construct a new test. * @param name test name */ public VerhoeffCheckDigitTest(String name) { super(name); } /** * Set up routine & valid codes. */ protected void setUp() throws Exception { super.setUp(); routine = VerhoeffCheckDigit.VERHOEFF_CHECK_DIGIT; valid = new String[] { "15", "1428570", "12345678902" }; } /** * Test zero sum */ public void testZeroSum() { // ignore, don't run this test } } commons-validator-1.4.0-src/src/test/java/org/apache/commons/validator/util/FlagsTest.java100644 765 0 5666 11711227700 32671 0ustarsimonetripodiwheel 0 0 /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.validator.util; import junit.framework.TestCase; /** * Test the Flags class. * * @version $Revision: 658832 $ $Date: 2008-05-21 21:57:21 +0200 (Wed, 21 May 2008) $ */ public class FlagsTest extends TestCase { /** * Declare some flags for testing. */ private static final long LONG_FLAG = 1; private static final long LONG_FLAG_2 = 2; private static final int INT_FLAG = 4; /** * Constructor for FlagsTest. */ public FlagsTest(String name) { super(name); } public void testHashCode() { Flags f = new Flags(45); assertEquals(f.hashCode(), 45); } public void testGetFlags() { Flags f = new Flags(45); assertEquals(f.getFlags(), 45); } public void testIsOnOff() { Flags f = new Flags(); f.turnOn(LONG_FLAG); f.turnOn(INT_FLAG); assertTrue(f.isOn(LONG_FLAG)); assertTrue(!f.isOff(LONG_FLAG)); assertTrue(f.isOn(INT_FLAG)); assertTrue(!f.isOff(INT_FLAG)); assertTrue(f.isOff(LONG_FLAG_2)); } public void testTurnOnOff() { } public void testTurnOff() { } public void testTurnOffAll() { Flags f = new Flags(98432); f.turnOffAll(); assertEquals(0, f.getFlags()); } public void testClear() { Flags f = new Flags(98432); f.clear(); assertEquals(0, f.getFlags()); } public void testTurnOnAll() { Flags f = new Flags(); f.turnOnAll(); assertEquals(Long.MAX_VALUE, f.getFlags()); } /** * Test for Object clone() */ public void testClone() { } /** * Test for boolean equals(Object) */ public void testEqualsObject() { } /** * Test for String toString() */ public void testToString() { Flags f = new Flags(); String s = f.toString(); assertEquals(64, s.length()); f.turnOn(INT_FLAG); s = f.toString(); assertEquals(64, s.length()); assertEquals( "0000000000000000000000000000000000000000000000000000000000000100", s); } } commons-validator-1.4.0-src/src/test/resources/org/apache/commons/validator/DateTest-config.xml100644 765 0 3537 11711227700 33743 0ustarsimonetripodiwheel 0 0
    datePattern MM/dd/yyyy
    commons-validator-1.4.0-src/src/test/resources/org/apache/commons/validator/EmailTest-config.xml100644 765 0 2603 11711227700 34106 0ustarsimonetripodiwheel 0 0
    ././@LongLink100644 0 0 152 11711231552 10247 Lustar 0 0 commons-validator-1.4.0-src/src/test/resources/org/apache/commons/validator/EntityImportTest-byteform.xmlcommons-validator-1.4.0-src/src/test/resources/org/apache/commons/validator/EntityImportTest-bytefor100644 765 0 1525 11711227700 35136 0ustarsimonetripodiwheel 0 0
    ././@LongLink100644 0 0 150 11711231552 10245 Lustar 0 0 commons-validator-1.4.0-src/src/test/resources/org/apache/commons/validator/EntityImportTest-config.xmlcommons-validator-1.4.0-src/src/test/resources/org/apache/commons/validator/EntityImportTest-config.100644 765 0 2563 11711227700 35012 0ustarsimonetripodiwheel 0 0 ]> &byteform; ././@LongLink100644 0 0 145 11711231552 10251 Lustar 0 0 commons-validator-1.4.0-src/src/test/resources/org/apache/commons/validator/ExceptionTest-config.xmlcommons-validator-1.4.0-src/src/test/resources/org/apache/commons/validator/ExceptionTest-config.xml100644 765 0 2642 11711227700 35020 0ustarsimonetripodiwheel 0 0
    ././@LongLink100644 0 0 145 11711231552 10251 Lustar 0 0 commons-validator-1.4.0-src/src/test/resources/org/apache/commons/validator/ExtensionTest-config.xmlcommons-validator-1.4.0-src/src/test/resources/org/apache/commons/validator/ExtensionTest-config.xml100644 765 0 4237 11711227700 35040 0ustarsimonetripodiwheel 0 0
    ././@LongLink100644 0 0 160 11711231552 10246 Lustar 0 0 commons-validator-1.4.0-src/src/test/resources/org/apache/commons/validator/GenericTypeValidatorTest-config.xmlcommons-validator-1.4.0-src/src/test/resources/org/apache/commons/validator/GenericTypeValidatorTest100644 765 0 12547 11711227700 35131 0ustarsimonetripodiwheel 0 0
    commons-validator-1.4.0-src/src/test/resources/org/apache/commons/validator/LocaleTest-config.xml100644 765 0 5472 11711227700 34265 0ustarsimonetripodiwheel 0 0
    ././@LongLink100644 0 0 161 11711231552 10247 Lustar 0 0 commons-validator-1.4.0-src/src/test/resources/org/apache/commons/validator/MultipleConfigFilesTest-1-config.xmlcommons-validator-1.4.0-src/src/test/resources/org/apache/commons/validator/MultipleConfigFilesTest-100644 765 0 5526 11711227700 35005 0ustarsimonetripodiwheel 0 0 testConstName1 testConstValue1
    var11 ${testConstName1} var12 ${testConstName2}
    testConstName1_fr testConstValue1_fr
    var11_fr ${testConstName1_fr} var12_fr ${testConstName2_fr}
    ././@LongLink100644 0 0 161 11711231552 10247 Lustar 0 0 commons-validator-1.4.0-src/src/test/resources/org/apache/commons/validator/MultipleConfigFilesTest-2-config.xmlcommons-validator-1.4.0-src/src/test/resources/org/apache/commons/validator/MultipleConfigFilesTest-100644 765 0 5061 11711227700 34777 0ustarsimonetripodiwheel 0 0 testConstName2 testConstValue2
    var21 ${testConstName1} var22 ${testConstName2}
    testConstName2_fr testConstValue2_fr
    var21_fr ${testConstName1_fr} var22_fr ${testConstName2_fr}
    ././@LongLink100644 0 0 145 11711231552 10251 Lustar 0 0 commons-validator-1.4.0-src/src/test/resources/org/apache/commons/validator/MultipleTests-config.xmlcommons-validator-1.4.0-src/src/test/resources/org/apache/commons/validator/MultipleTests-config.xml100644 765 0 4455 11711227700 35044 0ustarsimonetripodiwheel 0 0
    ././@LongLink100644 0 0 145 11711231552 10251 Lustar 0 0 commons-validator-1.4.0-src/src/test/resources/org/apache/commons/validator/ParameterTest-config.xmlcommons-validator-1.4.0-src/src/test/resources/org/apache/commons/validator/ParameterTest-config.xml100644 765 0 3423 11711227700 35000 0ustarsimonetripodiwheel 0 0
    ././@LongLink100644 0 0 146 11711231552 10252 Lustar 0 0 commons-validator-1.4.0-src/src/test/resources/org/apache/commons/validator/RequiredIfTest-config.xmlcommons-validator-1.4.0-src/src/test/resources/org/apache/commons/validator/RequiredIfTest-config.xm100644 765 0 4261 11711227700 34744 0ustarsimonetripodiwheel 0 0
    field[0] lastName fieldTest[0] NOTNULL field[0] firstName fieldTest[0] NOTNULL
    ././@LongLink100644 0 0 150 11711231552 10245 Lustar 0 0 commons-validator-1.4.0-src/src/test/resources/org/apache/commons/validator/RequiredNameTest-config.xmlcommons-validator-1.4.0-src/src/test/resources/org/apache/commons/validator/RequiredNameTest-config.100644 765 0 3172 11711227700 34721 0ustarsimonetripodiwheel 0 0
    ././@LongLink100644 0 0 150 11711231552 10245 Lustar 0 0 commons-validator-1.4.0-src/src/test/resources/org/apache/commons/validator/RetrieveFormTest-config.xmlcommons-validator-1.4.0-src/src/test/resources/org/apache/commons/validator/RetrieveFormTest-config.100644 765 0 11727 11711227700 34776 0ustarsimonetripodiwheel 0 0
    localeVar default
    localeVar default
    localeVar default
    localeVar default
    localeVar fr
    localeVar fr
    localeVar fr
    localeVar fr_FR
    localeVar fr_FR
    localeVar fr_CA
    localeVar fr_CA
    localeVar fr_CA_XXX
    commons-validator-1.4.0-src/src/test/resources/org/apache/commons/validator/TestNumber-config.xml100644 765 0 6157 11711227700 34317 0ustarsimonetripodiwheel 0 0
    ././@LongLink100644 0 0 154 11711231552 10251 Lustar 0 0 commons-validator-1.4.0-src/src/test/resources/org/apache/commons/validator/ValidatorResultsTest-config.xmlcommons-validator-1.4.0-src/src/test/resources/org/apache/commons/validator/ValidatorResultsTest-con100644 765 0 4455 11711227700 35110 0ustarsimonetripodiwheel 0 0
    commons-validator-1.4.0-src/src/test/resources/org/apache/commons/validator/VarTest-config.xml100644 765 0 4031 11711227700 33604 0ustarsimonetripodiwheel 0 0
    var-1-1 value-1-1 jstype-1-1 var-2-1 value-2-1 jstype-2-1 var-2-2 value-2-2
    int" classname="org.apache.commons.validator.GenericValidatorImpl" method="validateInt" methodParams="java.lang.Object,org.apache.commons.validator.Field" msg=""/>