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.item.server.logic.checksum; 018 019import com.echothree.util.common.message.ExecutionErrors; 020import com.echothree.util.server.message.ExecutionErrorAccumulator; 021import javax.enterprise.context.ApplicationScoped; 022import javax.enterprise.inject.spi.CDI; 023 024@ApplicationScoped 025public class Isbn10ChecksumLogic 026 extends BaseChecksumLogic 027 implements ItemAliasChecksumInterface { 028 029 protected Isbn10ChecksumLogic() { 030 super(); 031 } 032 033 public static Isbn10ChecksumLogic getInstance() { 034 return CDI.current().select(Isbn10ChecksumLogic.class).get(); 035 } 036 037 private int getIsbn10CheckDigit(String alias, int offset) { 038 var result = -1; 039 var digit = alias.charAt(offset); 040 041 if(digit >= '0' && digit <= '9') { 042 result = digit - '0'; 043 } else if(digit == 'X') { 044 result = 10; 045 } 046 047 return result; 048 } 049 050 @Override 051 public void checkChecksum(final ExecutionErrorAccumulator eea, final String alias) { 052 if(alias.length() == 10) { 053 var hasCharacterError = false; 054 var runningTotal = 0; 055 var checksum = 0; 056 057 for(var i = 0; i < 9; i++) { 058 var digit = getDigit(alias, i); 059 060 if(digit == -1) { 061 hasCharacterError = true; 062 break; 063 } else { 064 runningTotal += digit; 065 checksum += runningTotal; 066 } 067 } 068 069 if(!hasCharacterError) { 070 var checkDigit = getIsbn10CheckDigit(alias, 9); 071 072 hasCharacterError = checkDigit == -1; 073 074 if(!hasCharacterError) { 075 runningTotal += checkDigit; 076 checksum += runningTotal; 077 078 if(checksum % 11 != 0) { 079 eea.addExecutionError(ExecutionErrors.IncorrectIsbn10Checksum.name(), alias); 080 } 081 } 082 } 083 084 if(hasCharacterError) { 085 eea.addExecutionError(ExecutionErrors.IncorrectIsbn10Character.name(), alias); 086 } 087 } else { 088 eea.addExecutionError(ExecutionErrors.IncorrectIsbn10Length.name(), alias); 089 } 090 } 091 092}