001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.commons.validator.routines.checkdigit;
018
019import java.io.Serializable;
020
021/**
022 * Abstract <b>Modulus</b> Check digit calculation/validation.
023 * <p>
024 * Provides a <i>base</i> class for building <i>modulus</i> Check
025 * Digit routines.
026 * <p>
027 * This implementation only handles <i>single-digit numeric</i> codes, such as
028 * <b>EAN-13</b>. For <i>alphanumeric</i> codes such as <b>EAN-128</b> you
029 * will need to implement/override the <code>toInt()</code> and
030 * <code>toChar()</code> methods.
031 * <p>
032 *
033 * @version $Revision: 1562817 $ $Date: 2014-01-30 14:33:19 +0100 (Do, 30 Jan 2014) $
034 * @since Validator 1.4
035 */
036public abstract class ModulusCheckDigit implements CheckDigit, Serializable {
037
038    private static final long serialVersionUID = 2948962251251528941L;
039
040    // N.B. The modulus can be > 10 provided that the implementing class overrides toCheckDigit and toInt
041    // (for example as in ISBN10CheckDigit)
042    private final int modulus;
043
044    /**
045     * Construct a {@link CheckDigit} routine for a specified modulus.
046     *
047     * @param modulus The modulus value to use for the check digit calculation
048     */
049    public ModulusCheckDigit(int modulus) {
050        this.modulus = modulus;
051    }
052
053    /**
054     * Return the modulus value this check digit routine is based on.
055     *
056     * @return The modulus value this check digit routine is based on
057     */
058    public int getModulus() {
059        return modulus;
060    }
061
062    /**
063     * Validate a modulus check digit for a code.
064     *
065     * @param code The code to validate
066     * @return <code>true</code> if the check digit is valid, otherwise
067     * <code>false</code>
068     */
069    public boolean isValid(String code) {
070        if (code == null || code.length() == 0) {
071            return false;
072        }
073        try {
074            int modulusResult = calculateModulus(code, true);
075            return (modulusResult == 0);
076        } catch (CheckDigitException  ex) {
077            return false;
078        }
079    }
080
081    /**
082     * Calculate a modulus <i>Check Digit</i> for a code.
083     *
084     * @param code The code to calculate the Check Digit for
085     * @return The calculated Check Digit
086     * @throws CheckDigitException if an error occurs calculating
087     * the check digit for the specified code
088     */
089    public String calculate(String code) throws CheckDigitException {
090        if (code == null || code.length() == 0) {
091            throw new CheckDigitException("Code is missing");
092        }
093        int modulusResult = calculateModulus(code, false);
094        int charValue = (modulus - modulusResult) % modulus;
095        return toCheckDigit(charValue);
096    }
097
098    /**
099     * Calculate the modulus for a code.
100     *
101     * @param code The code to calculate the modulus for.
102     * @param includesCheckDigit Whether the code includes the Check Digit or not.
103     * @return The modulus value
104     * @throws CheckDigitException if an error occurs calculating the modulus
105     * for the specified code
106     */
107    protected int calculateModulus(String code, boolean includesCheckDigit) throws CheckDigitException {
108        int total = 0;
109        for (int i = 0; i < code.length(); i++) {
110            int lth = code.length() + (includesCheckDigit ? 0 : 1);
111            int leftPos  = i + 1;
112            int rightPos = lth - i;
113            int charValue = toInt(code.charAt(i), leftPos, rightPos);
114            total += weightedValue(charValue, leftPos, rightPos);
115        }
116        if (total == 0) {
117            throw new CheckDigitException("Invalid code, sum is zero");
118        }
119        return (total % modulus);
120    }
121
122    /**
123     * Calculates the <i>weighted</i> value of a character in the
124     * code at a specified position.
125     * <p>
126     * Some modulus routines weight the value of a character
127     * depending on its position in the code (e.g. ISBN-10), while
128     * others use different weighting factors for odd/even positions
129     * (e.g. EAN or Luhn). Implement the appropriate mechanism
130     * required by overriding this method.
131     *
132     * @param charValue The numeric value of the character
133     * @param leftPos The position of the character in the code, counting from left to right
134     * @param rightPos The positionof the character in the code, counting from right to left
135     * @return The weighted value of the character
136     * @throws CheckDigitException if an error occurs calculating
137     * the weighted value
138     */
139    protected abstract int weightedValue(int charValue, int leftPos, int rightPos)
140            throws CheckDigitException;
141
142
143    /**
144     * Convert a character at a specified position to an integer value.
145     * <p>
146     * <b>Note:</b> this implementation only handlers numeric values
147     * For non-numeric characters, override this method to provide
148     * character-->integer conversion.
149     *
150     * @param character The character to convert
151     * @param leftPos The position of the character in the code, counting from left to right (for identifiying the position in the string)
152     * @param rightPos The position of the character in the code, counting from right to left (not used here)
153     * @return The integer value of the character
154     * @throws CheckDigitException if character is non-numeric
155     */
156    protected int toInt(char character, int leftPos, int rightPos)
157            throws CheckDigitException {
158        if (Character.isDigit(character)) {
159            return Character.getNumericValue(character);
160        } else {
161            throw new CheckDigitException("Invalid Character[" +
162                    leftPos + "] = '" + character + "'");
163        }
164    }
165
166    /**
167     * Convert an integer value to a check digit.
168     * <p>
169     * <b>Note:</b> this implementation only handles single-digit numeric values
170     * For non-numeric characters, override this method to provide
171     * integer-->character conversion.
172     *
173     * @param charValue The integer value of the character
174     * @return The converted character
175     * @throws CheckDigitException if integer character value
176     * doesn't represent a numeric character
177     */
178    protected String toCheckDigit(int charValue)
179            throws CheckDigitException {
180        if (charValue >= 0 && charValue <= 9) {
181            return Integer.toString(charValue);
182        } else {
183            throw new CheckDigitException("Invalid Check Digit Value =" +
184                    + charValue);
185        }
186    }
187
188    /**
189     * Add together the individual digits in a number.
190     *
191     * @param number The number whose digits are to be added
192     * @return The sum of the digits
193     */
194    public static int sumDigits(int number) {
195        int total = 0;
196        int todo = number;
197        while (todo > 0) {
198            total += todo % 10;
199            todo  = todo / 10;
200        }
201        return total;
202    }
203
204}