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