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 021import org.apache.commons.validator.GenericValidator; 022 023/** 024 * Abstract <b>Modulus</b> Check digit calculation/validation. 025 * <p> 026 * Provides a <i>base</i> class for building <i>modulus</i> Check Digit routines. 027 * </p> 028 * <p> 029 * 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 030 * to implement/override the <code>toInt()</code> and <code>toChar()</code> methods. 031 * </p> 032 * 033 * @since 1.4 034 */ 035public abstract class ModulusCheckDigit extends AbstractCheckDigit implements Serializable { 036 037 static final int MODULUS_10 = 10; 038 static final int MODULUS_11 = 11; 039 private static final long serialVersionUID = 2948962251251528941L; 040 041 /** 042 * Add together the individual digits in a number. 043 * 044 * @param number The number whose digits are to be added 045 * @return The sum of the digits 046 */ 047 public static int sumDigits(final int number) { 048 int total = 0; 049 int todo = number; 050 while (todo > 0) { 051 total += todo % 10; // CHECKSTYLE IGNORE MagicNumber 052 todo /= 10; // CHECKSTYLE IGNORE MagicNumber 053 } 054 return total; 055 } 056 057 /** 058 * The modulus can be greater than 10 provided that the implementing class overrides toCheckDigit and toInt (for example as in ISBN10CheckDigit). 059 */ 060 private final int modulus; 061 062 /** 063 * Constructs a modulus 10 {@link CheckDigit} routine for a specified modulus. 064 */ 065 ModulusCheckDigit() { 066 this(MODULUS_10); 067 } 068 069 /** 070 * Constructs a {@link CheckDigit} routine for a specified modulus. 071 * 072 * @param modulus The modulus value to use for the check digit calculation 073 */ 074 public ModulusCheckDigit(final int modulus) { 075 this.modulus = modulus; 076 } 077 078 /** 079 * Calculate a modulus <i>Check Digit</i> for a code which does not yet have one. 080 * 081 * @param code The code for which to calculate the Check Digit; 082 * the check digit should not be included 083 * @return The calculated Check Digit 084 * @throws CheckDigitException if an error occurs calculating the check digit 085 */ 086 @Override 087 public String calculate(final String code) throws CheckDigitException { 088 if (GenericValidator.isBlankOrNull(code)) { 089 throw new CheckDigitException("Code is missing"); 090 } 091 final int modulusResult = calculateModulus(code, false); 092 final int charValue = (modulus - modulusResult) % modulus; 093 return toCheckDigit(charValue); 094 } 095 096 /** 097 * Calculate the modulus for a code. 098 * 099 * @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(final String code, final boolean includesCheckDigit) throws CheckDigitException { 106 int total = 0; 107 for (int i = 0; i < code.length(); i++) { 108 final int lth = code.length() + (includesCheckDigit ? 0 : 1); 109 final int leftPos = i + 1; 110 final int rightPos = lth - i; 111 final 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 * Gets the modulus value this check digit routine is based on. 122 * 123 * @return The modulus value this check digit routine is based on 124 */ 125 public int getModulus() { 126 return modulus; 127 } 128 129 /** 130 * Validate a modulus check digit for a code. 131 * 132 * @param code The code to validate 133 * @return {@code true} if the check digit is valid, otherwise 134 * {@code false} 135 */ 136 @Override 137 public boolean isValid(final String code) { 138 if (GenericValidator.isBlankOrNull(code)) { 139 return false; 140 } 141 try { 142 final int modulusResult = calculateModulus(code, true); 143 return modulusResult == 0; 144 } catch (final CheckDigitException ex) { 145 return false; 146 } 147 } 148 149 /** 150 * Convert an integer value to a check digit. 151 * <p> 152 * <b>Note:</b> this implementation only handles single-digit numeric values 153 * For non-numeric characters, override this method to provide 154 * integer-->character conversion. 155 * 156 * @param charValue The integer value of the character 157 * @return The converted character 158 * @throws CheckDigitException if integer character value 159 * doesn't represent a numeric character 160 */ 161 protected String toCheckDigit(final int charValue) throws CheckDigitException { 162 if (charValue >= 0 && charValue <= 9) { // CHECKSTYLE IGNORE MagicNumber 163 return Integer.toString(charValue); 164 } 165 throw new CheckDigitException("Invalid Check Digit Value =" + +charValue); 166 } 167 168 /** 169 * Convert a character at a specified position to an integer value. 170 * <p> 171 * <b>Note:</b> this implementation only handlers numeric values 172 * For non-numeric characters, override this method to provide 173 * character-->integer conversion. 174 * 175 * @param character The character to convert 176 * @param leftPos The position of the character in the code, counting from left to right (for identifiying the position in the string) 177 * @param rightPos The position of the character in the code, counting from right to left (not used here) 178 * @return The integer value of the character 179 * @throws CheckDigitException if character is non-numeric 180 */ 181 protected int toInt(final char character, final int leftPos, final int rightPos) throws CheckDigitException { 182 if (Character.isDigit(character)) { 183 return Character.getNumericValue(character); 184 } 185 throw new CheckDigitException("Invalid Character[" + leftPos + "] = '" + character + "'"); 186 } 187 188 /** 189 * Calculates the <i>weighted</i> value of a character in the 190 * code at a specified position. 191 * <p> 192 * Some modulus routines weight the value of a character 193 * depending on its position in the code (e.g. ISBN-10), while 194 * others use different weighting factors for odd/even positions 195 * (e.g. EAN or Luhn). Implement the appropriate mechanism 196 * required by overriding this method. 197 * 198 * @param charValue The numeric value of the character 199 * @param leftPos The position of the character in the code, counting from left to right 200 * @param rightPos The positionof the character in the code, counting from right to left 201 * @return The weighted value of the character 202 * @throws CheckDigitException if an error occurs calculating 203 * the weighted value 204 */ 205 protected abstract int weightedValue(int charValue, int leftPos, int rightPos) throws CheckDigitException; 206 207}