001// -------------------------------------------------------------------------------- 002// Copyright 2002-2025 Echo Three, LLC 003// 004// Licensed under the Apache License, Version 2.0 (the "License"); 005// you may not use this file except in compliance with the License. 006// You may obtain a copy of the License at 007// 008// http://www.apache.org/licenses/LICENSE-2.0 009// 010// Unless required by applicable law or agreed to in writing, software 011// distributed under the License is distributed on an "AS IS" BASIS, 012// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013// See the License for the specific language governing permissions and 014// limitations under the License. 015// -------------------------------------------------------------------------------- 016 017package com.echothree.model.control.sequence.server.logic.checksum; 018 019import com.echothree.model.control.sequence.server.logic.SequenceGeneratorLogic; 020import java.nio.charset.StandardCharsets; 021import javax.enterprise.context.ApplicationScoped; 022import javax.enterprise.inject.spi.CDI; 023 024@ApplicationScoped 025public class Mod10SequenceChecksum 026 implements SequenceChecksum { 027 028 protected Mod10SequenceChecksum() { 029 super(); 030 } 031 032 public static Mod10SequenceChecksum getInstance() { 033 return CDI.current().select(Mod10SequenceChecksum.class).get(); 034 } 035 036 @Override 037 public String calculate(String value) { 038 var bytes = value.getBytes(StandardCharsets.UTF_8); 039 var sum = 0; 040 041 for(var i = 0; i < bytes.length; i++) { 042 sum += (bytes [i] * (i + 1)); 043 } 044 045 var modCharacter = new char[]{SequenceGeneratorLogic.NUMERIC_VALUES.charAt(sum % SequenceGeneratorLogic.NUMERIC_MAX_INDEX)}; 046 return new String(modCharacter); 047 } 048 049 @Override 050 public String regexp() { 051 return "[\\p{Digit}]"; 052 } 053 054 @Override 055 public boolean verify(String value) { 056 var codePoints = value.codePoints().toArray(); 057 var length = codePoints.length; 058 var valueWithoutChecksum = new String(codePoints, 0, length - 1); 059 var checksumFromValue = new String(codePoints, length - 1, 1); 060 var checksum = calculate(valueWithoutChecksum); 061 062 return checksumFromValue.equals(checksum); 063 } 064 065}