be.fgov.minfin.webForm.util.ISINValidationUtil.java Source code

Java tutorial

Introduction

Here is the source code for be.fgov.minfin.webForm.util.ISINValidationUtil.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package be.fgov.minfin.webForm.util;

import org.apache.commons.validator.routines.checkdigit.CheckDigitException;
import org.apache.commons.validator.routines.checkdigit.ModulusCheckDigit;

/**
 *
 * @author gbeurnel
 */
public class ISINValidationUtil extends ModulusCheckDigit {

    private static final int[] POSITION_WEIGHT = new int[] { 2, 1 };

    public ISINValidationUtil() {
        super(10);
    }

    @Override
    protected int weightedValue(int charValue, int leftPos, int rightPos) throws CheckDigitException {
        int weight = POSITION_WEIGHT[rightPos % 2];
        int weightedValue = (charValue * weight);
        return ModulusCheckDigit.sumDigits(weightedValue);
    }

    public int calculcateModulus(String code, boolean includesCheckDigit) throws CheckDigitException {
        StringBuilder transformed = new StringBuilder(code.length() * 2);
        if (includesCheckDigit) {
            char checkDigit = code.charAt(code.length() - 1); // Choppe le dernier caractre
            if (!Character.isDigit(checkDigit)) {
                throw new CheckDigitException("Invalid checkdigit[" + checkDigit + "] in " + code);
            }
        }
        for (int i = 0; i < code.length(); i++) {
            int charValue = Character.getNumericValue(code.charAt(i));
            if (charValue < 0 || charValue > 35) {
                throw new CheckDigitException("Invalid Character[" + (i + 1) + "] = '" + charValue + "'");
            }
            transformed.append(charValue);
        }
        //Doit retourner 0 pour que ce soit valide
        return super.calculateModulus(transformed.toString(), includesCheckDigit);
    }

}