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