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