VCardParserImpl_V21.java revision 9e87c7606b0593b6789cdd177d80e31b991c864c
1/* 2 * Copyright (C) 2010 The Android Open Source Project 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 */ 16package com.android.vcard; 17 18import android.text.TextUtils; 19import android.util.Base64; 20import android.util.Log; 21 22import com.android.vcard.exception.VCardAgentNotSupportedException; 23import com.android.vcard.exception.VCardException; 24import com.android.vcard.exception.VCardInvalidCommentLineException; 25import com.android.vcard.exception.VCardInvalidLineException; 26import com.android.vcard.exception.VCardVersionException; 27 28import java.io.BufferedReader; 29import java.io.IOException; 30import java.io.InputStream; 31import java.io.InputStreamReader; 32import java.io.Reader; 33import java.util.ArrayList; 34import java.util.Collection; 35import java.util.HashSet; 36import java.util.List; 37import java.util.Set; 38 39/** 40 * <p> 41 * Basic implementation achieving vCard parsing. Based on vCard 2.1. 42 * </p> 43 * @hide 44 */ 45/* package */ class VCardParserImpl_V21 { 46 private static final String LOG_TAG = VCardConstants.LOG_TAG; 47 48 protected static final class CustomBufferedReader extends BufferedReader { 49 private long mTime; 50 51 /** 52 * Needed since "next line" may be null due to end of line. 53 */ 54 private boolean mNextLineIsValid; 55 private String mNextLine; 56 57 public CustomBufferedReader(Reader in) { 58 super(in); 59 } 60 61 @Override 62 public String readLine() throws IOException { 63 if (mNextLineIsValid) { 64 final String ret = mNextLine; 65 mNextLine = null; 66 mNextLineIsValid = false; 67 return ret; 68 } 69 70 final long start = System.currentTimeMillis(); 71 final String line = super.readLine(); 72 final long end = System.currentTimeMillis(); 73 mTime += end - start; 74 return line; 75 } 76 77 /** 78 * Read one line, but make this object store it in its queue. 79 */ 80 public String peekLine() throws IOException { 81 if (!mNextLineIsValid) { 82 final long start = System.currentTimeMillis(); 83 final String line = super.readLine(); 84 final long end = System.currentTimeMillis(); 85 mTime += end - start; 86 87 mNextLine = line; 88 mNextLineIsValid = true; 89 } 90 91 return mNextLine; 92 } 93 94 public long getTotalmillisecond() { 95 return mTime; 96 } 97 } 98 99 private static final String DEFAULT_ENCODING = "8BIT"; 100 private static final String DEFAULT_CHARSET = "UTF-8"; 101 102 protected final String mIntermediateCharset; 103 104 private final List<VCardInterpreter> mInterpreterList = new ArrayList<VCardInterpreter>(); 105 private boolean mCanceled; 106 107 /** 108 * <p> 109 * The encoding type for deconding byte streams. This member variable is 110 * reset to a default encoding every time when a new item comes. 111 * </p> 112 * <p> 113 * "Encoding" in vCard is different from "Charset". It is mainly used for 114 * addresses, notes, images. "7BIT", "8BIT", "BASE64", and 115 * "QUOTED-PRINTABLE" are known examples. 116 * </p> 117 */ 118 protected String mCurrentEncoding; 119 120 protected String mCurrentCharset; 121 122 /** 123 * <p> 124 * The reader object to be used internally. 125 * </p> 126 * <p> 127 * Developers should not directly read a line from this object. Use 128 * getLine() unless there some reason. 129 * </p> 130 */ 131 protected CustomBufferedReader mReader; 132 133 /** 134 * <p> 135 * Set for storing unkonwn TYPE attributes, which is not acceptable in vCard 136 * specification, but happens to be seen in real world vCard. 137 * </p> 138 * <p> 139 * We just accept those invalid types after emitting a warning for each of it. 140 * </p> 141 */ 142 protected final Set<String> mUnknownTypeSet = new HashSet<String>(); 143 144 /** 145 * <p> 146 * Set for storing unkonwn VALUE attributes, which is not acceptable in 147 * vCard specification, but happens to be seen in real world vCard. 148 * </p> 149 * <p> 150 * We just accept those invalid types after emitting a warning for each of it. 151 * </p> 152 */ 153 protected final Set<String> mUnknownValueSet = new HashSet<String>(); 154 155 156 public VCardParserImpl_V21() { 157 this(VCardConfig.VCARD_TYPE_DEFAULT); 158 } 159 160 public VCardParserImpl_V21(int vcardType) { 161 mIntermediateCharset = VCardConfig.DEFAULT_INTERMEDIATE_CHARSET; 162 } 163 164 /** 165 * @return true when a given property name is a valid property name. 166 */ 167 protected boolean isValidPropertyName(final String propertyName) { 168 if (!(getKnownPropertyNameSet().contains(propertyName.toUpperCase()) || 169 propertyName.startsWith("X-")) 170 && !mUnknownTypeSet.contains(propertyName)) { 171 mUnknownTypeSet.add(propertyName); 172 Log.w(LOG_TAG, "Property name unsupported by vCard 2.1: " + propertyName); 173 } 174 return true; 175 } 176 177 /** 178 * @return String. It may be null, or its length may be 0 179 * @throws IOException 180 */ 181 protected String getLine() throws IOException { 182 return mReader.readLine(); 183 } 184 185 protected String peekLine() throws IOException { 186 return mReader.peekLine(); 187 } 188 189 /** 190 * @return String with it's length > 0 191 * @throws IOException 192 * @throws VCardException when the stream reached end of line 193 */ 194 protected String getNonEmptyLine() throws IOException, VCardException { 195 String line; 196 while (true) { 197 line = getLine(); 198 if (line == null) { 199 throw new VCardException("Reached end of buffer."); 200 } else if (line.trim().length() > 0) { 201 return line; 202 } 203 } 204 } 205 206 /** 207 * <code> 208 * vcard = "BEGIN" [ws] ":" [ws] "VCARD" [ws] 1*CRLF 209 * items *CRLF 210 * "END" [ws] ":" [ws] "VCARD" 211 * </code> 212 * @return False when reaching end of file. 213 */ 214 private boolean parseOneVCard() throws IOException, VCardException { 215 // reset for this entire vCard. 216 mCurrentEncoding = DEFAULT_ENCODING; 217 mCurrentCharset = DEFAULT_CHARSET; 218 219 boolean allowGarbage = false; 220 if (!readBeginVCard(allowGarbage)) { 221 return false; 222 } 223 for (VCardInterpreter interpreter : mInterpreterList) { 224 interpreter.onEntryStarted(); 225 } 226 parseItems(); 227 for (VCardInterpreter interpreter : mInterpreterList) { 228 interpreter.onEntryEnded(); 229 } 230 return true; 231 } 232 233 /** 234 * @return True when successful. False when reaching the end of line 235 * @throws IOException 236 * @throws VCardException 237 */ 238 protected boolean readBeginVCard(boolean allowGarbage) throws IOException, VCardException { 239 // TODO: use consructPropertyLine(). 240 String line; 241 do { 242 while (true) { 243 line = getLine(); 244 if (line == null) { 245 return false; 246 } else if (line.trim().length() > 0) { 247 break; 248 } 249 } 250 final String[] strArray = line.split(":", 2); 251 final int length = strArray.length; 252 253 // Although vCard 2.1/3.0 specification does not allow lower cases, 254 // we found vCard file emitted by some external vCard expoter have such 255 // invalid Strings. 256 // e.g. BEGIN:vCard 257 if (length == 2 && strArray[0].trim().equalsIgnoreCase("BEGIN") 258 && strArray[1].trim().equalsIgnoreCase("VCARD")) { 259 return true; 260 } else if (!allowGarbage) { 261 throw new VCardException("Expected String \"BEGIN:VCARD\" did not come " 262 + "(Instead, \"" + line + "\" came)"); 263 } 264 } while (allowGarbage); 265 266 throw new VCardException("Reached where must not be reached."); 267 } 268 269 /** 270 * Parses lines other than the first "BEGIN:VCARD". Takes care of "END:VCARD"n and 271 * "BEGIN:VCARD" in nested vCard. 272 */ 273 /* 274 * items = *CRLF item / item 275 * 276 * Note: BEGIN/END aren't include in the original spec while this method handles them. 277 */ 278 protected void parseItems() throws IOException, VCardException { 279 boolean ended = false; 280 281 try { 282 ended = parseItem(); 283 } catch (VCardInvalidCommentLineException e) { 284 Log.e(LOG_TAG, "Invalid line which looks like some comment was found. Ignored."); 285 } 286 287 while (!ended) { 288 try { 289 ended = parseItem(); 290 } catch (VCardInvalidCommentLineException e) { 291 Log.e(LOG_TAG, "Invalid line which looks like some comment was found. Ignored."); 292 } 293 } 294 } 295 296 /* 297 * item = [groups "."] name [params] ":" value CRLF / [groups "."] "ADR" 298 * [params] ":" addressparts CRLF / [groups "."] "ORG" [params] ":" orgparts 299 * CRLF / [groups "."] "N" [params] ":" nameparts CRLF / [groups "."] 300 * "AGENT" [params] ":" vcard CRLF 301 */ 302 protected boolean parseItem() throws IOException, VCardException { 303 // Reset for an item. 304 mCurrentEncoding = DEFAULT_ENCODING; 305 306 final String line = getNonEmptyLine(); 307 final VCardProperty propertyData = constructPropertyData(line); 308 309 final String propertyNameUpper = propertyData.getName().toUpperCase(); 310 final String propertyRawValue = propertyData.getRawValue(); 311 312 if (propertyNameUpper.equals(VCardConstants.PROPERTY_BEGIN)) { 313 if (propertyRawValue.equalsIgnoreCase("VCARD")) { 314 handleNest(); 315 } else { 316 throw new VCardException("Unknown BEGIN type: " + propertyRawValue); 317 } 318 } else if (propertyNameUpper.equals(VCardConstants.PROPERTY_END)) { 319 if (propertyRawValue.equalsIgnoreCase("VCARD")) { 320 return true; // Ended. 321 } else { 322 throw new VCardException("Unknown END type: " + propertyRawValue); 323 } 324 } else { 325 parseItemInter(propertyData, propertyNameUpper); 326 } 327 return false; 328 } 329 330 private void parseItemInter(VCardProperty property, String propertyNameUpper) 331 throws IOException, VCardException { 332 String propertyRawValue = property.getRawValue(); 333 if (propertyNameUpper.equals(VCardConstants.PROPERTY_AGENT)) { 334 handleAgent(property); 335 } else if (isValidPropertyName(propertyNameUpper)) { 336 if (propertyNameUpper.equals(VCardConstants.PROPERTY_VERSION) && 337 !propertyRawValue.equals(getVersionString())) { 338 throw new VCardVersionException( 339 "Incompatible version: " + propertyRawValue + " != " + getVersionString()); 340 } 341 handlePropertyValue(property, propertyNameUpper); 342 } else { 343 throw new VCardException("Unknown property name: \"" + propertyNameUpper + "\""); 344 } 345 } 346 347 private void handleNest() throws IOException, VCardException { 348 for (VCardInterpreter interpreter : mInterpreterList) { 349 interpreter.onEntryStarted(); 350 } 351 parseItems(); 352 for (VCardInterpreter interpreter : mInterpreterList) { 353 interpreter.onEntryEnded(); 354 } 355 } 356 357 // For performance reason, the states for group and property name are merged into one. 358 static private final int STATE_GROUP_OR_PROPERTY_NAME = 0; 359 static private final int STATE_PARAMS = 1; 360 // vCard 3.0 specification allows double-quoted parameters, while vCard 2.1 does not. 361 static private final int STATE_PARAMS_IN_DQUOTE = 2; 362 363 protected VCardProperty constructPropertyData(String line) throws VCardException { 364 final VCardProperty propertyData = new VCardProperty(); 365 366 final int length = line.length(); 367 if (length > 0 && line.charAt(0) == '#') { 368 throw new VCardInvalidCommentLineException(); 369 } 370 371 int state = STATE_GROUP_OR_PROPERTY_NAME; 372 int nameIndex = 0; 373 374 // This loop is developed so that we don't have to take care of bottle neck here. 375 // Refactor carefully when you need to do so. 376 for (int i = 0; i < length; i++) { 377 final char ch = line.charAt(i); 378 switch (state) { 379 case STATE_GROUP_OR_PROPERTY_NAME: { 380 if (ch == ':') { // End of a property name. 381 final String propertyName = line.substring(nameIndex, i); 382 propertyData.setName(propertyName); 383 propertyData.setRawValue( i < length - 1 ? line.substring(i + 1) : ""); 384 return propertyData; 385 } else if (ch == '.') { // Each group is followed by the dot. 386 final String groupName = line.substring(nameIndex, i); 387 if (groupName.length() == 0) { 388 Log.w(LOG_TAG, "Empty group found. Ignoring."); 389 } else { 390 propertyData.addGroup(groupName); 391 } 392 nameIndex = i + 1; // Next should be another group or a property name. 393 } else if (ch == ';') { // End of property name and beginneng of parameters. 394 final String propertyName = line.substring(nameIndex, i); 395 propertyData.setName(propertyName); 396 nameIndex = i + 1; 397 state = STATE_PARAMS; // Start parameter parsing. 398 } 399 // TODO: comma support (in vCard 3.0 and 4.0). 400 break; 401 } 402 case STATE_PARAMS: { 403 if (ch == '"') { 404 if (VCardConstants.VERSION_V21.equalsIgnoreCase(getVersionString())) { 405 Log.w(LOG_TAG, "Double-quoted params found in vCard 2.1. " + 406 "Silently allow it"); 407 } 408 state = STATE_PARAMS_IN_DQUOTE; 409 } else if (ch == ';') { // Starts another param. 410 handleParams(propertyData, line.substring(nameIndex, i)); 411 nameIndex = i + 1; 412 } else if (ch == ':') { // End of param and beginenning of values. 413 handleParams(propertyData, line.substring(nameIndex, i)); 414 propertyData.setRawValue(i < length - 1 ? line.substring(i + 1) : ""); 415 return propertyData; 416 } 417 break; 418 } 419 case STATE_PARAMS_IN_DQUOTE: { 420 if (ch == '"') { 421 if (VCardConstants.VERSION_V21.equalsIgnoreCase(getVersionString())) { 422 Log.w(LOG_TAG, "Double-quoted params found in vCard 2.1. " + 423 "Silently allow it"); 424 } 425 state = STATE_PARAMS; 426 } 427 break; 428 } 429 } 430 } 431 432 throw new VCardInvalidLineException("Invalid line: \"" + line + "\""); 433 } 434 435 /* 436 * params = ";" [ws] paramlist paramlist = paramlist [ws] ";" [ws] param / 437 * param param = "TYPE" [ws] "=" [ws] ptypeval / "VALUE" [ws] "=" [ws] 438 * pvalueval / "ENCODING" [ws] "=" [ws] pencodingval / "CHARSET" [ws] "=" 439 * [ws] charsetval / "LANGUAGE" [ws] "=" [ws] langval / "X-" word [ws] "=" 440 * [ws] word / knowntype 441 */ 442 protected void handleParams(VCardProperty propertyData, String params) 443 throws VCardException { 444 final String[] strArray = params.split("=", 2); 445 if (strArray.length == 2) { 446 final String paramName = strArray[0].trim().toUpperCase(); 447 String paramValue = strArray[1].trim(); 448 if (paramName.equals("TYPE")) { 449 handleType(propertyData, paramValue); 450 } else if (paramName.equals("VALUE")) { 451 handleValue(propertyData, paramValue); 452 } else if (paramName.equals("ENCODING")) { 453 handleEncoding(propertyData, paramValue); 454 } else if (paramName.equals("CHARSET")) { 455 handleCharset(propertyData, paramValue); 456 } else if (paramName.equals("LANGUAGE")) { 457 handleLanguage(propertyData, paramValue); 458 } else if (paramName.startsWith("X-")) { 459 handleAnyParam(propertyData, paramName, paramValue); 460 } else { 461 throw new VCardException("Unknown type \"" + paramName + "\""); 462 } 463 } else { 464 handleParamWithoutName(propertyData, strArray[0]); 465 } 466 } 467 468 /** 469 * vCard 3.0 parser implementation may throw VCardException. 470 */ 471 protected void handleParamWithoutName(VCardProperty propertyData, final String paramValue) { 472 handleType(propertyData, paramValue); 473 } 474 475 /* 476 * ptypeval = knowntype / "X-" word 477 */ 478 protected void handleType(VCardProperty propertyData, final String ptypeval) { 479 if (!(getKnownTypeSet().contains(ptypeval.toUpperCase()) 480 || ptypeval.startsWith("X-")) 481 && !mUnknownTypeSet.contains(ptypeval)) { 482 mUnknownTypeSet.add(ptypeval); 483 Log.w(LOG_TAG, String.format("TYPE unsupported by %s: ", getVersion(), ptypeval)); 484 } 485 propertyData.addParameter(VCardConstants.PARAM_TYPE, ptypeval); 486 } 487 488 /* 489 * pvalueval = "INLINE" / "URL" / "CONTENT-ID" / "CID" / "X-" word 490 */ 491 protected void handleValue(VCardProperty propertyData, final String pvalueval) { 492 if (!(getKnownValueSet().contains(pvalueval.toUpperCase()) 493 || pvalueval.startsWith("X-") 494 || mUnknownValueSet.contains(pvalueval))) { 495 mUnknownValueSet.add(pvalueval); 496 Log.w(LOG_TAG, String.format( 497 "The value unsupported by TYPE of %s: ", getVersion(), pvalueval)); 498 } 499 propertyData.addParameter(VCardConstants.PARAM_VALUE, pvalueval); 500 } 501 502 /* 503 * pencodingval = "7BIT" / "8BIT" / "QUOTED-PRINTABLE" / "BASE64" / "X-" word 504 */ 505 protected void handleEncoding(VCardProperty propertyData, String pencodingval) 506 throws VCardException { 507 if (getAvailableEncodingSet().contains(pencodingval) || 508 pencodingval.startsWith("X-")) { 509 propertyData.addParameter(VCardConstants.PARAM_ENCODING, pencodingval); 510 // Update encoding right away, as this is needed to understanding other params. 511 mCurrentEncoding = pencodingval; 512 } else { 513 throw new VCardException("Unknown encoding \"" + pencodingval + "\""); 514 } 515 } 516 517 /** 518 * <p> 519 * vCard 2.1 specification only allows us-ascii and iso-8859-xxx (See RFC 1521), 520 * but recent vCard files often contain other charset like UTF-8, SHIFT_JIS, etc. 521 * We allow any charset. 522 * </p> 523 */ 524 protected void handleCharset(VCardProperty propertyData, String charsetval) { 525 mCurrentCharset = charsetval; 526 propertyData.addParameter(VCardConstants.PARAM_CHARSET, charsetval); 527 } 528 529 /** 530 * See also Section 7.1 of RFC 1521 531 */ 532 protected void handleLanguage(VCardProperty propertyData, String langval) 533 throws VCardException { 534 String[] strArray = langval.split("-"); 535 if (strArray.length != 2) { 536 throw new VCardException("Invalid Language: \"" + langval + "\""); 537 } 538 String tmp = strArray[0]; 539 int length = tmp.length(); 540 for (int i = 0; i < length; i++) { 541 if (!isAsciiLetter(tmp.charAt(i))) { 542 throw new VCardException("Invalid Language: \"" + langval + "\""); 543 } 544 } 545 tmp = strArray[1]; 546 length = tmp.length(); 547 for (int i = 0; i < length; i++) { 548 if (!isAsciiLetter(tmp.charAt(i))) { 549 throw new VCardException("Invalid Language: \"" + langval + "\""); 550 } 551 } 552 propertyData.addParameter(VCardConstants.PARAM_LANGUAGE, langval); 553 } 554 555 private boolean isAsciiLetter(char ch) { 556 if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) { 557 return true; 558 } 559 return false; 560 } 561 562 /** 563 * Mainly for "X-" type. This accepts any kind of type without check. 564 */ 565 protected void handleAnyParam( 566 VCardProperty propertyData, String paramName, String paramValue) { 567 propertyData.addParameter(paramName, paramValue); 568 } 569 570 protected void handlePropertyValue(VCardProperty property, String propertyName) 571 throws IOException, VCardException { 572 final String propertyNameUpper = property.getName().toUpperCase(); 573 String propertyRawValue = property.getRawValue(); 574 final String sourceCharset = VCardConfig.DEFAULT_INTERMEDIATE_CHARSET; 575 final Collection<String> charsetCollection = 576 property.getParameters(VCardConstants.PARAM_CHARSET); 577 String targetCharset = 578 ((charsetCollection != null) ? charsetCollection.iterator().next() : null); 579 if (TextUtils.isEmpty(targetCharset)) { 580 targetCharset = VCardConfig.DEFAULT_IMPORT_CHARSET; 581 } 582 583 // TODO: have "separableProperty" which reflects vCard spec.. 584 if (propertyNameUpper.equals(VCardConstants.PROPERTY_ADR) 585 || propertyNameUpper.equals(VCardConstants.PROPERTY_ORG) 586 || propertyNameUpper.equals(VCardConstants.PROPERTY_N)) { 587 handleAdrOrgN(property, propertyRawValue, sourceCharset, targetCharset); 588 return; 589 } 590 591 final String upperEncoding = mCurrentEncoding.toUpperCase(); 592 if (upperEncoding.equals(VCardConstants.PARAM_ENCODING_QP)) { 593 final String quotedPrintablePart = getQuotedPrintablePart(propertyRawValue); 594 final String propertyEncodedValue = 595 VCardUtils.parseQuotedPrintable(quotedPrintablePart, 596 false, sourceCharset, targetCharset); 597 property.setRawValue(quotedPrintablePart); 598 property.setValues(propertyEncodedValue); 599 for (VCardInterpreter interpreter : mInterpreterList) { 600 interpreter.onPropertyCreated(property); 601 } 602 } else if (upperEncoding.equals(VCardConstants.PARAM_ENCODING_BASE64) 603 || upperEncoding.equals(VCardConstants.PARAM_ENCODING_B)) { 604 // It is very rare, but some BASE64 data may be so big that 605 // OutOfMemoryError occurs. To ignore such cases, use try-catch. 606 try { 607 final String base64Property = getBase64(propertyRawValue); 608 try { 609 property.setByteValue(Base64.decode(base64Property, Base64.DEFAULT)); 610 } catch (IllegalArgumentException e) { 611 throw new VCardException("Decode error on base64 photo: " + propertyRawValue); 612 } 613 for (VCardInterpreter interpreter : mInterpreterList) { 614 interpreter.onPropertyCreated(property); 615 } 616 } catch (OutOfMemoryError error) { 617 Log.e(LOG_TAG, "OutOfMemoryError happened during parsing BASE64 data!"); 618 for (VCardInterpreter interpreter : mInterpreterList) { 619 interpreter.onPropertyCreated(property); 620 } 621 } 622 } else { 623 if (!(upperEncoding.equals("7BIT") || upperEncoding.equals("8BIT") || 624 upperEncoding.startsWith("X-"))) { 625 Log.w(LOG_TAG, 626 String.format("The encoding \"%s\" is unsupported by vCard %s", 627 mCurrentEncoding, getVersionString())); 628 } 629 630 // Some device uses line folding defined in RFC 2425, which is not allowed 631 // in vCard 2.1 (while needed in vCard 3.0). 632 // 633 // e.g. 634 // BEGIN:VCARD 635 // VERSION:2.1 636 // N:;Omega;;; 637 // EMAIL;INTERNET:"Omega" 638 // <omega@example.com> 639 // FN:Omega 640 // END:VCARD 641 // 642 // The vCard above assumes that email address should become: 643 // "Omega" <omega@example.com> 644 // 645 // But vCard 2.1 requires Quote-Printable when a line contains line break(s). 646 // 647 // For more information about line folding, 648 // see "5.8.1. Line delimiting and folding" in RFC 2425. 649 // 650 // We take care of this case more formally in vCard 3.0, so we only need to 651 // do this in vCard 2.1. 652 if (getVersion() == VCardConfig.VERSION_21) { 653 StringBuilder builder = null; 654 while (true) { 655 final String nextLine = peekLine(); 656 // We don't need to care too much about this exceptional case, 657 // but we should not wrongly eat up "END:VCARD", since it critically 658 // breaks this parser's state machine. 659 // Thus we roughly look over the next line and confirm it is at least not 660 // "END:VCARD". This extra fee is worth paying. This is exceptional 661 // anyway. 662 if (!TextUtils.isEmpty(nextLine) && 663 nextLine.charAt(0) == ' ' && 664 !"END:VCARD".contains(nextLine.toUpperCase())) { 665 getLine(); // Drop the next line. 666 667 if (builder == null) { 668 builder = new StringBuilder(); 669 builder.append(propertyRawValue); 670 } 671 builder.append(nextLine.substring(1)); 672 } else { 673 break; 674 } 675 } 676 if (builder != null) { 677 propertyRawValue = builder.toString(); 678 } 679 } 680 681 ArrayList<String> propertyValueList = new ArrayList<String>(); 682 String value = VCardUtils.convertStringCharset( 683 maybeUnescapeText(propertyRawValue), sourceCharset, targetCharset); 684 propertyValueList.add(value); 685 property.setValues(propertyValueList); 686 for (VCardInterpreter interpreter : mInterpreterList) { 687 interpreter.onPropertyCreated(property); 688 } 689 } 690 } 691 692 private void handleAdrOrgN(VCardProperty property, String propertyRawValue, 693 String sourceCharset, String targetCharset) throws VCardException, IOException { 694 List<String> encodedValueList = new ArrayList<String>(); 695 696 // vCard 2.1 does not allow QUOTED-PRINTABLE here, but some softwares/devices emit 697 // such data. 698 if (mCurrentEncoding.equalsIgnoreCase(VCardConstants.PARAM_ENCODING_QP)) { 699 // First we retrieve Quoted-Printable String from vCard entry, which may include 700 // multiple lines. 701 final String quotedPrintablePart = getQuotedPrintablePart(propertyRawValue); 702 703 // "Raw value" from the view of users should contain all part of QP string. 704 // TODO: add test for this handling 705 property.setRawValue(quotedPrintablePart); 706 707 // We split Quoted-Printable String using semi-colon before decoding it, as 708 // the Quoted-Printable may have semi-colon, which confuses splitter. 709 final List<String> quotedPrintableValueList = 710 VCardUtils.constructListFromValue(quotedPrintablePart, getVersion()); 711 for (String quotedPrintableValue : quotedPrintableValueList) { 712 String encoded = VCardUtils.parseQuotedPrintable(quotedPrintableValue, 713 false, sourceCharset, targetCharset); 714 encodedValueList.add(encoded); 715 } 716 } else { 717 final String propertyValue = getPotentialMultiline(propertyRawValue); 718 final List<String> rawValueList = 719 VCardUtils.constructListFromValue(propertyValue, getVersion()); 720 for (String rawValue : rawValueList) { 721 encodedValueList.add(VCardUtils.convertStringCharset( 722 rawValue, sourceCharset, targetCharset)); 723 } 724 } 725 726 property.setValues(encodedValueList); 727 for (VCardInterpreter interpreter : mInterpreterList) { 728 interpreter.onPropertyCreated(property); 729 } 730 } 731 732 /** 733 * <p> 734 * Parses and returns Quoted-Printable. 735 * </p> 736 * 737 * @param firstString The string following a parameter name and attributes. 738 * Example: "string" in 739 * "ADR:ENCODING=QUOTED-PRINTABLE:string\n\r". 740 * @return whole Quoted-Printable string, including a given argument and 741 * following lines. Excludes the last empty line following to Quoted 742 * Printable lines. 743 * @throws IOException 744 * @throws VCardException 745 */ 746 private String getQuotedPrintablePart(String firstString) 747 throws IOException, VCardException { 748 // Specifically, there may be some padding between = and CRLF. 749 // See the following: 750 // 751 // qp-line := *(qp-segment transport-padding CRLF) 752 // qp-part transport-padding 753 // qp-segment := qp-section *(SPACE / TAB) "=" 754 // ; Maximum length of 76 characters 755 // 756 // e.g. (from RFC 2045) 757 // Now's the time = 758 // for all folk to come= 759 // to the aid of their country. 760 if (firstString.trim().endsWith("=")) { 761 // remove "transport-padding" 762 int pos = firstString.length() - 1; 763 while (firstString.charAt(pos) != '=') { 764 } 765 StringBuilder builder = new StringBuilder(); 766 builder.append(firstString.substring(0, pos + 1)); 767 builder.append("\r\n"); 768 String line; 769 while (true) { 770 line = getLine(); 771 if (line == null) { 772 throw new VCardException("File ended during parsing a Quoted-Printable String"); 773 } 774 if (line.trim().endsWith("=")) { 775 // remove "transport-padding" 776 pos = line.length() - 1; 777 while (line.charAt(pos) != '=') { 778 } 779 builder.append(line.substring(0, pos + 1)); 780 builder.append("\r\n"); 781 } else { 782 builder.append(line); 783 break; 784 } 785 } 786 return builder.toString(); 787 } else { 788 return firstString; 789 } 790 } 791 792 /** 793 * Given the first line of a property, checks consecutive lines after it and builds a new 794 * multi-line value if it exists. 795 * 796 * @param firstString The first line of the property. 797 * @return A new property, potentially built from multiple lines. 798 * @throws IOException 799 */ 800 private String getPotentialMultiline(String firstString) throws IOException { 801 final StringBuilder builder = new StringBuilder(); 802 builder.append(firstString); 803 804 while (true) { 805 final String line = peekLine(); 806 if (line == null || line.length() == 0) { 807 break; 808 } 809 810 final String propertyName = getPropertyNameUpperCase(line); 811 if (propertyName != null) { 812 break; 813 } 814 815 // vCard 2.1 does not allow multi-line of adr but microsoft vcards may have it. 816 // We will consider the next line to be a part of a multi-line value if it does not 817 // contain a property name (i.e. a colon or semi-colon). 818 // Consume the line. 819 getLine(); 820 builder.append(" ").append(line); 821 } 822 823 return builder.toString(); 824 } 825 826 protected String getBase64(String firstString) throws IOException, VCardException { 827 final StringBuilder builder = new StringBuilder(); 828 builder.append(firstString); 829 830 while (true) { 831 final String line = peekLine(); 832 if (line == null) { 833 throw new VCardException("File ended during parsing BASE64 binary"); 834 } 835 836 // vCard 2.1 requires two spaces at the end of BASE64 strings, but some vCard doesn't 837 // have them. We try to detect those cases using colon and semi-colon, given BASE64 838 // does not contain it. 839 // E.g. 840 // TEL;TYPE=WORK:+5555555 841 // or 842 // END:VCARD 843 String propertyName = getPropertyNameUpperCase(line); 844 if (getKnownPropertyNameSet().contains(propertyName)) { 845 Log.w(LOG_TAG, "Found a next property during parsing a BASE64 string, " + 846 "which must not contain semi-colon or colon. Treat the line as next " 847 + "property."); 848 Log.w(LOG_TAG, "Problematic line: " + line.trim()); 849 break; 850 } 851 852 // Consume the line. 853 getLine(); 854 855 if (line.length() == 0) { 856 break; 857 } 858 builder.append(line); 859 } 860 861 return builder.toString(); 862 } 863 864 /** 865 * Extracts the property name portion of a given vCard line. 866 * <p> 867 * Properties must contain a colon. 868 * <p> 869 * E.g. 870 * TEL;TYPE=WORK:+5555555 // returns "TEL" 871 * END:VCARD // returns "END" 872 * TEL; // returns null 873 * 874 * @param line The vCard line. 875 * @return The property name portion. {@literal null} if no property name found. 876 */ 877 private String getPropertyNameUpperCase(String line) { 878 final int colonIndex = line.indexOf(":"); 879 if (colonIndex > -1) { 880 final int semiColonIndex = line.indexOf(";"); 881 882 // Find the minimum index that is greater than -1. 883 final int minIndex; 884 if (colonIndex == -1) { 885 minIndex = semiColonIndex; 886 } else if (semiColonIndex == -1) { 887 minIndex = colonIndex; 888 } else { 889 minIndex = Math.min(colonIndex, semiColonIndex); 890 } 891 return line.substring(0, minIndex).toUpperCase(); 892 } 893 return null; 894 } 895 896 /* 897 * vCard 2.1 specifies AGENT allows one vcard entry. Currently we emit an 898 * error toward the AGENT property. 899 * // TODO: Support AGENT property. 900 * item = 901 * ... / [groups "."] "AGENT" [params] ":" vcard CRLF vcard = "BEGIN" [ws] 902 * ":" [ws] "VCARD" [ws] 1*CRLF items *CRLF "END" [ws] ":" [ws] "VCARD" 903 */ 904 protected void handleAgent(final VCardProperty property) throws VCardException { 905 if (!property.getRawValue().toUpperCase().contains("BEGIN:VCARD")) { 906 // Apparently invalid line seen in Windows Mobile 6.5. Ignore them. 907 for (VCardInterpreter interpreter : mInterpreterList) { 908 interpreter.onPropertyCreated(property); 909 } 910 return; 911 } else { 912 throw new VCardAgentNotSupportedException("AGENT Property is not supported now."); 913 } 914 } 915 916 /** 917 * For vCard 3.0. 918 */ 919 protected String maybeUnescapeText(final String text) { 920 return text; 921 } 922 923 /** 924 * Returns unescaped String if the character should be unescaped. Return 925 * null otherwise. e.g. In vCard 2.1, "\;" should be unescaped into ";" 926 * while "\x" should not be. 927 */ 928 protected String maybeUnescapeCharacter(final char ch) { 929 return unescapeCharacter(ch); 930 } 931 932 /* package */ static String unescapeCharacter(final char ch) { 933 // Original vCard 2.1 specification does not allow transformation 934 // "\:" -> ":", "\," -> ",", and "\\" -> "\", but previous 935 // implementation of 936 // this class allowed them, so keep it as is. 937 if (ch == '\\' || ch == ';' || ch == ':' || ch == ',') { 938 return String.valueOf(ch); 939 } else { 940 return null; 941 } 942 } 943 944 /** 945 * @return {@link VCardConfig#VERSION_21} 946 */ 947 protected int getVersion() { 948 return VCardConfig.VERSION_21; 949 } 950 951 /** 952 * @return {@link VCardConfig#VERSION_30} 953 */ 954 protected String getVersionString() { 955 return VCardConstants.VERSION_V21; 956 } 957 958 protected Set<String> getKnownPropertyNameSet() { 959 return VCardParser_V21.sKnownPropertyNameSet; 960 } 961 962 protected Set<String> getKnownTypeSet() { 963 return VCardParser_V21.sKnownTypeSet; 964 } 965 966 protected Set<String> getKnownValueSet() { 967 return VCardParser_V21.sKnownValueSet; 968 } 969 970 protected Set<String> getAvailableEncodingSet() { 971 return VCardParser_V21.sAvailableEncoding; 972 } 973 974 protected String getDefaultEncoding() { 975 return DEFAULT_ENCODING; 976 } 977 978 protected String getDefaultCharset() { 979 return DEFAULT_CHARSET; 980 } 981 982 protected String getCurrentCharset() { 983 return mCurrentCharset; 984 } 985 986 public void addInterpreter(VCardInterpreter interpreter) { 987 mInterpreterList.add(interpreter); 988 } 989 990 public void parse(InputStream is) throws IOException, VCardException { 991 if (is == null) { 992 throw new NullPointerException("InputStream must not be null."); 993 } 994 995 final InputStreamReader tmpReader = new InputStreamReader(is, mIntermediateCharset); 996 mReader = new CustomBufferedReader(tmpReader); 997 998 final long start = System.currentTimeMillis(); 999 for (VCardInterpreter interpreter : mInterpreterList) { 1000 interpreter.onVCardStarted(); 1001 } 1002 1003 // vcard_file = [wsls] vcard [wsls] 1004 while (true) { 1005 synchronized (this) { 1006 if (mCanceled) { 1007 Log.i(LOG_TAG, "Cancel request has come. exitting parse operation."); 1008 break; 1009 } 1010 } 1011 if (!parseOneVCard()) { 1012 break; 1013 } 1014 } 1015 1016 for (VCardInterpreter interpreter : mInterpreterList) { 1017 interpreter.onVCardEnded(); 1018 } 1019 } 1020 1021 public void parseOne(InputStream is) throws IOException, VCardException { 1022 if (is == null) { 1023 throw new NullPointerException("InputStream must not be null."); 1024 } 1025 1026 final InputStreamReader tmpReader = new InputStreamReader(is, mIntermediateCharset); 1027 mReader = new CustomBufferedReader(tmpReader); 1028 1029 final long start = System.currentTimeMillis(); 1030 for (VCardInterpreter interpreter : mInterpreterList) { 1031 interpreter.onVCardStarted(); 1032 } 1033 parseOneVCard(); 1034 for (VCardInterpreter interpreter : mInterpreterList) { 1035 interpreter.onVCardEnded(); 1036 } 1037 } 1038 1039 public final synchronized void cancel() { 1040 Log.i(LOG_TAG, "ParserImpl received cancel operation."); 1041 mCanceled = true; 1042 } 1043} 1044