001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      https://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.commons.validator.routines.checkdigit;
018
019import java.util.Arrays;
020
021import org.apache.commons.validator.GenericValidator;
022import org.apache.commons.validator.routines.CodeValidator;
023
024/**
025 * General Modulus 10 Check Digit calculation/validation.
026 *
027 * <h2>How it Works</h2>
028 * <p>
029 * This implementation calculates/validates the check digit in the following
030 * way:
031 * </p>
032 * <ul>
033 * <li>Converting each character to an integer value using
034 * {@code Character.getNumericValue(char)} - negative integer values from
035 * that method are invalid.</li>
036 * <li>Calculating a <em>weighted value</em> by multiplying the character's
037 * integer value by a <em>weighting factor</em>. The <em>weighting factor</em> is
038 * selected from the configured {@code positionWeight} array based on its
039 * position. The {@code postitionWeight} values are used either
040 * left-to-right (when {@code useRightPos=false}) or right-to-left (when
041 * {@code useRightPos=true}).</li>
042 * <li>If {@code sumWeightedDigits=true}, the <em>weighted value</em> is
043 * re-calculated by summing its digits.</li>
044 * <li>The <em>weighted values</em> of each character are totalled.</li>
045 * <li>The total modulo 10 will be zero for a code with a valid Check Digit.</li>
046 * </ul>
047 * <h2>Limitations</h2>
048 * <p>
049 * This implementation has the following limitations:
050 * </p>
051 * <ul>
052 * <li>It assumes the last character in the code is the Check Digit and
053 * validates that it is a numeric character.</li>
054 * <li>The only limitation on valid characters are those that
055 * {@code Character.getNumericValue(char)} returns a positive value. If,
056 * for example, the code should only contain numbers, this implementation does
057 * not check that.</li>
058 * <li>There are no checks on code length.</li>
059 * </ul>
060 * <p>
061 * <strong>Note:</strong> This implementation can be combined with the
062 * {@link CodeValidator} in order to ensure the length and characters are valid.
063 * </p>
064 *
065 * <h2>Example Usage</h2>
066 * <p>
067 * This implementation was added after a number of Modulus 10 routines and these
068 * are shown re-implemented using this routine below:
069 * </p>
070 *
071 * <p>
072 * <strong>ABA Number</strong> Check Digit Routine (equivalent of
073 * {@link ABANumberCheckDigit}). Weighting factors are {@code [1, 7, 3]}
074 * applied from right to left.
075 * </p>
076 *
077 * <pre>
078 * CheckDigit routine = new ModulusTenCheckDigit(new int[] { 1, 7, 3 }, true);
079 * </pre>
080 *
081 * <p>
082 * <strong>CUSIP</strong> Check Digit Routine (equivalent of {@link CUSIPCheckDigit}).
083 * Weighting factors are {@code [1, 2]} applied from right to left and the
084 * digits of the <em>weighted value</em> are summed.
085 * </p>
086 *
087 * <pre>
088 * CheckDigit routine = new ModulusTenCheckDigit(new int[] { 1, 2 }, true, true);
089 * </pre>
090 *
091 * <p>
092 * <strong>EAN-13 / UPC</strong> Check Digit Routine (equivalent of
093 * {@link EAN13CheckDigit}). Weighting factors are {@code [1, 3]} applied
094 * from right to left.
095 * </p>
096 *
097 * <pre>
098 * CheckDigit routine = new ModulusTenCheckDigit(new int[] { 1, 3 }, true);
099 * </pre>
100 *
101 * <p>
102 * <strong>Luhn</strong> Check Digit Routine (equivalent of {@link LuhnCheckDigit}).
103 * Weighting factors are {@code [1, 2]} applied from right to left and the
104 * digits of the <em>weighted value</em> are summed.
105 * </p>
106 *
107 * <pre>
108 * CheckDigit routine = new ModulusTenCheckDigit(new int[] { 1, 2 }, true, true);
109 * </pre>
110 *
111 * <p>
112 * <strong>SEDOL</strong> Check Digit Routine (equivalent of {@link SedolCheckDigit}).
113 * Weighting factors are {@code [1, 3, 1, 7, 3, 9, 1]} applied from left to
114 * right.
115 * </p>
116 *
117 * <pre>
118 * CheckDigit routine = new ModulusTenCheckDigit(new int[] { 1, 3, 1, 7, 3, 9, 1 });
119 * </pre>
120 *
121 * @since 1.6
122 */
123public final class ModulusTenCheckDigit extends ModulusCheckDigit {
124
125    private static final long serialVersionUID = -3752929983453368497L;
126
127    /**
128     * The weighted values to apply based on the character position
129     */
130    private final int[] positionWeight;
131
132    /**
133     * {@code true} if use positionWeights from right to left
134     */
135    private final boolean useRightPos;
136
137    /**
138     * {@code true} if sum the digits of the weighted value
139     */
140    private final boolean sumWeightedDigits;
141
142    /**
143     * Constructs a modulus 10 Check Digit routine with the specified weighting from left to right.
144     *
145     * @param positionWeight The weighted values to apply based on the character position
146     */
147    public ModulusTenCheckDigit(final int[] positionWeight) {
148        this(positionWeight, false, false);
149    }
150
151    /**
152     * Constructs a modulus 10 Check Digit routine with the specified weighting, indicating whether its from the left or right.
153     *
154     * @param positionWeight The weighted values to apply based on the character position
155     * @param useRightPos    {@code true} if use positionWeights from right to left
156     */
157    public ModulusTenCheckDigit(final int[] positionWeight, final boolean useRightPos) {
158        this(positionWeight, useRightPos, false);
159    }
160
161    /**
162     * Constructs a modulus 10 Check Digit routine with the specified weighting, indicating whether its from the left or right and whether the weighted digits
163     * should be summed.
164     *
165     * @param positionWeight    The weighted values to apply based on the character position
166     * @param useRightPos       {@code true} if use positionWeights from right to left
167     * @param sumWeightedDigits {@code true} if sum the digits of the weighted value
168     */
169    public ModulusTenCheckDigit(final int[] positionWeight, final boolean useRightPos, final boolean sumWeightedDigits) {
170        this.positionWeight = Arrays.copyOf(positionWeight, positionWeight.length);
171        this.useRightPos = useRightPos;
172        this.sumWeightedDigits = sumWeightedDigits;
173    }
174
175    /**
176     * Validate a modulus check digit for a code.
177     * <p>
178     * Note: assumes last digit is the check digit.
179     * </p>
180     *
181     * @param code The code to validate.
182     * @return {@code true} if the check digit is valid, otherwise {@code false}.
183     */
184    @Override
185    public boolean isValid(final String code) {
186        if (GenericValidator.isBlankOrNull(code) || !isAsciiDigit(code.charAt(code.length() - 1))) {
187            return false;
188        }
189        return super.isValid(code);
190    }
191
192    /**
193     * Convert a character at a specified position to an integer value.
194     * <p>
195     * <strong>Note:</strong> this implementation only handlers values that Character.getNumericValue(char) returns a non-negative number.
196     * </p>
197     *
198     * @param character The character to convert.
199     * @param leftPos   The position of the character in the code, counting from left to right (for identifying the position in the string).
200     * @param rightPos  The position of the character in the code, counting from right to left (not used here).
201     * @return The integer value of the character.
202     * @throws CheckDigitException if Character.getNumericValue(char) returns a negative number.
203     */
204    @Override
205    protected int toInt(final char character, final int leftPos, final int rightPos) throws CheckDigitException {
206        if (!isAsciiAlphaNum(character)) {
207            throw new CheckDigitException("Invalid Character[%d,%d] = '%c'", leftPos, rightPos, character);
208        }
209        return Character.getNumericValue(character);
210    }
211
212    /**
213     * Return a string representation of this implementation.
214     *
215     * @return A string representation.
216     */
217    @Override
218    public String toString() {
219        return getClass().getSimpleName() + "[positionWeight=" + Arrays.toString(positionWeight) + ", useRightPos=" + useRightPos + ", sumWeightedDigits="
220                + sumWeightedDigits + "]";
221    }
222
223    /**
224     * Calculates the <em>weighted</em> value of a character in the code at a specified position.
225     *
226     * @param charValue The numeric value of the character.
227     * @param leftPos   The position of the character in the code, counting from left to right.
228     * @param rightPos  The position of the character in the code, counting from right to left.
229     * @return The weighted value of the character.
230     */
231    @Override
232    protected int weightedValue(final int charValue, final int leftPos, final int rightPos) {
233        final int pos = useRightPos ? rightPos : leftPos;
234        final int weight = positionWeight[(pos - 1) % positionWeight.length];
235        int weightedValue = charValue * weight;
236        if (sumWeightedDigits) {
237            weightedValue = sumDigits(weightedValue);
238        }
239        return weightedValue;
240    }
241}