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