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 Isbn13ChecksumLogic 026 extends BaseChecksumLogic 027 implements ItemAliasChecksumInterface { 028 029 protected Isbn13ChecksumLogic() { 030 super(); 031 } 032 033 public static Isbn13ChecksumLogic getInstance() { 034 return CDI.current().select(Isbn13ChecksumLogic.class).get(); 035 } 036 037 @Override 038 public void checkChecksum(final ExecutionErrorAccumulator eea, final String alias) { 039 if(alias.length() == 13) { 040 var hasCharacterError = false; 041 var checksum = 0; 042 043 for(int i = 0; i < 12; i++) { 044 int d = getDigit(alias, i); 045 046 if(d == -1) { 047 hasCharacterError = true; 048 break; 049 } 050 051 // Positions are 1-based in the spec: odd positions weight 1, even positions weight 3. 052 // i is 0-based, so i % 2 == 0 means even position. 053 checksum += i % 2 == 0 ? d : (3 * d); 054 } 055 056 if(!hasCharacterError) { 057 var checkDigit = getDigit(alias, 12); 058 059 hasCharacterError = checkDigit == -1; 060 061 if(!hasCharacterError) { 062 checksum += checkDigit; 063 064 if(!(checksum % 10 == 0)) { 065 eea.addExecutionError(ExecutionErrors.IncorrectIsbn13Checksum.name(), alias); 066 } 067 } 068 } 069 070 if(hasCharacterError) { 071 eea.addExecutionError(ExecutionErrors.IncorrectIsbn13Character.name(), alias); 072 } 073 } else { 074 eea.addExecutionError(ExecutionErrors.IncorrectIsbn13Length.name(), alias); 075 } 076 } 077 078 079}