ModulusCheckDigit.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.apache.commons.validator.routines.checkdigit;

  18. import java.io.Serializable;

  19. import org.apache.commons.validator.GenericValidator;

  20. /**
  21.  * Abstract <b>Modulus</b> Check digit calculation/validation.
  22.  * <p>
  23.  * Provides a <i>base</i> class for building <i>modulus</i> Check Digit routines.
  24.  * </p>
  25.  * <p>
  26.  * This implementation only handles <i>single-digit numeric</i> codes, such as <b>EAN-13</b>. For <i>alphanumeric</i> codes such as <b>EAN-128</b> you will need
  27.  * to implement/override the <code>toInt()</code> and <code>toChar()</code> methods.
  28.  * </p>
  29.  *
  30.  * @since 1.4
  31.  */
  32. public abstract class ModulusCheckDigit extends AbstractCheckDigit implements Serializable {

  33.     static final int MODULUS_10 = 10;
  34.     static final int MODULUS_11 = 11;
  35.     private static final long serialVersionUID = 2948962251251528941L;

  36.     /**
  37.      * Add together the individual digits in a number.
  38.      *
  39.      * @param number The number whose digits are to be added
  40.      * @return The sum of the digits
  41.      */
  42.     public static int sumDigits(final int number) {
  43.         int total = 0;
  44.         int todo = number;
  45.         while (todo > 0) {
  46.             total += todo % 10; // CHECKSTYLE IGNORE MagicNumber
  47.             todo /= 10; // CHECKSTYLE IGNORE MagicNumber
  48.         }
  49.         return total;
  50.     }

  51.     /**
  52.      * The modulus can be greater than 10 provided that the implementing class overrides toCheckDigit and toInt (for example as in ISBN10CheckDigit).
  53.      */
  54.     private final int modulus;

  55.     /**
  56.      * Constructs a modulus 10 {@link CheckDigit} routine for a specified modulus.
  57.      */
  58.     ModulusCheckDigit() {
  59.         this(MODULUS_10);
  60.     }

  61.     /**
  62.      * Constructs a {@link CheckDigit} routine for a specified modulus.
  63.      *
  64.      * @param modulus The modulus value to use for the check digit calculation
  65.      */
  66.     public ModulusCheckDigit(final int modulus) {
  67.         this.modulus = modulus;
  68.     }

  69.     /**
  70.      * Calculate a modulus <i>Check Digit</i> for a code which does not yet have one.
  71.      *
  72.      * @param code The code for which to calculate the Check Digit;
  73.      * the check digit should not be included
  74.      * @return The calculated Check Digit
  75.      * @throws CheckDigitException if an error occurs calculating the check digit
  76.      */
  77.     @Override
  78.     public String calculate(final String code) throws CheckDigitException {
  79.         if (GenericValidator.isBlankOrNull(code)) {
  80.             throw new CheckDigitException("Code is missing");
  81.         }
  82.         final int modulusResult = calculateModulus(code, false);
  83.         final int charValue = (modulus - modulusResult) % modulus;
  84.         return toCheckDigit(charValue);
  85.     }

  86.     /**
  87.      * Calculate the modulus for a code.
  88.      *
  89.      * @param code The code to calculate the modulus for.
  90.      * @param includesCheckDigit Whether the code includes the Check Digit or not.
  91.      * @return The modulus value
  92.      * @throws CheckDigitException if an error occurs calculating the modulus
  93.      * for the specified code
  94.      */
  95.     protected int calculateModulus(final String code, final boolean includesCheckDigit) throws CheckDigitException {
  96.         int total = 0;
  97.         for (int i = 0; i < code.length(); i++) {
  98.             final int lth = code.length() + (includesCheckDigit ? 0 : 1);
  99.             final int leftPos = i + 1;
  100.             final int rightPos = lth - i;
  101.             final int charValue = toInt(code.charAt(i), leftPos, rightPos);
  102.             total += weightedValue(charValue, leftPos, rightPos);
  103.         }
  104.         if (total == 0) {
  105.             throw new CheckDigitException("Invalid code, sum is zero");
  106.         }
  107.         return total % modulus;
  108.     }

  109.     /**
  110.      * Gets the modulus value this check digit routine is based on.
  111.      *
  112.      * @return The modulus value this check digit routine is based on
  113.      */
  114.     public int getModulus() {
  115.         return modulus;
  116.     }

  117.     /**
  118.      * Validate a modulus check digit for a code.
  119.      *
  120.      * @param code The code to validate
  121.      * @return {@code true} if the check digit is valid, otherwise
  122.      * {@code false}
  123.      */
  124.     @Override
  125.     public boolean isValid(final String code) {
  126.         if (GenericValidator.isBlankOrNull(code)) {
  127.             return false;
  128.         }
  129.         try {
  130.             final int modulusResult = calculateModulus(code, true);
  131.             return modulusResult == 0;
  132.         } catch (final CheckDigitException ex) {
  133.             return false;
  134.         }
  135.     }

  136.     /**
  137.      * Convert an integer value to a check digit.
  138.      * <p>
  139.      * <b>Note:</b> this implementation only handles single-digit numeric values
  140.      * For non-numeric characters, override this method to provide
  141.      * integer--&gt;character conversion.
  142.      *
  143.      * @param charValue The integer value of the character
  144.      * @return The converted character
  145.      * @throws CheckDigitException if integer character value
  146.      * doesn't represent a numeric character
  147.      */
  148.     protected String toCheckDigit(final int charValue) throws CheckDigitException {
  149.         if (charValue >= 0 && charValue <= 9) { // CHECKSTYLE IGNORE MagicNumber
  150.             return Integer.toString(charValue);
  151.         }
  152.         throw new CheckDigitException("Invalid Check Digit Value =" + +charValue);
  153.     }

  154.     /**
  155.      * Convert a character at a specified position to an integer value.
  156.      * <p>
  157.      * <b>Note:</b> this implementation only handlers numeric values
  158.      * For non-numeric characters, override this method to provide
  159.      * character--&gt;integer conversion.
  160.      *
  161.      * @param character The character to convert
  162.      * @param leftPos The position of the character in the code, counting from left to right (for identifiying the position in the string)
  163.      * @param rightPos The position of the character in the code, counting from right to left (not used here)
  164.      * @return The integer value of the character
  165.      * @throws CheckDigitException if character is non-numeric
  166.      */
  167.     protected int toInt(final char character, final int leftPos, final int rightPos) throws CheckDigitException {
  168.         if (Character.isDigit(character)) {
  169.             return Character.getNumericValue(character);
  170.         }
  171.         throw new CheckDigitException("Invalid Character[" + leftPos + "] = '" + character + "'");
  172.     }

  173.     /**
  174.      * Calculates the <i>weighted</i> value of a character in the
  175.      * code at a specified position.
  176.      * <p>
  177.      * Some modulus routines weight the value of a character
  178.      * depending on its position in the code (e.g. ISBN-10), while
  179.      * others use different weighting factors for odd/even positions
  180.      * (e.g. EAN or Luhn). Implement the appropriate mechanism
  181.      * required by overriding this method.
  182.      *
  183.      * @param charValue The numeric value of the character
  184.      * @param leftPos The position of the character in the code, counting from left to right
  185.      * @param rightPos The positionof the character in the code, counting from right to left
  186.      * @return The weighted value of the character
  187.      * @throws CheckDigitException if an error occurs calculating
  188.      * the weighted value
  189.      */
  190.     protected abstract int weightedValue(int charValue, int leftPos, int rightPos) throws CheckDigitException;

  191. }