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