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