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