-
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
82 additions
and
39 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,76 @@ | ||
package net.sf.jabref.logic.util; | ||
|
||
import java.util.Objects; | ||
import java.util.regex.Matcher; | ||
import java.util.regex.Pattern; | ||
|
||
public class ISBN { | ||
|
||
private static final Pattern ISBN_PATTERN = Pattern.compile("^(\\d{9}[\\dxX]|\\d{13})$"); | ||
|
||
private final String isbn; | ||
|
||
|
||
public ISBN(String isbnString) { | ||
this.isbn = Objects.requireNonNull(isbnString).trim().replace("-", ""); | ||
} | ||
|
||
public boolean isValidFormat() { | ||
Matcher isbnMatcher = ISBN_PATTERN.matcher(isbn); | ||
if (isbnMatcher.matches()) { | ||
return true; | ||
} | ||
return false; | ||
} | ||
|
||
public boolean isValidChecksum() { | ||
boolean valid; | ||
if (isbn.length() == 10) { | ||
valid = isbn10check(); | ||
} else { | ||
// length is either 10 or 13 based on regexp so will be 13 here | ||
valid = isbn13check(); | ||
} | ||
return valid; | ||
} | ||
|
||
public boolean isIsbn10() { | ||
return isbn10check(); | ||
} | ||
|
||
public boolean isIsbn13() { | ||
return isbn13check(); | ||
} | ||
|
||
// Check that the control digit is correct, see e.g. https://en.wikipedia.org/wiki/International_Standard_Book_Number#Check_digits | ||
private boolean isbn10check() { | ||
if ((isbn == null) || (isbn.length() != 10)) { | ||
return false; | ||
} | ||
|
||
int sum = 0; | ||
for (int pos = 0; pos <= 8; pos++) { | ||
sum += (isbn.charAt(pos) - '0') * ((10 - pos)); | ||
} | ||
char control = isbn.charAt(9); | ||
if ((control == 'x') || (control == 'X')) { | ||
control = '9' + 1; | ||
} | ||
sum += (control - '0'); | ||
return (sum % 11) == 0; | ||
} | ||
|
||
// Check that the control digit is correct, see e.g. https://en.wikipedia.org/wiki/International_Standard_Book_Number#Check_digits | ||
private boolean isbn13check() { | ||
if ((isbn == null) || (isbn.length() != 13)) { | ||
return false; | ||
} | ||
|
||
int sum = 0; | ||
for (int pos = 0; pos <= 12; pos++) { | ||
sum += (isbn.charAt(pos) - '0') * ((pos % 2) == 0 ? 1 : 3); | ||
} | ||
return (sum % 10) == 0; | ||
} | ||
|
||
} |