View Javadoc
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  
19  import java.io.Serializable;
20  
21  /**
22   * Abstract <b>Modulus</b> Check digit calculation/validation.
23   * <p>
24   * Provides a <i>base</i> class for building <i>modulus</i> Check
25   * Digit routines.
26   * <p>
27   * This implementation only handles <i>single-digit numeric</i> codes, such as
28   * <b>EAN-13</b>. For <i>alphanumeric</i> codes such as <b>EAN-128</b> you
29   * will need to implement/override the <code>toInt()</code> and
30   * <code>toChar()</code> methods.
31   * <p>
32   *
33   * @version $Revision: 1562817 $ $Date: 2014-01-30 14:33:19 +0100 (Do, 30 Jan 2014) $
34   * @since Validator 1.4
35   */
36  public abstract class ModulusCheckDigit implements CheckDigit, Serializable {
37  
38      private static final long serialVersionUID = 2948962251251528941L;
39  
40      // N.B. The modulus can be > 10 provided that the implementing class overrides toCheckDigit and toInt
41      // (for example as in ISBN10CheckDigit)
42      private final int modulus;
43  
44      /**
45       * Construct a {@link CheckDigit} routine for a specified modulus.
46       *
47       * @param modulus The modulus value to use for the check digit calculation
48       */
49      public ModulusCheckDigit(int modulus) {
50          this.modulus = modulus;
51      }
52  
53      /**
54       * Return the modulus value this check digit routine is based on.
55       *
56       * @return The modulus value this check digit routine is based on
57       */
58      public int getModulus() {
59          return modulus;
60      }
61  
62      /**
63       * Validate a modulus check digit for a code.
64       *
65       * @param code The code to validate
66       * @return <code>true</code> if the check digit is valid, otherwise
67       * <code>false</code>
68       */
69      public boolean isValid(String code) {
70          if (code == null || code.length() == 0) {
71              return false;
72          }
73          try {
74              int modulusResult = calculateModulus(code, true);
75              return (modulusResult == 0);
76          } catch (CheckDigitException  ex) {
77              return false;
78          }
79      }
80  
81      /**
82       * Calculate a modulus <i>Check Digit</i> for a code.
83       *
84       * @param code The code to calculate the Check Digit for
85       * @return The calculated Check Digit
86       * @throws CheckDigitException if an error occurs calculating
87       * the check digit for the specified code
88       */
89      public String calculate(String code) throws CheckDigitException {
90          if (code == null || code.length() == 0) {
91              throw new CheckDigitException("Code is missing");
92          }
93          int modulusResult = calculateModulus(code, false);
94          int charValue = (modulus - modulusResult) % modulus;
95          return toCheckDigit(charValue);
96      }
97  
98      /**
99       * 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 }