(schemes.length);
+ for(int i=0; i < schemes.length; i++) {
+ allowedSchemes.add(schemes[i].toLowerCase(Locale.ENGLISH));
+ }
+ }
+
+ this.authorityValidator = authorityValidator;
+ }
+
+ /**
+ * Checks if a field has a valid url address.
+ *
+ * Note that the method calls #isValidAuthority()
+ * which checks that the domain is valid.
+ *
+ * @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;
+ }
+
+ // 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)) {// Special case - file: allows an empty authority
+ if (authority != null) {
+ if (authority.contains(":")) { // but cannot allow trailing :
+ return false;
+ }
+ }
+ // drop through to continue validation
+ } else { // not file:
+ // 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 schemes are allowed.
+ * Otherwise the default schemes are "http", "https", "ftp".
+ * Matching is case-blind.
+ * @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;
+ }
+
+ // TODO could be removed if external schemes were checked in the ctor before being stored
+ if (!SCHEME_PATTERN.matcher(scheme).matches()) {
+ return false;
+ }
+
+ if (isOff(ALLOW_ALL_SCHEMES) && !allowedSchemes.contains(scheme.toLowerCase(Locale.ENGLISH))) {
+ 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.
+ * Note: this implementation validates the domain unless a RegexValidator was provided.
+ * If a RegexValidator was supplied and it matches, then the authority is regarded
+ * as valid with no further checks, otherwise the method checks against the
+ * AUTHORITY_PATTERN and the DomainValidator (ALLOW_LOCAL_URLS)
+ * @param authority Authority value to validate, alllows IDN
+ * @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 && authorityValidator.isValid(authority)) {
+ return true;
+ }
+ // convert to ASCII if possible
+ final String authorityASCII = DomainValidator.unicodeToASCII(authority);
+
+ Matcher authorityMatcher = AUTHORITY_PATTERN.matcher(authorityASCII);
+ if (!authorityMatcher.matches()) {
+ return false;
+ }
+
+ // We have to process IPV6 separately because that is parsed in a different group
+ String ipv6 = authorityMatcher.group(PARSE_AUTHORITY_IPV6);
+ if (ipv6 != null) {
+ InetAddressValidator inetAddressValidator = InetAddressValidator.getInstance();
+ if (!inetAddressValidator.isValidInet6Address(ipv6)) {
+ return false;
+ }
+ } else {
+ 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 IPv4 address
+ InetAddressValidator inetAddressValidator = InetAddressValidator.getInstance();
+ if (!inetAddressValidator.isValidInet4Address(hostLocation)) {
+ // isn't IPv4, so the URL is invalid
+ return false;
+ }
+ }
+ String port = authorityMatcher.group(PARSE_AUTHORITY_PORT);
+ if (port != null && port.length() > 0) {
+ try {
+ int iPort = Integer.parseInt(port);
+ if (iPort < 0 || iPort > MAX_UNSIGNED_16_BIT_INT) {
+ return false;
+ }
+ } catch (NumberFormatException nfe) {
+ return false; // this can happen for big numbers
+ }
+ }
+ }
+
+ 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;
+ }
+
+ try {
+ URI uri = new URI(null,null,path,null);
+ String norm = uri.normalize().getPath();
+ if (norm.startsWith("/../") // Trying to go via the parent dir
+ || norm.equals("/..")) { // Trying to go to the parent dir
+ return false;
+ }
+ } catch (URISyntaxException e) {
+ return false;
+ }
+
+ int slash2Count = countToken("//", path);
+ if (isOff(ALLOW_2_SLASHES) && (slash2Count > 0)) {
+ 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 (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 (options & flag) == 0;
+ }
+
+ // Unit test access to pattern matcher
+ Matcher matchURL(String value) {
+ return URL_PATTERN.matcher(value);
+ }
+}
Index: 3rdParty_sources/commons-validator/org/apache/commons/validator/routines/checkdigit/ABANumberCheckDigit.java
===================================================================
diff -u
--- 3rdParty_sources/commons-validator/org/apache/commons/validator/routines/checkdigit/ABANumberCheckDigit.java (revision 0)
+++ 3rdParty_sources/commons-validator/org/apache/commons/validator/routines/checkdigit/ABANumberCheckDigit.java (revision 08255e7eeeaeba69421502fb648a1b6e98e92610)
@@ -0,0 +1,85 @@
+/*
+ * 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: 1739356 $
+ * @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); // CHECKSTYLE IGNORE MagicNumber
+ }
+
+ /**
+ * 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.
+ */
+ @Override
+ protected int weightedValue(int charValue, int leftPos, int rightPos) {
+ int weight = POSITION_WEIGHT[rightPos % 3]; // CHECKSTYLE IGNORE MagicNumber
+ return charValue * weight;
+ }
+
+}
Index: 3rdParty_sources/commons-validator/org/apache/commons/validator/routines/checkdigit/CUSIPCheckDigit.java
===================================================================
diff -u
--- 3rdParty_sources/commons-validator/org/apache/commons/validator/routines/checkdigit/CUSIPCheckDigit.java (revision 0)
+++ 3rdParty_sources/commons-validator/org/apache/commons/validator/routines/checkdigit/CUSIPCheckDigit.java (revision 08255e7eeeaeba69421502fb648a1b6e98e92610)
@@ -0,0 +1,100 @@
+/*
+ * 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: 1739356 $
+ * @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); // CHECKSTYLE IGNORE MagicNumber
+ }
+
+ /**
+ * 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 position of the character in the code, counting from right to left
+ * @return The integer value of the character
+ * @throws CheckDigitException if character is not alphanumeric
+ */
+ @Override
+ protected int toInt(char character, int leftPos, int rightPos)
+ throws CheckDigitException {
+ int charValue = Character.getNumericValue(character);
+ // the final character is only allowed to reach 9
+ final int charMax = rightPos == 1 ? 9 : 35; // CHECKSTYLE IGNORE MagicNumber
+ if (charValue < 0 || charValue > charMax) {
+ throw new CheckDigitException("Invalid Character[" +
+ leftPos + "," + rightPos + "] = '" + charValue + "' out of range 0 to " + charMax);
+ }
+ return charValue;
+ }
+
+ /**
+ * Calculates the weighted value of a charcter in the
+ * code at a specified position.
+ *
+ * For CUSIP (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.
+ */
+ @Override
+ protected int weightedValue(int charValue, int leftPos, int rightPos) {
+ int weight = POSITION_WEIGHT[rightPos % 2];
+ int weightedValue = (charValue * weight);
+ return ModulusCheckDigit.sumDigits(weightedValue);
+ }
+}
Index: 3rdParty_sources/commons-validator/org/apache/commons/validator/routines/checkdigit/CheckDigit.java
===================================================================
diff -u
--- 3rdParty_sources/commons-validator/org/apache/commons/validator/routines/checkdigit/CheckDigit.java (revision 0)
+++ 3rdParty_sources/commons-validator/org/apache/commons/validator/routines/checkdigit/CheckDigit.java (revision 08255e7eeeaeba69421502fb648a1b6e98e92610)
@@ -0,0 +1,71 @@
+/*
+ * 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.
+ *
+ *
+ * CheckDigit is used by the new generic @link 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: 1649287 $
+ * @since Validator 1.4
+ */
+public interface CheckDigit {
+
+ /**
+ * Calculates the Check Digit for a code.
+ *
+ * @param code The code to calculate the Check Digit for.
+ * The string must not include the check digit
+ * @return The calculated Check Digit
+ * @throws CheckDigitException if an error occurs.
+ */
+ String calculate(String code) throws CheckDigitException;
+
+ /**
+ * Validates the check digit for the code.
+ *
+ * @param code The code to validate, the string must include the check digit.
+ * @return true
if the check digit is valid, otherwise
+ * false
.
+ */
+ boolean isValid(String code);
+
+}
Index: 3rdParty_sources/commons-validator/org/apache/commons/validator/routines/checkdigit/CheckDigitException.java
===================================================================
diff -u
--- 3rdParty_sources/commons-validator/org/apache/commons/validator/routines/checkdigit/CheckDigitException.java (revision 0)
+++ 3rdParty_sources/commons-validator/org/apache/commons/validator/routines/checkdigit/CheckDigitException.java (revision 08255e7eeeaeba69421502fb648a1b6e98e92610)
@@ -0,0 +1,55 @@
+/*
+ * 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: 1649191 $
+ * @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);
+ }
+
+}
Index: 3rdParty_sources/commons-validator/org/apache/commons/validator/routines/checkdigit/EAN13CheckDigit.java
===================================================================
diff -u
--- 3rdParty_sources/commons-validator/org/apache/commons/validator/routines/checkdigit/EAN13CheckDigit.java (revision 0)
+++ 3rdParty_sources/commons-validator/org/apache/commons/validator/routines/checkdigit/EAN13CheckDigit.java (revision 08255e7eeeaeba69421502fb648a1b6e98e92610)
@@ -0,0 +1,78 @@
+/*
+ * 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: 1739356 $
+ * @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); // CHECKSTYLE IGNORE MagicNumber
+ }
+
+ /**
+ * 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.
+ */
+ @Override
+ protected int weightedValue(int charValue, int leftPos, int rightPos) {
+ int weight = POSITION_WEIGHT[rightPos % 2];
+ return charValue * weight;
+ }
+}
Index: 3rdParty_sources/commons-validator/org/apache/commons/validator/routines/checkdigit/IBANCheckDigit.java
===================================================================
diff -u
--- 3rdParty_sources/commons-validator/org/apache/commons/validator/routines/checkdigit/IBANCheckDigit.java (revision 0)
+++ 3rdParty_sources/commons-validator/org/apache/commons/validator/routines/checkdigit/IBANCheckDigit.java (revision 08255e7eeeaeba69421502fb648a1b6e98e92610)
@@ -0,0 +1,137 @@
+/*
+ * 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 routine is based on the ISO 7064 Mod 97,10 check digit calculation 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 calculation the check digit value should be set to zero (i.e.
+ * CC00nnnnnnn
in this example.
+ *
+ * Note: the class does not check the format of the IBAN number, only the check digits.
+ *
+ * For further information see
+ * Wikipedia -
+ * IBAN number.
+ *
+ * @version $Revision: 1739357 $
+ * @since Validator 1.4
+ */
+public final class IBANCheckDigit implements CheckDigit, Serializable {
+
+ private static final int MIN_CODE_LEN = 5;
+
+ private static final long serialVersionUID = -3600191725934382801L;
+
+ private static final int MAX_ALPHANUMERIC_VALUE = 35; // Character.getNumericValue('Z')
+
+ /** 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 of an IBAN code.
+ *
+ * @param code The code to validate
+ * @return true
if the check digit is valid, otherwise
+ * false
+ */
+ @Override
+ public boolean isValid(String code) {
+ if (code == null || code.length() < MIN_CODE_LEN) {
+ return false;
+ }
+ String check = code.substring(2,4); // CHECKSTYLE IGNORE MagicNumber
+ if ("00".equals(check) || "01".equals(check) || "99".equals(check)) {
+ 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 is set to the value "00
".
+ *
+ * @param code The code to calculate the Check Digit for
+ * @return The calculated Check Digit as 2 numeric decimal characters, e.g. "42"
+ * @throws CheckDigitException if an error occurs calculating
+ * the check digit for the specified code
+ */
+ @Override
+ public String calculate(String code) throws CheckDigitException {
+ if (code == null || code.length() < MIN_CODE_LEN) {
+ throw new CheckDigitException("Invalid Code length=" +
+ (code == null ? 0 : code.length()));
+ }
+ code = code.substring(0, 2) + "00" + code.substring(4); // CHECKSTYLE IGNORE MagicNumber
+ int modulusResult = calculateModulus(code);
+ int charValue = (98 - modulusResult); // CHECKSTYLE IGNORE MagicNumber
+ String checkDigit = Integer.toString(charValue);
+ return (charValue > 9 ? checkDigit : "0" + checkDigit); // CHECKSTYLE IGNORE MagicNumber
+ }
+
+ /**
+ * 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); // CHECKSTYLE IGNORE MagicNumber
+ long total = 0;
+ for (int i = 0; i < reformattedCode.length(); i++) {
+ int charValue = Character.getNumericValue(reformattedCode.charAt(i));
+ if (charValue < 0 || charValue > MAX_ALPHANUMERIC_VALUE) {
+ throw new CheckDigitException("Invalid Character[" +
+ i + "] = '" + charValue + "'");
+ }
+ total = (charValue > 9 ? total * 100 : total * 10) + charValue; // CHECKSTYLE IGNORE MagicNumber
+ if (total > MAX) {
+ total = total % MODULUS;
+ }
+ }
+ return (int)(total % MODULUS);
+ }
+
+}
Index: 3rdParty_sources/commons-validator/org/apache/commons/validator/routines/checkdigit/ISBN10CheckDigit.java
===================================================================
diff -u
--- 3rdParty_sources/commons-validator/org/apache/commons/validator/routines/checkdigit/ISBN10CheckDigit.java (revision 0)
+++ 3rdParty_sources/commons-validator/org/apache/commons/validator/routines/checkdigit/ISBN10CheckDigit.java (revision 08255e7eeeaeba69421502fb648a1b6e98e92610)
@@ -0,0 +1,115 @@
+/*
+ * 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: 1739356 $
+ * @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); // CHECKSTYLE IGNORE MagicNumber
+ }
+
+ /**
+ * 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.
+ */
+ @Override
+ 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 position of the character in the code, counting from right to left
+ * @return The integer value of the character.
+ * @throws CheckDigitException if an error occurs.
+ */
+ @Override
+ protected int toInt(char character, int leftPos, int rightPos)
+ throws CheckDigitException {
+ if (rightPos == 1 && character == 'X') {
+ return 10; // CHECKSTYLE IGNORE MagicNumber
+ }
+ 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.
+ */
+ @Override
+ protected String toCheckDigit(int charValue)
+ throws CheckDigitException {
+ if (charValue == 10) { // CHECKSTYLE IGNORE MagicNumber
+ return "X";
+ }
+ return super.toCheckDigit(charValue);
+ }
+
+}
Index: 3rdParty_sources/commons-validator/org/apache/commons/validator/routines/checkdigit/ISBNCheckDigit.java
===================================================================
diff -u
--- 3rdParty_sources/commons-validator/org/apache/commons/validator/routines/checkdigit/ISBNCheckDigit.java (revision 0)
+++ 3rdParty_sources/commons-validator/org/apache/commons/validator/routines/checkdigit/ISBNCheckDigit.java (revision 08255e7eeeaeba69421502fb648a1b6e98e92610)
@@ -0,0 +1,106 @@
+/*
+ * 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: 1739357 $
+ * @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.
+ */
+ @Override
+ 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) { // CHECKSTYLE IGNORE MagicNumber
+ return ISBN10_CHECK_DIGIT.calculate(code);
+ } else if (code.length() == 12) { // CHECKSTYLE IGNORE MagicNumber
+ 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
.
+ */
+ @Override
+ public boolean isValid(String code) {
+ if (code == null) {
+ return false;
+ } else if (code.length() == 10) { // CHECKSTYLE IGNORE MagicNumber
+ return ISBN10_CHECK_DIGIT.isValid(code);
+ } else if (code.length() == 13) { // CHECKSTYLE IGNORE MagicNumber
+ return ISBN13_CHECK_DIGIT.isValid(code);
+ } else {
+ return false;
+ }
+ }
+
+}
Index: 3rdParty_sources/commons-validator/org/apache/commons/validator/routines/checkdigit/ISINCheckDigit.java
===================================================================
diff -u
--- 3rdParty_sources/commons-validator/org/apache/commons/validator/routines/checkdigit/ISINCheckDigit.java (revision 0)
+++ 3rdParty_sources/commons-validator/org/apache/commons/validator/routines/checkdigit/ISINCheckDigit.java (revision 08255e7eeeaeba69421502fb648a1b6e98e92610)
@@ -0,0 +1,111 @@
+/*
+ * 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: 1739356 $
+ * @since Validator 1.4
+ */
+public final class ISINCheckDigit extends ModulusCheckDigit {
+
+ private static final long serialVersionUID = -1239211208101323599L;
+
+ private static final int MAX_ALPHANUMERIC_VALUE = 35; // Character.getNumericValue('Z')
+
+ /** 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); // CHECKSTYLE IGNORE MagicNumber
+ }
+
+ /**
+ * 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
+ */
+ @Override
+ protected int calculateModulus(String code, boolean includesCheckDigit) throws CheckDigitException {
+ StringBuilder transformed = new StringBuilder(code.length() * 2);
+ if (includesCheckDigit) {
+ char checkDigit = code.charAt(code.length()-1); // fetch the last character
+ if (!Character.isDigit(checkDigit)){
+ throw new CheckDigitException("Invalid checkdigit["+ checkDigit+ "] in " + code);
+ }
+ }
+ for (int i = 0; i < code.length(); i++) {
+ int charValue = Character.getNumericValue(code.charAt(i));
+ if (charValue < 0 || charValue > MAX_ALPHANUMERIC_VALUE) {
+ throw new CheckDigitException("Invalid Character[" +
+ (i + 1) + "] = '" + charValue + "'");
+ }
+ // this converts alphanumerics to two digits
+ // so there is no need to overload toInt()
+ 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.
+ */
+ @Override
+ protected int weightedValue(int charValue, int leftPos, int rightPos) {
+ int weight = POSITION_WEIGHT[rightPos % 2];
+ int weightedValue = (charValue * weight);
+ return ModulusCheckDigit.sumDigits(weightedValue);
+ }
+}
Index: 3rdParty_sources/commons-validator/org/apache/commons/validator/routines/checkdigit/ISSNCheckDigit.java
===================================================================
diff -u
--- 3rdParty_sources/commons-validator/org/apache/commons/validator/routines/checkdigit/ISSNCheckDigit.java (revision 0)
+++ 3rdParty_sources/commons-validator/org/apache/commons/validator/routines/checkdigit/ISSNCheckDigit.java (revision 08255e7eeeaeba69421502fb648a1b6e98e92610)
@@ -0,0 +1,85 @@
+/*
+ * 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;
+
+/**
+ * International Standard Serial Number (ISSN)
+ * is an eight-digit serial number used to
+ * uniquely identify a serial publication.
+ *
+ * The format is:
+ *
+ * ISSN dddd-dddC
+ * where:
+ * d = decimal digit (0-9)
+ * C = checksum (0-9 or X)
+ *
+ * The checksum is formed by adding the first 7 digits multiplied by
+ * the position in the entire number (counting from the right).
+ * For example, abcd-efg would be 8a + 7b + 6c + 5d + 4e +3f +2g.
+ * The check digit is modulus 11, where the value 10 is represented by 'X'
+ * For example:
+ * ISSN 0317-8471
+ * ISSN 1050-124X
+ *
+ *
+ * Note: This class expects the input to be numeric only,
+ * with all formatting removed.
+ * For example:
+ *
+ * 03178471
+ * 1050124X
+ *
+ * @since 1.5.0
+ */
+public final class ISSNCheckDigit extends ModulusCheckDigit {
+
+
+ private static final long serialVersionUID = 1L;
+
+ /** Singleton ISSN Check Digit instance */
+ public static final CheckDigit ISSN_CHECK_DIGIT = new ISSNCheckDigit();
+
+ /**
+ * Creates the instance using a checkdigit modulus of 11
+ */
+ public ISSNCheckDigit() {
+ super(11); // CHECKSTYLE IGNORE MagicNumber
+ }
+
+ @Override
+ protected int weightedValue(int charValue, int leftPos, int rightPos) throws CheckDigitException {
+ return charValue * (9 - leftPos); // CHECKSTYLE IGNORE MagicNumber
+ }
+
+ @Override
+ protected String toCheckDigit(int charValue) throws CheckDigitException {
+ if (charValue == 10) { // CHECKSTYLE IGNORE MagicNumber
+ return "X";
+ }
+ return super.toCheckDigit(charValue);
+ }
+
+ @Override
+ protected int toInt(char character, int leftPos, int rightPos)
+ throws CheckDigitException {
+ if (rightPos == 1 && character == 'X') {
+ return 10; // CHECKSTYLE IGNORE MagicNumber
+ }
+ return super.toInt(character, leftPos, rightPos);
+ }
+}
Index: 3rdParty_sources/commons-validator/org/apache/commons/validator/routines/checkdigit/LuhnCheckDigit.java
===================================================================
diff -u
--- 3rdParty_sources/commons-validator/org/apache/commons/validator/routines/checkdigit/LuhnCheckDigit.java (revision 0)
+++ 3rdParty_sources/commons-validator/org/apache/commons/validator/routines/checkdigit/LuhnCheckDigit.java (revision 08255e7eeeaeba69421502fb648a1b6e98e92610)
@@ -0,0 +1,76 @@
+/*
+ * 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: 1739356 $
+ * @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); // CHECKSTYLE IGNORE MagicNumber
+ }
+
+ /**
+ * 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.
+ */
+ @Override
+ protected int weightedValue(int charValue, int leftPos, int rightPos) {
+ int weight = POSITION_WEIGHT[rightPos % 2]; // CHECKSTYLE IGNORE MagicNumber
+ int weightedValue = charValue * weight;
+ return weightedValue > 9 ? (weightedValue - 9) : weightedValue; // CHECKSTYLE IGNORE MagicNumber
+ }
+}
Index: 3rdParty_sources/commons-validator/org/apache/commons/validator/routines/checkdigit/ModulusCheckDigit.java
===================================================================
diff -u
--- 3rdParty_sources/commons-validator/org/apache/commons/validator/routines/checkdigit/ModulusCheckDigit.java (revision 0)
+++ 3rdParty_sources/commons-validator/org/apache/commons/validator/routines/checkdigit/ModulusCheckDigit.java (revision 08255e7eeeaeba69421502fb648a1b6e98e92610)
@@ -0,0 +1,204 @@
+/*
+ * 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 single-digit 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: 1739357 $
+ * @since Validator 1.4
+ */
+public abstract class ModulusCheckDigit implements CheckDigit, Serializable {
+
+ private static final long serialVersionUID = 2948962251251528941L;
+
+ // N.B. The modulus can be > 10 provided that the implementing class overrides toCheckDigit and toInt
+ // (for example as in ISBN10CheckDigit)
+ 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
+ */
+ @Override
+ 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 which does not yet have one.
+ *
+ * @param code The code for which to calculate the Check Digit;
+ * the check digit should not be included
+ * @return The calculated Check Digit
+ * @throws CheckDigitException if an error occurs calculating the check digit
+ */
+ @Override
+ 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 (for identifiying the position in the string)
+ * @param rightPos The position of the character in the code, counting from right to left (not used here)
+ * @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);
+ }
+ throw new CheckDigitException("Invalid Character[" +
+ leftPos + "] = '" + character + "'");
+ }
+
+ /**
+ * Convert an integer value to a check digit.
+ *
+ * Note: this implementation only handles single-digit 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) { // CHECKSTYLE IGNORE MagicNumber
+ return Integer.toString(charValue);
+ }
+ 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; // CHECKSTYLE IGNORE MagicNumber
+ todo = todo / 10; // CHECKSTYLE IGNORE MagicNumber
+ }
+ return total;
+ }
+
+}
Index: 3rdParty_sources/commons-validator/org/apache/commons/validator/routines/checkdigit/ModulusTenCheckDigit.java
===================================================================
diff -u
--- 3rdParty_sources/commons-validator/org/apache/commons/validator/routines/checkdigit/ModulusTenCheckDigit.java (revision 0)
+++ 3rdParty_sources/commons-validator/org/apache/commons/validator/routines/checkdigit/ModulusTenCheckDigit.java (revision 08255e7eeeaeba69421502fb648a1b6e98e92610)
@@ -0,0 +1,243 @@
+/*
+ * 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.Arrays;
+
+import org.apache.commons.validator.routines.CodeValidator;
+
+/**
+ * General Modulus 10 Check Digit calculation/validation.
+ *
+ *
How if Works
+ *
+ * This implementation calculates/validates the check digit in the following
+ * way:
+ *
+ * - Converting each character to an integer value using
+ *
Character.getNumericValue(char)
- negative integer values from
+ * that method are invalid.
+ * - Calculating a weighted value by multiplying the character's
+ * integer value by a weighting factor. The weighting factor is
+ * selected from the configured
postitionWeight
array based on its
+ * position. The postitionWeight
values are used either
+ * left-to-right (when useRightPos=false
) or right-to-left (when
+ * useRightPos=true
).
+ * - If
sumWeightedDigits=true
, the weighted value is
+ * re-calculated by summing its digits.
+ * - The weighted values of each character are totalled.
+ * - The total modulo 10 will be zero for a code with a valid Check Digit.
+ *
+ * Limitations
+ *
+ * This implementation has the following limitations:
+ *
+ * - It assumes the last character in the code is the Check Digit and
+ * validates that it is a numeric character.
+ * - The only limitation on valid characters are those that
+ *
Character.getNumericValue(char)
returns a positive value. If,
+ * for example, the code should only contain numbers, this implementation does
+ * not check that.
+ * - There are no checks on code length.
+ *
+ *
+ * Note: This implementation can be combined with the
+ * {@link CodeValidator} in order to ensure the length and characters are valid.
+ *
+ *
Example Usage
+ *
+ * This implementation was added after a number of Modulus 10 routines and these
+ * are shown re-implemented using this routine below:
+ *
+ *
+ * ABA Number Check Digit Routine (equivalent of
+ * {@link ABANumberCheckDigit}). Weighting factors are [1, 7, 3]
+ * applied from right to left.
+ *
+ *
+ * CheckDigit routine = new ModulusTenCheckDigit(new int[] { 1, 7, 3 }, true);
+ *
+ *
+ *
+ * CUSIP Check Digit Routine (equivalent of {@link CUSIPCheckDigit}).
+ * Weighting factors are [1, 2]
applied from right to left and the
+ * digits of the weighted value are summed.
+ *
+ *
+ * CheckDigit routine = new ModulusTenCheckDigit(new int[] { 1, 2 }, true, true);
+ *
+ *
+ *
+ * EAN-13 / UPC Check Digit Routine (equivalent of
+ * {@link EAN13CheckDigit}). Weighting factors are [1, 3]
applied
+ * from right to left.
+ *
+ *
+ * CheckDigit routine = new ModulusTenCheckDigit(new int[] { 1, 3 }, true);
+ *
+ *
+ *
+ * Luhn Check Digit Routine (equivalent of {@link LuhnCheckDigit}).
+ * Weighting factors are [1, 2]
applied from right to left and the
+ * digits of the weighted value are summed.
+ *
+ *
+ * CheckDigit routine = new ModulusTenCheckDigit(new int[] { 1, 2 }, true, true);
+ *
+ *
+ *
+ * SEDOL Check Digit Routine (equivalent of {@link SedolCheckDigit}).
+ * Weighting factors are [1, 3, 1, 7, 3, 9, 1]
applied from left to
+ * right.
+ *
+ *
+ * CheckDigit routine = new ModulusTenCheckDigit(new int[] { 1, 3, 1, 7, 3, 9, 1 });
+ *
+ *
+ * @since Validator 1.6
+ * @version $Revision: 1739356 $
+ */
+public final class ModulusTenCheckDigit extends ModulusCheckDigit {
+
+ private static final long serialVersionUID = -3752929983453368497L;
+
+ private final int[] postitionWeight;
+ private final boolean useRightPos;
+ private final boolean sumWeightedDigits;
+
+ /**
+ * Construct a modulus 10 Check Digit routine with the specified weighting
+ * from left to right.
+ *
+ * @param postitionWeight the weighted values to apply based on the
+ * character position
+ */
+ public ModulusTenCheckDigit(int[] postitionWeight) {
+ this(postitionWeight, false, false);
+ }
+
+ /**
+ * Construct a modulus 10 Check Digit routine with the specified weighting,
+ * indicating whether its from the left or right.
+ *
+ * @param postitionWeight the weighted values to apply based on the
+ * character position
+ * @param useRightPos true
if use positionWeights from right to
+ * left
+ */
+ public ModulusTenCheckDigit(int[] postitionWeight, boolean useRightPos) {
+ this(postitionWeight, useRightPos, false);
+ }
+
+ /**
+ * Construct a modulus 10 Check Digit routine with the specified weighting,
+ * indicating whether its from the left or right and whether the weighted
+ * digits should be summed.
+ *
+ * @param postitionWeight the weighted values to apply based on the
+ * character position
+ * @param useRightPos true
if use positionWeights from right to
+ * left
+ * @param sumWeightedDigits true
if sum the digits of the
+ * weighted value
+ */
+ public ModulusTenCheckDigit(int[] postitionWeight, boolean useRightPos, boolean sumWeightedDigits) {
+ super(10); // CHECKSTYLE IGNORE MagicNumber
+ this.postitionWeight = Arrays.copyOf(postitionWeight, postitionWeight.length);
+ this.useRightPos = useRightPos;
+ this.sumWeightedDigits = sumWeightedDigits;
+ }
+
+ /**
+ * Validate a modulus check digit for a code.
+ *
+ * Note: assumes last digit is the check digit
+ *
+ * @param code The code to validate
+ * @return true
if the check digit is valid, otherwise
+ * false
+ */
+ @Override
+ public boolean isValid(String code) {
+ if (code == null || code.length() == 0) {
+ return false;
+ }
+ if (!Character.isDigit(code.charAt(code.length() - 1))) {
+ return false;
+ }
+
+ return super.isValid(code);
+ }
+
+ /**
+ * Convert a character at a specified position to an integer value.
+ *
+ * Note: this implementation only handlers values that
+ * Character.getNumericValue(char) returns a non-negative number.
+ *
+ * @param character The character to convert
+ * @param leftPos The position of the character in the code, counting from
+ * left to right (for identifying the position in the string)
+ * @param rightPos The position of the character in the code, counting from
+ * right to left (not used here)
+ * @return The integer value of the character
+ * @throws CheckDigitException if Character.getNumericValue(char) returns a
+ * negative number
+ */
+ @Override
+ protected int toInt(char character, int leftPos, int rightPos) throws CheckDigitException {
+ int num = Character.getNumericValue(character);
+ if (num < 0) {
+ throw new CheckDigitException("Invalid Character[" + leftPos + "] = '" + character + "'");
+ }
+ return num;
+ }
+
+ /**
+ * Calculates the weighted value of a character 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 position of the character in the code, counting from
+ * right to left
+ * @return The weighted value of the character.
+ */
+ @Override
+ protected int weightedValue(int charValue, int leftPos, int rightPos) {
+ int pos = useRightPos ? rightPos : leftPos;
+ int weight = postitionWeight[(pos - 1) % postitionWeight.length];
+ int weightedValue = charValue * weight;
+ if (sumWeightedDigits) {
+ weightedValue = ModulusCheckDigit.sumDigits(weightedValue);
+ }
+ return weightedValue;
+ }
+
+ /**
+ * Return a string representation of this implementation.
+ *
+ * @return a string representation
+ */
+ @Override
+ public String toString() {
+ return getClass().getSimpleName() + "[postitionWeight=" + Arrays.toString(postitionWeight) + ", useRightPos="
+ + useRightPos + ", sumWeightedDigits=" + sumWeightedDigits + "]";
+ }
+
+}
Index: 3rdParty_sources/commons-validator/org/apache/commons/validator/routines/checkdigit/SedolCheckDigit.java
===================================================================
diff -u
--- 3rdParty_sources/commons-validator/org/apache/commons/validator/routines/checkdigit/SedolCheckDigit.java (revision 0)
+++ 3rdParty_sources/commons-validator/org/apache/commons/validator/routines/checkdigit/SedolCheckDigit.java (revision 08255e7eeeaeba69421502fb648a1b6e98e92610)
@@ -0,0 +1,114 @@
+/*
+ * 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: 1739356 $
+ * @since Validator 1.4
+ */
+public final class SedolCheckDigit extends ModulusCheckDigit {
+
+ private static final long serialVersionUID = -8976881621148878443L;
+
+ private static final int MAX_ALPHANUMERIC_VALUE = 35; // Character.getNumericValue('Z')
+
+ /** 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); // CHECKSTYLE IGNORE MagicNumber
+ }
+
+ /**
+ * 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
+ */
+ @Override
+ protected int calculateModulus(String code, boolean includesCheckDigit) throws CheckDigitException {
+ if (code.length() > POSITION_WEIGHT.length) {
+ 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.
+ */
+ @Override
+ 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
+ */
+ @Override
+ protected int toInt(char character, int leftPos, int rightPos)
+ throws CheckDigitException {
+ int charValue = Character.getNumericValue(character);
+ // the check digit is only allowed to reach 9
+ final int charMax = rightPos == 1 ? 9 : MAX_ALPHANUMERIC_VALUE; // CHECKSTYLE IGNORE MagicNumber
+ if (charValue < 0 || charValue > charMax) {
+ throw new CheckDigitException("Invalid Character[" +
+ leftPos + "," + rightPos + "] = '" + charValue + "' out of range 0 to " + charMax);
+ }
+ return charValue;
+ }
+
+}
Index: 3rdParty_sources/commons-validator/org/apache/commons/validator/routines/checkdigit/VerhoeffCheckDigit.java
===================================================================
diff -u
--- 3rdParty_sources/commons-validator/org/apache/commons/validator/routines/checkdigit/VerhoeffCheckDigit.java (revision 0)
+++ 3rdParty_sources/commons-validator/org/apache/commons/validator/routines/checkdigit/VerhoeffCheckDigit.java (revision 08255e7eeeaeba69421502fb648a1b6e98e92610)
@@ -0,0 +1,129 @@
+/*
+ * 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: 1739357 $
+ * @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
+ */
+ @Override
+ 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
+ */
+ @Override
+ 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) { // CHECKSTYLE IGNORE MagicNumber
+ 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]]; // CHECKSTYLE IGNORE MagicNumber
+ }
+ return checksum;
+ }
+
+}
Index: 3rdParty_sources/commons-validator/org/apache/commons/validator/routines/checkdigit/package.html
===================================================================
diff -u
--- 3rdParty_sources/commons-validator/org/apache/commons/validator/routines/checkdigit/package.html (revision 0)
+++ 3rdParty_sources/commons-validator/org/apache/commons/validator/routines/checkdigit/package.html (revision 08255e7eeeaeba69421502fb648a1b6e98e92610)
@@ -0,0 +1,26 @@
+
+
+
+Package Documentation for org.apache.commons.validator.routines.checkdigit Package
+
+
+
+ This package contains Check Digit validation/calculation routines.
+
+
+
Index: 3rdParty_sources/commons-validator/org/apache/commons/validator/routines/package.html
===================================================================
diff -u
--- 3rdParty_sources/commons-validator/org/apache/commons/validator/routines/package.html (revision 0)
+++ 3rdParty_sources/commons-validator/org/apache/commons/validator/routines/package.html (revision 08255e7eeeaeba69421502fb648a1b6e98e92610)
@@ -0,0 +1,827 @@
+
+
+
+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, independent 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, independent
+ 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
.
+
+
+ - Date Validator - validates dates
+ converting to a
java.util.Date
type.
+ - Calendar Validator - validates dates
+ converting to a
java.util.Calendar
type.
+ - Time Validator - validates times
+ converting to a
java.util.Calendar
type.
+
+
+
+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 following 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
+ }
+
+
+
Index: 3rdParty_sources/commons-validator/org/apache/commons/validator/util/Flags.java
===================================================================
diff -u
--- 3rdParty_sources/commons-validator/org/apache/commons/validator/util/Flags.java (revision 0)
+++ 3rdParty_sources/commons-validator/org/apache/commons/validator/util/Flags.java (revision 08255e7eeeaeba69421502fb648a1b6e98e92610)
@@ -0,0 +1,206 @@
+/*
+ * 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: 1739356 $
+ */
+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) == flag;
+ }
+
+ /**
+ * 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 = 0xFFFFFFFFFFFFFFFFl;
+ }
+
+ /**
+ * Clone this Flags object.
+ *
+ * @return a copy of this object.
+ * @see java.lang.Object#clone()
+ */
+ @Override
+ 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.
+ */
+ @Override
+ 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.
+ */
+ @Override
+ 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.
+ */
+ @Override
+ public String toString() {
+ StringBuilder bin = new StringBuilder(Long.toBinaryString(this.flags));
+ for (int i = 64 - bin.length(); i > 0; i--) { // CHECKSTYLE IGNORE MagicNumber
+ bin.insert(0, "0");
+ }
+ return bin.toString();
+ }
+
+}
Index: 3rdParty_sources/commons-validator/org/apache/commons/validator/util/ValidatorUtils.java
===================================================================
diff -u
--- 3rdParty_sources/commons-validator/org/apache/commons/validator/util/ValidatorUtils.java (revision 0)
+++ 3rdParty_sources/commons-validator/org/apache/commons/validator/util/ValidatorUtils.java (revision 08255e7eeeaeba69421502fb648a1b6e98e92610)
@@ -0,0 +1,200 @@
+/*
+ * 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; // DEPRECATED
+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: 1739361 $
+ */
+public class ValidatorUtils {
+
+ private static final Log LOG = LogFactory.getLog(ValidatorUtils.class);
+
+ /**
+ * 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.error(e.getMessage(), e);
+ } catch(InvocationTargetException e) {
+ LOG.error(e.getMessage(), e);
+ } catch(NoSuchMethodException e) {
+ 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.
+ */
+ @Deprecated
+ public static FastHashMap copyFastHashMap(FastHashMap map) {
+ FastHashMap results = new FastHashMap();
+
+ @SuppressWarnings("unchecked") // FastHashMap is not generic
+ Iterator> i = map.entrySet().iterator();
+ while (i.hasNext()) {
+ Entry entry = i.next();
+ String key = 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 = i.next();
+ String key = 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;
+ }
+
+}
Index: 3rdParty_sources/commons-validator/org/apache/commons/validator/util/package.html
===================================================================
diff -u
--- 3rdParty_sources/commons-validator/org/apache/commons/validator/util/package.html (revision 0)
+++ 3rdParty_sources/commons-validator/org/apache/commons/validator/util/package.html (revision 08255e7eeeaeba69421502fb648a1b6e98e92610)
@@ -0,0 +1,26 @@
+
+
+
+Package Documentation for org.apache.commons.validator.util Package
+
+
+
+This package contains utility classes used by Commons Validator.
+
+
+