Renamed UPC result type to Product, and introduced an idea of 'product ID' and 'norma...
[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       // We depend on ISBN parsing coming before UPC, as it is a subset.
70       return result;
71     } else if ((result = ProductResultParser.parse(theResult)) != null) {
72       return result;
73     }
74     return new TextParsedResult(theResult.getText(), null);
75   }
76
77   protected static void maybeAppend(String value, StringBuffer result) {
78     if (value != null) {
79       result.append('\n');
80       result.append(value);
81     }
82   }
83
84   protected static void maybeAppend(String[] value, StringBuffer result) {
85     if (value != null) {
86       for (int i = 0; i < value.length; i++) {
87         result.append('\n');
88         result.append(value[i]);
89       }
90     }
91   }
92
93   protected static String unescapeBackslash(String escaped) {
94     if (escaped != null) {
95       int backslash = escaped.indexOf((int) '\\');
96       if (backslash >= 0) {
97         int max = escaped.length();
98         StringBuffer unescaped = new StringBuffer(max - 1);
99         unescaped.append(escaped.toCharArray(), 0, backslash);
100         boolean nextIsEscaped = false;
101         for (int i = backslash; i < max; i++) {
102           char c = escaped.charAt(i);
103           if (nextIsEscaped || c != '\\') {
104             unescaped.append(c);
105             nextIsEscaped = false;
106           } else {
107             nextIsEscaped = true;
108           }
109         }
110         return unescaped.toString();
111       }
112     }
113     return escaped;
114   }
115
116   static String urlDecode(String escaped) {
117
118     // No we can't use java.net.URLDecoder here. JavaME doesn't have it.
119     if (escaped == null) {
120       return null;
121     }
122     char[] escapedArray = escaped.toCharArray();
123
124     int first = findFirstEscape(escapedArray);
125     if (first < 0) {
126       return escaped;
127     }
128
129     int max = escapedArray.length;
130     // final length is at most 2 less than original due to at least 1 unescaping
131     StringBuffer unescaped = new StringBuffer(max - 2);
132     // Can append everything up to first escape character
133     unescaped.append(escapedArray, 0, first);
134
135     for (int i = first; i < max; i++) {
136       char c = escapedArray[i];
137       if (c == '+') {
138         // + is translated directly into a space
139         unescaped.append(' ');
140       } else if (c == '%') {
141         // Are there even two more chars? if not we will just copy the escaped sequence and be done
142         if (i >= max - 2) {
143           unescaped.append('%'); // append that % and move on
144         } else {
145           int firstDigitValue = parseHexDigit(escapedArray[++i]);
146           int secondDigitValue = parseHexDigit(escapedArray[++i]);
147           if (firstDigitValue < 0 || secondDigitValue < 0) {
148             // bad digit, just move on
149             unescaped.append('%');
150             unescaped.append(escapedArray[i-1]);
151             unescaped.append(escapedArray[i]);
152           }
153           unescaped.append((char) ((firstDigitValue << 4) + secondDigitValue));
154         }
155       } else {
156         unescaped.append(c);
157       }
158     }
159     return unescaped.toString();
160   }
161
162   private static int findFirstEscape(char[] escapedArray) {
163     int max = escapedArray.length;
164     for (int i = 0; i < max; i++) {
165       char c = escapedArray[i];
166       if (c == '+' || c == '%') {
167         return i;
168       }
169     }
170     return -1;
171   }
172
173   private static int parseHexDigit(char c) {
174     if (c >= 'a') {
175       if (c <= 'f') {
176         return 10 + (c - 'a');
177       }
178     } else if (c >= 'A') {
179       if (c <= 'F') {
180         return 10 + (c - 'A');
181       }
182     } else if (c >= '0') {
183       if (c <= '9') {
184         return c - '0';
185       }
186     }
187     return -1;
188   }
189
190   protected static boolean isStringOfDigits(String value, int length) {
191     if (value == null) {
192       return false;
193     }
194     int stringLength = value.length();
195     if (length != stringLength) {
196       return false;
197     }
198     for (int i = 0; i < length; i++) {
199       char c = value.charAt(i);
200       if (c < '0' || c > '9') {
201         return false;
202       }
203     }
204     return true;
205   }
206
207   static Hashtable parseNameValuePairs(String uri) {
208     int paramStart = uri.indexOf('?');
209     if (paramStart < 0) {
210       return null;
211     }
212     Hashtable result = new Hashtable(3);
213     paramStart++;
214     int paramEnd;
215     while ((paramEnd = uri.indexOf('&', paramStart)) >= 0) {
216       appendKeyValue(uri, paramStart, paramEnd, result);
217       paramStart = paramEnd + 1;
218     }
219     appendKeyValue(uri, paramStart, uri.length(), result);
220     return result;
221   }
222
223   private static void appendKeyValue(String uri, int paramStart, int paramEnd, Hashtable result) {
224     int separator = uri.indexOf('=', paramStart);
225     if (separator >= 0) {
226       // key = value
227       String key = uri.substring(paramStart, separator);
228       String value = uri.substring(separator + 1, paramEnd);
229       value = urlDecode(value);
230       result.put(key, value);
231     } else {
232       // key, no value
233       String key = uri.substring(paramStart, paramEnd);
234       result.put(key, null);
235     }
236   }
237
238   static String[] matchPrefixedField(String prefix, String rawText, char endChar, boolean trim) {
239     Vector matches = null;
240     int i = 0;
241     int max = rawText.length();
242     while (i < max) {
243       i = rawText.indexOf(prefix, i);
244       if (i < 0) {
245         break;
246       }
247       i += prefix.length(); // Skip past this prefix we found to start
248       int start = i; // Found the start of a match here
249       boolean done = false;
250       while (!done) {
251         i = rawText.indexOf((int) endChar, i);
252         if (i < 0) {
253           // No terminating end character? uh, done. Set i such that loop terminates and break
254           i = rawText.length();
255           done = true;
256         } else if (rawText.charAt(i - 1) == '\\') {
257           // semicolon was escaped so continue
258           i++;
259         } else {
260           // found a match
261           if (matches == null) {
262             matches = new Vector(3); // lazy init
263           }
264           String element = unescapeBackslash(rawText.substring(start, i));
265           if (trim) {
266             element = element.trim();
267           }
268           matches.addElement(element);
269           i++;
270           done = true;
271         }
272       }
273     }
274     if (matches == null || matches.isEmpty()) {
275       return null;
276     }
277     return toStringArray(matches);
278   }
279
280   static String matchSinglePrefixedField(String prefix, String rawText, char endChar, boolean trim) {
281     String[] matches = matchPrefixedField(prefix, rawText, endChar, trim);
282     return matches == null ? null : matches[0];
283   }
284
285   static String[] toStringArray(Vector strings) {
286     int size = strings.size();
287     String[] result = new String[size];
288     for (int j = 0; j < size; j++) {
289       result[j] = (String) strings.elementAt(j);
290     }
291     return result;
292   }
293
294 }