Olá pessoal após criar o Barcode Master para identificar os produtos via o código de barras EAN. Eu encontrei a necessidade de adicionar uma pre validação do código antes de pesquisar na API REST. Eu encontrei uma versão de JavaScript no GitHub Gist e escrevi em Java. Funcionou bem e estou compartilhando com vocês.
/**
* checksum calculation for GTIN-8, GTIN-12, GTIN-13, GTIN-14, and SSCC
* based on http://www.gs1.org/barcodes/support/check_digit_calculator
* @param barCode
* @return
*/
public static boolean isValidBarCodeEAN(String barCode) {
try {
if (barCode.length() < 8 || barCode.length() > 18 ||
(barCode.length() != 8 && barCode.length() != 12 &&
barCode.length() != 13 && barCode.length() != 14 &&
barCode.length() != 18)) {
return false;
}
int lastDigit = 0;
int checkSum = 0;
String ean = "";
int oddTotal = 0;
int evenTotal = 0;
//is digit
if (!Character.isDigit(barCode.charAt(barCode.length() - 1))) return false;
lastDigit = Integer.parseInt("" + barCode.charAt(barCode.length() - 1));
StringBuilder eanReverse = new StringBuilder();
ean = barCode.substring(0, barCode.length() - 1);
eanReverse = eanReverse.append(ean).reverse();
for (int i = 0; i <= eanReverse.length() - 1; i++) {
//is digit
if (!Character.isDigit(eanReverse.charAt(i))) return false;
if (i % 2 == 0) {
oddTotal += Integer.parseInt("" + eanReverse.charAt(i)) * 3;
} else {
evenTotal += Integer.parseInt("" + eanReverse.charAt(i));
}
}
checkSum = (10 - ((evenTotal + oddTotal) % 10)) % 10;
return (lastDigit == checkSum);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}