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>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: 1227719 $ $Date: 2012-01-05 12:45:51 -0500 (Thu, 05 Jan 2012) $
34 * @since Validator 1.4
35 */
36 public abstract class ModulusCheckDigit implements CheckDigit, Serializable {
37
38 private static final long serialVersionUID = 2948962251251528941L;
39
40 private final int modulus;
41
42 /**
43 * Construct a {@link CheckDigit} routine for a specified modulus.
44 *
45 * @param modulus The modulus value to use for the check digit calculation
46 */
47 public ModulusCheckDigit(int modulus) {
48 this.modulus = modulus;
49 }
50
51 /**
52 * Return the modulus value this check digit routine is based on.
53 *
54 * @return The modulus value this check digit routine is based on
55 */
56 public int getModulus() {
57 return modulus;
58 }
59
60 /**
61 * Validate a modulus check digit for a code.
62 *
63 * @param code The code to validate
64 * @return <code>true</code> if the check digit is valid, otherwise
65 * <code>false</code>
66 */
67 public boolean isValid(String code) {
68 if (code == null || code.length() == 0) {
69 return false;
70 }
71 try {
72 int modulusResult = calculateModulus(code, true);
73 return (modulusResult == 0);
74 } catch (CheckDigitException ex) {
75 return false;
76 }
77 }
78
79 /**
80 * Calculate a modulus <i>Check Digit</i> for a code.
81 *
82 * @param code The code to calculate the Check Digit for
83 * @return The calculated Check Digit
84 * @throws CheckDigitException if an error occurs calculating
85 * the check digit for the specified code
86 */
87 public String calculate(String code) throws CheckDigitException {
88 if (code == null || code.length() == 0) {
89 throw new CheckDigitException("Code is missing");
90 }
91 int modulusResult = calculateModulus(code, false);
92 int charValue = (modulus - modulusResult) % modulus;
93 return toCheckDigit(charValue);
94 }
95
96 /**
97 * Calculate the modulus for a code.
98 *
99 * @param code The code to calculate the modulus for.
100 * @param includesCheckDigit Whether the code includes the Check Digit or not.
101 * @return The modulus value
102 * @throws CheckDigitException if an error occurs calculating the modulus
103 * for the specified code
104 */
105 protected int calculateModulus(String code, boolean includesCheckDigit) throws CheckDigitException {
106 int total = 0;
107 for (int i = 0; i < code.length(); i++) {
108 int lth = code.length() + (includesCheckDigit ? 0 : 1);
109 int leftPos = i + 1;
110 int rightPos = lth - i;
111 int charValue = toInt(code.charAt(i), leftPos, rightPos);
112 total += weightedValue(charValue, leftPos, rightPos);
113 }
114 if (total == 0) {
115 throw new CheckDigitException("Invalid code, sum is zero");
116 }
117 return (total % modulus);
118 }
119
120 /**
121 * Calculates the <i>weighted</i> value of a character in the
122 * code at a specified position.
123 * <p>
124 * Some modulus routines weight the value of a character
125 * depending on its position in the code (e.g. ISBN-10), while
126 * others use different weighting factors for odd/even positions
127 * (e.g. EAN or Luhn). Implement the appropriate mechanism
128 * required by overriding this method.
129 *
130 * @param charValue The numeric value of the character
131 * @param leftPos The position of the character in the code, counting from left to right
132 * @param rightPos The positionof the character in the code, counting from right to left
133 * @return The weighted value of the character
134 * @throws CheckDigitException if an error occurs calculating
135 * the weighted value
136 */
137 protected abstract int weightedValue(int charValue, int leftPos, int rightPos)
138 throws CheckDigitException;
139
140
141 /**
142 * Convert a character at a specified position to an integer value.
143 * <p>
144 * <b>Note:</b> this implementation only handlers numeric values
145 * For non-numeric characters, override this method to provide
146 * character-->integer conversion.
147 *
148 * @param character The character to convert
149 * @param leftPos The position of the character in the code, counting from left to right
150 * @param rightPos The positionof the character in the code, counting from right to left
151 * @return The integer value of the character
152 * @throws CheckDigitException if character is non-numeric
153 */
154 protected int toInt(char character, int leftPos, int rightPos)
155 throws CheckDigitException {
156 if (Character.isDigit(character)) {
157 return Character.getNumericValue(character);
158 } else {
159 throw new CheckDigitException("Invalid Character[" +
160 leftPos + "] = '" + character + "'");
161 }
162 }
163
164 /**
165 * Convert an integer value to a check digit.
166 * <p>
167 * <b>Note:</b> this implementation only handles numeric values
168 * For non-numeric characters, override this method to provide
169 * integer-->character conversion.
170 *
171 * @param charValue The integer value of the character
172 * @return The converted character
173 * @throws CheckDigitException if integer character value
174 * doesn't represent a numeric character
175 */
176 protected String toCheckDigit(int charValue)
177 throws CheckDigitException {
178 if (charValue >= 0 && charValue <= 9) {
179 return Integer.toString(charValue);
180 } else {
181 throw new CheckDigitException("Invalid Check Digit Value =" +
182 + charValue);
183 }
184 }
185
186 /**
187 * Add together the individual digits in a number.
188 *
189 * @param number The number whose digits are to be added
190 * @return The sum of the digits
191 */
192 public static int sumDigits(int number) {
193 int total = 0;
194 int todo = number;
195 while (todo > 0) {
196 total += todo % 10;
197 todo = todo / 10;
198 }
199 return total;
200 }
201
202 }