Added an ISBN parsed result type courtesy of jbreiden.
[zxing.git] / core / src / com / google / zxing / client / result / ResultParser.java
1 /*
2  * Copyright 2007 ZXing authors
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package com.google.zxing.client.result;
18
19 import com.google.zxing.Result;
20
21 import java.util.Hashtable;
22 import java.util.Vector;
23
24 /**
25  * <p>Abstract class representing the result of decoding a barcode, as more than
26  * a String -- as some type of structured data. This might be a subclass which represents
27  * a URL, or an e-mail address. {@link #parseResult(com.google.zxing.Result)} will turn a raw
28  * decoded string into the most appropriate type of structured representation.</p>
29  *
30  * <p>Thanks to Jeff Griffin for proposing rewrite of these classes that relies less
31  * on exception-based mechanisms during parsing.</p>
32  *
33  * @author srowen@google.com (Sean Owen)
34  */
35 public abstract class ResultParser {
36
37   public static ParsedResult parseResult(Result theResult) {
38     // This is a bit messy, but given limited options in MIDP / CLDC, this may well be the simplest
39     // way to go about this. For example, we have no reflection available, really.
40     // Order is important here.
41     ParsedResult result;
42     if ((result = BookmarkDoCoMoResultParser.parse(theResult)) != null) {
43       return result;
44     } else if ((result = AddressBookDoCoMoResultParser.parse(theResult)) != null) {
45       return result;
46     } else if ((result = EmailDoCoMoResultParser.parse(theResult)) != null) {
47       return result;
48     } else if ((result = EmailAddressResultParser.parse(theResult)) != null) {
49       return result;
50     } else if ((result = AddressBookAUResultParser.parse(theResult)) != null) {
51       return result;
52     } else if ((result = VCardResultParser.parse(theResult)) != null) {
53       return result;
54     } else if ((result = BizcardResultParser.parse(theResult)) != null) {
55       return result;
56     } else if ((result = VEventResultParser.parse(theResult)) != null) {
57       return result;
58     } else if ((result = TelResultParser.parse(theResult)) != null) {
59       return result;
60     } else if ((result = SMSMMSResultParser.parse(theResult)) != null) {
61       return result;
62     } else if ((result = GeoResultParser.parse(theResult)) != null) {
63       return result;
64     } else if ((result = URLTOResultParser.parse(theResult)) != null) {
65       return result;
66     } else if ((result = URIResultParser.parse(theResult)) != null) {
67       return result;
68     } else if ((result = ISBNResultParser.parse(theResult)) != null) {
69       return result;
70     } else if ((result = UPCResultParser.parse(theResult)) != null) {
71       return result;
72     }
73     return new TextParsedResult(theResult.getText(), null);
74   }
75
76   protected static void maybeAppend(String value, StringBuffer result) {
77     if (value != null) {
78       result.append('\n');
79       result.append(value);
80     }
81   }
82
83   protected static void maybeAppend(String[] value, StringBuffer result) {
84     if (value != null) {
85       for (int i = 0; i < value.length; i++) {
86         result.append('\n');
87         result.append(value[i]);
88       }
89     }
90   }
91
92   protected static String unescapeBackslash(String escaped) {
93     if (escaped != null) {
94       int backslash = escaped.indexOf((int) '\\');
95       if (backslash >= 0) {
96         int max = escaped.length();
97         StringBuffer unescaped = new StringBuffer(max - 1);
98         unescaped.append(escaped.toCharArray(), 0, backslash);
99         boolean nextIsEscaped = false;
100         for (int i = backslash; i < max; i++) {
101           char c = escaped.charAt(i);
102           if (nextIsEscaped || c != '\\') {
103             unescaped.append(c);
104             nextIsEscaped = false;
105           } else {
106             nextIsEscaped = true;
107           }
108         }
109         return unescaped.toString();
110       }
111     }
112     return escaped;
113   }
114
115   static String urlDecode(String escaped) {
116
117     // No we can't use java.net.URLDecoder here. JavaME doesn't have it.
118     if (escaped == null) {
119       return null;
120     }
121     char[] escapedArray = escaped.toCharArray();
122
123     int first = findFirstEscape(escapedArray);
124     if (first < 0) {
125       return escaped;
126     }
127
128     int max = escapedArray.length;
129     // final length is at most 2 less than original due to at least 1 unescaping
130     StringBuffer unescaped = new StringBuffer(max - 2);
131     // Can append everything up to first escape character
132     unescaped.append(escapedArray, 0, first);
133
134     for (int i = first; i < max; i++) {
135       char c = escapedArray[i];
136       if (c == '+') {
137         // + is translated directly into a space
138         unescaped.append(' ');
139       } else if (c == '%') {
140         // Are there even two more chars? if not we will just copy the escaped sequence and be done
141         if (i >= max - 2) {
142           unescaped.append('%'); // append that % and move on
143         } else {
144           int firstDigitValue = parseHexDigit(escapedArray[++i]);
145           int secondDigitValue = parseHexDigit(escapedArray[++i]);
146           if (firstDigitValue < 0 || secondDigitValue < 0) {
147             // bad digit, just move on
148             unescaped.append('%');
149             unescaped.append(escapedArray[i-1]);
150             unescaped.append(escapedArray[i]);
151           }
152           unescaped.append((char) ((firstDigitValue << 4) + secondDigitValue));
153         }
154       } else {
155         unescaped.append(c);
156       }
157     }
158     return unescaped.toString();
159   }
160
161   private static int findFirstEscape(char[] escapedArray) {
162     int max = escapedArray.length;
163     for (int i = 0; i < max; i++) {
164       char c = escapedArray[i];
165       if (c == '+' || c == '%') {
166         return i;
167       }
168     }
169     return -1;
170   }
171
172   private static int parseHexDigit(char c) {
173     if (c >= 'a') {
174       if (c <= 'f') {
175         return 10 + (c - 'a');
176       }
177     } else if (c >= 'A') {
178       if (c <= 'F') {
179         return 10 + (c - 'A');
180       }
181     } else if (c >= '0') {
182       if (c <= '9') {
183         return c - '0';
184       }
185     }
186     return -1;
187   }
188
189   protected static boolean isStringOfDigits(String value, int length) {
190     if (value == null) {
191       return false;
192     }
193     int stringLength = value.length();
194     if (length != stringLength) {
195       return false;
196     }
197     for (int i = 0; i < length; i++) {
198       char c = value.charAt(i);
199       if (c < '0' || c > '9') {
200         return false;
201       }
202     }
203     return true;
204   }
205
206   static Hashtable parseNameValuePairs(String uri) {
207     int paramStart = uri.indexOf('?');
208     if (paramStart < 0) {
209       return null;
210     }
211     Hashtable result = new Hashtable(3);
212     paramStart++;
213     int paramEnd;
214     while ((paramEnd = uri.indexOf('&', paramStart)) >= 0) {
215       appendKeyValue(uri, paramStart, paramEnd, result);
216       paramStart = paramEnd + 1;
217     }
218     appendKeyValue(uri, paramStart, uri.length(), result);
219     return result;
220   }
221
222   private static void appendKeyValue(String uri, int paramStart, int paramEnd, Hashtable result) {
223     int separator = uri.indexOf('=', paramStart);
224     if (separator >= 0) {
225       // key = value
226       String key = uri.substring(paramStart, separator);
227       String value = uri.substring(separator + 1, paramEnd);
228       value = urlDecode(value);
229       result.put(key, value);
230     } else {
231       // key, no value
232       String key = uri.substring(paramStart, paramEnd);
233       result.put(key, null);
234     }
235   }
236
237   static String[] matchPrefixedField(String prefix, String rawText, char endChar) {
238     Vector matches = null;
239     int i = 0;
240     int max = rawText.length();
241     while (i < max) {
242       i = rawText.indexOf(prefix, i);
243       if (i < 0) {
244         break;
245       }
246       i += prefix.length(); // Skip past this prefix we found to start
247       int start = i; // Found the start of a match here
248       boolean done = false;
249       while (!done) {
250         i = rawText.indexOf((int) endChar, i);
251         if (i < 0) {
252           // No terminating end character? uh, done. Set i such that loop terminates and break
253           i = rawText.length();
254           done = true;
255         } else if (rawText.charAt(i - 1) == '\\') {
256           // semicolon was escaped so continue
257           i++;
258         } else {
259           // found a match
260           if (matches == null) {
261             matches = new Vector(3); // lazy init
262           }
263           matches.addElement(unescapeBackslash(rawText.substring(start, i)));
264           i++;
265           done = true;
266         }
267       }
268     }
269     if (matches == null || matches.isEmpty()) {
270       return null;
271     }
272     return toStringArray(matches);
273   }
274
275   static String matchSinglePrefixedField(String prefix, String rawText, char endChar) {
276     String[] matches = matchPrefixedField(prefix, rawText, endChar);
277     return matches == null ? null : matches[0];
278   }
279
280   static String[] toStringArray(Vector strings) {
281     int size = strings.size();
282     String[] result = new String[size];
283     for (int j = 0; j < size; j++) {
284       result[j] = (String) strings.elementAt(j);
285     }
286     return result;
287   }
288
289 }