Source code
Description: source: package: org.apache.commons.validator.routines.checkdigit, class: VerhoeffCheckDigit

    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 *      https://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 * <strong>Verhoeff</strong> (Dihedral) Check Digit calculation/validation.
    025 * <p>
    026 * Check digit calculation for numeric codes using a <a href="https://en.wikipedia.org/wiki/Dihedral_group">Dihedral Group</a> of order 10.
    027 * </p>
    028 * <p>
    029 * See <a href="https://en.wikipedia.org/wiki/Verhoeff_algorithm">Wikipedia - Verhoeff algorithm</a> for more details.
    030 * </p>
    031 *
    032 * @since 1.4
    033 */
    034public final class VerhoeffCheckDigit extends AbstractCheckDigit implements Serializable {
    035
    036    private static final long serialVersionUID = 4138993995483695178L;
    037
    038    /**
    039     * Singleton Verhoeff Check Digit instance.
    040     */
    041    public static final CheckDigit VERHOEFF_CHECK_DIGIT = new VerhoeffCheckDigit();
    042
    043    /** D - multiplication table */
    044    private static final int[][] D_TABLE = {
    045        {0, 1, 2, 3, 4, 5, 6, 7, 8, 9},
    046        {1, 2, 3, 4, 0, 6, 7, 8, 9, 5},
    047        {2, 3, 4, 0, 1, 7, 8, 9, 5, 6},
    048        {3, 4, 0, 1, 2, 8, 9, 5, 6, 7},
    049        {4, 0, 1, 2, 3, 9, 5, 6, 7, 8},
    050        {5, 9, 8, 7, 6, 0, 4, 3, 2, 1},
    051        {6, 5, 9, 8, 7, 1, 0, 4, 3, 2},
    052        {7, 6, 5, 9, 8, 2, 1, 0, 4, 3},
    053        {8, 7, 6, 5, 9, 3, 2, 1, 0, 4},
    054        {9, 8, 7, 6, 5, 4, 3, 2, 1, 0}};
    055
    056    /** P - permutation table */
    057    private static final int[][] P_TABLE = {
    058        {0, 1, 2, 3, 4, 5, 6, 7, 8, 9},
    059        {1, 5, 7, 6, 2, 8, 3, 0, 9, 4},
    060        {5, 8, 0, 3, 7, 9, 6, 1, 4, 2},
    061        {8, 9, 1, 6, 0, 4, 3, 5, 2, 7},
    062        {9, 4, 5, 3, 1, 2, 6, 8, 7, 0},
    063        {4, 2, 8, 6, 5, 7, 3, 9, 0, 1},
    064        {2, 7, 9, 3, 8, 0, 6, 4, 1, 5},
    065        {7, 0, 4, 6, 9, 1, 3, 2, 5, 8}};
    066
    067    /** Inverse table */
    068    private static final int[] INV_TABLE = {0, 4, 3, 2, 1, 5, 6, 7, 8, 9};
    069
    070    /**
    071     * Constructs a new instance.
    072     */
    073    public VerhoeffCheckDigit() {
    074        // empty
    075    }
    076
    077    /**
    078     * Calculate a Verhoeff <em>Check Digit</em> for a code.
    079     *
    080     * @param code The code to calculate the Check Digit for.
    081     * @return The calculated Check Digit.
    082     * @throws CheckDigitException if an error occurs calculating the check digit for the specified code.
    083     */
    084    @Override
    085    public String calculate(final String code) throws CheckDigitException {
    086        if (GenericValidator.isBlankOrNull(code)) {
    087            throw new CheckDigitException("Code is missing");
    088        }
    089        return Integer.toString(INV_TABLE[calculateChecksum(code, false)]);
    090    }
    091
    092    /**
    093     * Calculate the checksum.
    094     *
    095     * @param code               The code to calculate the checksum for.
    096     * @param includesCheckDigit Whether the code includes the Check Digit or not.
    097     * @return The checksum value.
    098     * @throws CheckDigitException if the code contains an invalid character (that is, a non-numeric character).
    099     */
    100    private int calculateChecksum(final String code, final boolean includesCheckDigit) throws CheckDigitException {
    101        int checksum = 0;
    102        for (int i = 0; i < code.length(); i++) {
    103            final int idx = code.length() - (i + 1);
    104            final char ch = code.charAt(idx);
    105            if (!isAsciiDigit(ch)) {
    106                throw new CheckDigitException("Invalid Character[%d] = '%d'", i, (int) ch);
    107            }
    108            final int num = ch - '0';
    109            final int pos = includesCheckDigit ? i : i + 1;
    110            checksum = D_TABLE[checksum][P_TABLE[pos % 8][num]]; // CHECKSTYLE IGNORE MagicNumber
    111        }
    112        return checksum;
    113    }
    114
    115    /**
    116     * Validate the Verhoeff <em>Check Digit</em> for a code.
    117     *
    118     * @param code The code to validate.
    119     * @return {@code true} if the check digit is valid, otherwise {@code false}.
    120     */
    121    @Override
    122    public boolean isValid(final String code) {
    123        if (GenericValidator.isBlankOrNull(code)) {
    124            return false;
    125        }
    126        try {
    127            return calculateChecksum(code, true) == 0;
    128        } catch (final CheckDigitException e) {
    129            return false;
    130        }
    131    }
    132}