1 package org.kuali.ole.docstore.utility;
2
3 import org.kuali.ole.docstore.OleException;
4 import org.slf4j.Logger;
5 import org.slf4j.LoggerFactory;
6
7 import java.util.regex.Matcher;
8 import java.util.regex.Pattern;
9
10
11
12
13
14
15
16
17 public class ISBNUtil {
18
19 private static final Logger LOG = LoggerFactory.getLogger(DocStoreSettingsUtil.class);
20
21 public String normalizeISBN(Object isbn) throws OleException {
22 String value = (String) isbn;
23 if (value != null) {
24 String modifiedValue = getModifiedString(value);
25 int len = modifiedValue.length();
26 if (len == 13) {
27 return modifiedValue;
28 } else if (len == 10) {
29 String regex = "[0-9]{9}[xX]{1}";
30 String regexNum = "[0-9]{10}";
31 value = getIsbnRegexValue(regexNum, modifiedValue);
32 if (value.length() == 0) {
33 value = getIsbnRegexValue(regex, modifiedValue);
34 }
35 if (value.length() > 0) {
36 value = calculateIsbnValue(value);
37 }
38 } else {
39 throw new OleException("Invalid ISBN Value: " + isbn);
40 }
41 if (value.length() == 0) {
42 throw new OleException("Normalization failed" + isbn);
43 }
44 }
45 return value;
46 }
47
48 private String getModifiedString(String value) {
49 String modifiedValue = value;
50 if (modifiedValue.contains("(") && modifiedValue.contains(")")) {
51 String parenthesesValue = modifiedValue
52 .substring(modifiedValue.indexOf("("), modifiedValue.lastIndexOf(")") + 1);
53 modifiedValue = modifiedValue.replace(parenthesesValue, "");
54 }
55 modifiedValue = modifiedValue.replaceAll("[-:\\s]", "");
56 return modifiedValue;
57 }
58
59 private String getIsbnRegexValue(String regex, String value) {
60 Pattern pattern = Pattern.compile(regex);
61 Matcher matcher = pattern.matcher(value);
62 String matchingValue = null;
63 if (matcher.find()) {
64 matchingValue = matcher.group(0);
65 matchingValue = value.substring(0, 9);
66 } else {
67 matchingValue = "";
68 }
69 return matchingValue;
70 }
71
72 private String calculateIsbnValue(String value) {
73 String num = value;
74 if (num.length() == 9) {
75 num = "978" + num;
76 try {
77 num = getNormalizedIsbn(num);
78 } catch (Exception e) {
79 LOG.error("Unable to normalize the modified ISBN value " + value + e.getMessage());
80 num = "";
81 }
82 }
83 return num;
84 }
85
86 private String getNormalizedIsbn(String value) {
87 String normalizeIsbn = value;
88 int count = 0;
89 int multiple = 1;
90 for (int i = 0; i < value.length(); i++) {
91 Character c = new Character(value.charAt(i));
92 int j = Integer.parseInt(c.toString());
93 int sum = j * multiple;
94 count = count + sum;
95 if (i != 0 && i % 2 != 0) {
96 multiple = 1;
97 } else {
98 multiple = 3;
99 }
100 }
101 count = count % 10;
102 if (count == 0) {
103 count = 0;
104 } else {
105 count = 10 - count;
106 }
107 normalizeIsbn = normalizeIsbn + Integer.toString(count);
108 return normalizeIsbn;
109 }
110 }