VCardUtils.java revision 58ca5f9943bb5c8aeeab3150ac96f1143dfd86ba
1/* 2 * Copyright (C) 2009 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 com.android.vcard.exception.VCardException; 19 20import org.apache.commons.codec.DecoderException; 21import org.apache.commons.codec.net.QuotedPrintableCodec; 22 23import android.content.ContentProviderOperation; 24import android.provider.ContactsContract.Data; 25import android.provider.ContactsContract.CommonDataKinds.Im; 26import android.provider.ContactsContract.CommonDataKinds.Phone; 27import android.provider.ContactsContract.CommonDataKinds.StructuredPostal; 28import android.telephony.PhoneNumberUtils; 29import android.text.TextUtils; 30import android.util.Log; 31 32import java.io.UnsupportedEncodingException; 33import java.nio.ByteBuffer; 34import java.nio.charset.Charset; 35import java.util.ArrayList; 36import java.util.Arrays; 37import java.util.Collection; 38import java.util.HashMap; 39import java.util.HashSet; 40import java.util.List; 41import java.util.Map; 42import java.util.Set; 43 44/** 45 * Utilities for VCard handling codes. 46 */ 47public class VCardUtils { 48 private static final String LOG_TAG = "VCardUtils"; 49 50 // Note that not all types are included in this map/set, since, for example, TYPE_HOME_FAX is 51 // converted to two parameter Strings. These only contain some minor fields valid in both 52 // vCard and current (as of 2009-08-07) Contacts structure. 53 private static final Map<Integer, String> sKnownPhoneTypesMap_ItoS; 54 private static final Set<String> sPhoneTypesUnknownToContactsSet; 55 private static final Map<String, Integer> sKnownPhoneTypeMap_StoI; 56 private static final Map<Integer, String> sKnownImPropNameMap_ItoS; 57 private static final Set<String> sMobilePhoneLabelSet; 58 59 static { 60 sKnownPhoneTypesMap_ItoS = new HashMap<Integer, String>(); 61 sKnownPhoneTypeMap_StoI = new HashMap<String, Integer>(); 62 63 sKnownPhoneTypesMap_ItoS.put(Phone.TYPE_CAR, VCardConstants.PARAM_TYPE_CAR); 64 sKnownPhoneTypeMap_StoI.put(VCardConstants.PARAM_TYPE_CAR, Phone.TYPE_CAR); 65 sKnownPhoneTypesMap_ItoS.put(Phone.TYPE_PAGER, VCardConstants.PARAM_TYPE_PAGER); 66 sKnownPhoneTypeMap_StoI.put(VCardConstants.PARAM_TYPE_PAGER, Phone.TYPE_PAGER); 67 sKnownPhoneTypesMap_ItoS.put(Phone.TYPE_ISDN, VCardConstants.PARAM_TYPE_ISDN); 68 sKnownPhoneTypeMap_StoI.put(VCardConstants.PARAM_TYPE_ISDN, Phone.TYPE_ISDN); 69 70 sKnownPhoneTypeMap_StoI.put(VCardConstants.PARAM_TYPE_HOME, Phone.TYPE_HOME); 71 sKnownPhoneTypeMap_StoI.put(VCardConstants.PARAM_TYPE_WORK, Phone.TYPE_WORK); 72 sKnownPhoneTypeMap_StoI.put(VCardConstants.PARAM_TYPE_CELL, Phone.TYPE_MOBILE); 73 74 sKnownPhoneTypeMap_StoI.put(VCardConstants.PARAM_PHONE_EXTRA_TYPE_OTHER, Phone.TYPE_OTHER); 75 sKnownPhoneTypeMap_StoI.put(VCardConstants.PARAM_PHONE_EXTRA_TYPE_CALLBACK, 76 Phone.TYPE_CALLBACK); 77 sKnownPhoneTypeMap_StoI.put( 78 VCardConstants.PARAM_PHONE_EXTRA_TYPE_COMPANY_MAIN, Phone.TYPE_COMPANY_MAIN); 79 sKnownPhoneTypeMap_StoI.put(VCardConstants.PARAM_PHONE_EXTRA_TYPE_RADIO, Phone.TYPE_RADIO); 80 sKnownPhoneTypeMap_StoI.put(VCardConstants.PARAM_PHONE_EXTRA_TYPE_TTY_TDD, 81 Phone.TYPE_TTY_TDD); 82 sKnownPhoneTypeMap_StoI.put(VCardConstants.PARAM_PHONE_EXTRA_TYPE_ASSISTANT, 83 Phone.TYPE_ASSISTANT); 84 85 sPhoneTypesUnknownToContactsSet = new HashSet<String>(); 86 sPhoneTypesUnknownToContactsSet.add(VCardConstants.PARAM_TYPE_MODEM); 87 sPhoneTypesUnknownToContactsSet.add(VCardConstants.PARAM_TYPE_MSG); 88 sPhoneTypesUnknownToContactsSet.add(VCardConstants.PARAM_TYPE_BBS); 89 sPhoneTypesUnknownToContactsSet.add(VCardConstants.PARAM_TYPE_VIDEO); 90 91 sKnownImPropNameMap_ItoS = new HashMap<Integer, String>(); 92 sKnownImPropNameMap_ItoS.put(Im.PROTOCOL_AIM, VCardConstants.PROPERTY_X_AIM); 93 sKnownImPropNameMap_ItoS.put(Im.PROTOCOL_MSN, VCardConstants.PROPERTY_X_MSN); 94 sKnownImPropNameMap_ItoS.put(Im.PROTOCOL_YAHOO, VCardConstants.PROPERTY_X_YAHOO); 95 sKnownImPropNameMap_ItoS.put(Im.PROTOCOL_SKYPE, VCardConstants.PROPERTY_X_SKYPE_USERNAME); 96 sKnownImPropNameMap_ItoS.put(Im.PROTOCOL_GOOGLE_TALK, 97 VCardConstants.PROPERTY_X_GOOGLE_TALK); 98 sKnownImPropNameMap_ItoS.put(Im.PROTOCOL_ICQ, VCardConstants.PROPERTY_X_ICQ); 99 sKnownImPropNameMap_ItoS.put(Im.PROTOCOL_JABBER, VCardConstants.PROPERTY_X_JABBER); 100 sKnownImPropNameMap_ItoS.put(Im.PROTOCOL_QQ, VCardConstants.PROPERTY_X_QQ); 101 sKnownImPropNameMap_ItoS.put(Im.PROTOCOL_NETMEETING, VCardConstants.PROPERTY_X_NETMEETING); 102 103 // \u643A\u5E2F\u96FB\u8A71 = Full-width Hiragana "Keitai-Denwa" (mobile phone) 104 // \u643A\u5E2F = Full-width Hiragana "Keitai" (mobile phone) 105 // \u30B1\u30A4\u30BF\u30A4 = Full-width Katakana "Keitai" (mobile phone) 106 // \uFF79\uFF72\uFF80\uFF72 = Half-width Katakana "Keitai" (mobile phone) 107 sMobilePhoneLabelSet = new HashSet<String>(Arrays.asList( 108 "MOBILE", "\u643A\u5E2F\u96FB\u8A71", "\u643A\u5E2F", "\u30B1\u30A4\u30BF\u30A4", 109 "\uFF79\uFF72\uFF80\uFF72")); 110 } 111 112 public static String getPhoneTypeString(Integer type) { 113 return sKnownPhoneTypesMap_ItoS.get(type); 114 } 115 116 /** 117 * Returns Interger when the given types can be parsed as known type. Returns String object 118 * when not, which should be set to label. 119 */ 120 public static Object getPhoneTypeFromStrings(Collection<String> types, 121 String number) { 122 if (number == null) { 123 number = ""; 124 } 125 int type = -1; 126 String label = null; 127 boolean isFax = false; 128 boolean hasPref = false; 129 130 if (types != null) { 131 for (String typeString : types) { 132 if (typeString == null) { 133 continue; 134 } 135 typeString = typeString.toUpperCase(); 136 if (typeString.equals(VCardConstants.PARAM_TYPE_PREF)) { 137 hasPref = true; 138 } else if (typeString.equals(VCardConstants.PARAM_TYPE_FAX)) { 139 isFax = true; 140 } else { 141 if (typeString.startsWith("X-") && type < 0) { 142 typeString = typeString.substring(2); 143 } 144 if (typeString.length() == 0) { 145 continue; 146 } 147 final Integer tmp = sKnownPhoneTypeMap_StoI.get(typeString); 148 if (tmp != null) { 149 final int typeCandidate = tmp; 150 // TYPE_PAGER is prefered when the number contains @ surronded by 151 // a pager number and a domain name. 152 // e.g. 153 // o 1111@domain.com 154 // x @domain.com 155 // x 1111@ 156 final int indexOfAt = number.indexOf("@"); 157 if ((typeCandidate == Phone.TYPE_PAGER 158 && 0 < indexOfAt && indexOfAt < number.length() - 1) 159 || type < 0 160 || type == Phone.TYPE_CUSTOM) { 161 type = tmp; 162 } 163 } else if (type < 0) { 164 type = Phone.TYPE_CUSTOM; 165 label = typeString; 166 } 167 } 168 } 169 } 170 if (type < 0) { 171 if (hasPref) { 172 type = Phone.TYPE_MAIN; 173 } else { 174 // default to TYPE_HOME 175 type = Phone.TYPE_HOME; 176 } 177 } 178 if (isFax) { 179 if (type == Phone.TYPE_HOME) { 180 type = Phone.TYPE_FAX_HOME; 181 } else if (type == Phone.TYPE_WORK) { 182 type = Phone.TYPE_FAX_WORK; 183 } else if (type == Phone.TYPE_OTHER) { 184 type = Phone.TYPE_OTHER_FAX; 185 } 186 } 187 if (type == Phone.TYPE_CUSTOM) { 188 return label; 189 } else { 190 return type; 191 } 192 } 193 194 @SuppressWarnings("deprecation") 195 public static boolean isMobilePhoneLabel(final String label) { 196 // For backward compatibility. 197 // Detail: Until Donut, there isn't TYPE_MOBILE for email while there is now. 198 // To support mobile type at that time, this custom label had been used. 199 return ("_AUTO_CELL".equals(label) || sMobilePhoneLabelSet.contains(label)); 200 } 201 202 public static boolean isValidInV21ButUnknownToContactsPhoteType(final String label) { 203 return sPhoneTypesUnknownToContactsSet.contains(label); 204 } 205 206 public static String getPropertyNameForIm(final int protocol) { 207 return sKnownImPropNameMap_ItoS.get(protocol); 208 } 209 210 public static String[] sortNameElements(final int vcardType, 211 final String familyName, final String middleName, final String givenName) { 212 final String[] list = new String[3]; 213 final int nameOrderType = VCardConfig.getNameOrderType(vcardType); 214 switch (nameOrderType) { 215 case VCardConfig.NAME_ORDER_JAPANESE: { 216 if (containsOnlyPrintableAscii(familyName) && 217 containsOnlyPrintableAscii(givenName)) { 218 list[0] = givenName; 219 list[1] = middleName; 220 list[2] = familyName; 221 } else { 222 list[0] = familyName; 223 list[1] = middleName; 224 list[2] = givenName; 225 } 226 break; 227 } 228 case VCardConfig.NAME_ORDER_EUROPE: { 229 list[0] = middleName; 230 list[1] = givenName; 231 list[2] = familyName; 232 break; 233 } 234 default: { 235 list[0] = givenName; 236 list[1] = middleName; 237 list[2] = familyName; 238 break; 239 } 240 } 241 return list; 242 } 243 244 public static int getPhoneNumberFormat(final int vcardType) { 245 if (VCardConfig.isJapaneseDevice(vcardType)) { 246 return PhoneNumberUtils.FORMAT_JAPAN; 247 } else { 248 return PhoneNumberUtils.FORMAT_NANP; 249 } 250 } 251 252 /** 253 * <p> 254 * Inserts postal data into the builder object. 255 * </p> 256 * <p> 257 * Note that the data structure of ContactsContract is different from that defined in vCard. 258 * So some conversion may be performed in this method. 259 * </p> 260 */ 261 public static void insertStructuredPostalDataUsingContactsStruct(int vcardType, 262 final ContentProviderOperation.Builder builder, 263 final VCardEntry.PostalData postalData) { 264 builder.withValueBackReference(StructuredPostal.RAW_CONTACT_ID, 0); 265 builder.withValue(Data.MIMETYPE, StructuredPostal.CONTENT_ITEM_TYPE); 266 267 builder.withValue(StructuredPostal.TYPE, postalData.type); 268 if (postalData.type == StructuredPostal.TYPE_CUSTOM) { 269 builder.withValue(StructuredPostal.LABEL, postalData.label); 270 } 271 272 final String streetString; 273 if (TextUtils.isEmpty(postalData.street)) { 274 if (TextUtils.isEmpty(postalData.extendedAddress)) { 275 streetString = null; 276 } else { 277 streetString = postalData.extendedAddress; 278 } 279 } else { 280 if (TextUtils.isEmpty(postalData.extendedAddress)) { 281 streetString = postalData.street; 282 } else { 283 streetString = postalData.street + " " + postalData.extendedAddress; 284 } 285 } 286 builder.withValue(StructuredPostal.POBOX, postalData.pobox); 287 builder.withValue(StructuredPostal.STREET, streetString); 288 builder.withValue(StructuredPostal.CITY, postalData.localty); 289 builder.withValue(StructuredPostal.REGION, postalData.region); 290 builder.withValue(StructuredPostal.POSTCODE, postalData.postalCode); 291 builder.withValue(StructuredPostal.COUNTRY, postalData.country); 292 293 builder.withValue(StructuredPostal.FORMATTED_ADDRESS, 294 postalData.getFormattedAddress(vcardType)); 295 if (postalData.isPrimary) { 296 builder.withValue(Data.IS_PRIMARY, 1); 297 } 298 } 299 300 public static String constructNameFromElements(final int vcardType, 301 final String familyName, final String middleName, final String givenName) { 302 return constructNameFromElements(vcardType, familyName, middleName, givenName, 303 null, null); 304 } 305 306 public static String constructNameFromElements(final int vcardType, 307 final String familyName, final String middleName, final String givenName, 308 final String prefix, final String suffix) { 309 final StringBuilder builder = new StringBuilder(); 310 final String[] nameList = sortNameElements(vcardType, familyName, middleName, givenName); 311 boolean first = true; 312 if (!TextUtils.isEmpty(prefix)) { 313 first = false; 314 builder.append(prefix); 315 } 316 for (final String namePart : nameList) { 317 if (!TextUtils.isEmpty(namePart)) { 318 if (first) { 319 first = false; 320 } else { 321 builder.append(' '); 322 } 323 builder.append(namePart); 324 } 325 } 326 if (!TextUtils.isEmpty(suffix)) { 327 if (!first) { 328 builder.append(' '); 329 } 330 builder.append(suffix); 331 } 332 return builder.toString(); 333 } 334 335 public static List<String> constructListFromValue(final String value, 336 final boolean isV30) { 337 final List<String> list = new ArrayList<String>(); 338 StringBuilder builder = new StringBuilder(); 339 int length = value.length(); 340 for (int i = 0; i < length; i++) { 341 char ch = value.charAt(i); 342 if (ch == '\\' && i < length - 1) { 343 char nextCh = value.charAt(i + 1); 344 final String unescapedString = 345 (isV30 ? VCardParserImpl_V30.escapeCharacter(nextCh) : 346 VCardParserImpl_V21.unescapeCharacter(nextCh)); 347 if (unescapedString != null) { 348 builder.append(unescapedString); 349 i++; 350 } else { 351 builder.append(ch); 352 } 353 } else if (ch == ';') { 354 list.add(builder.toString()); 355 builder = new StringBuilder(); 356 } else { 357 builder.append(ch); 358 } 359 } 360 list.add(builder.toString()); 361 return list; 362 } 363 364 public static boolean containsOnlyPrintableAscii(final String...values) { 365 if (values == null) { 366 return true; 367 } 368 return containsOnlyPrintableAscii(Arrays.asList(values)); 369 } 370 371 public static boolean containsOnlyPrintableAscii(final Collection<String> values) { 372 if (values == null) { 373 return true; 374 } 375 for (final String value : values) { 376 if (TextUtils.isEmpty(value)) { 377 continue; 378 } 379 if (!TextUtils.isPrintableAsciiOnly(value)) { 380 return false; 381 } 382 } 383 return true; 384 } 385 386 /** 387 * <p> 388 * This is useful when checking the string should be encoded into quoted-printable 389 * or not, which is required by vCard 2.1. 390 * </p> 391 * <p> 392 * See the definition of "7bit" in vCard 2.1 spec for more information. 393 * </p> 394 */ 395 public static boolean containsOnlyNonCrLfPrintableAscii(final String...values) { 396 if (values == null) { 397 return true; 398 } 399 return containsOnlyNonCrLfPrintableAscii(Arrays.asList(values)); 400 } 401 402 public static boolean containsOnlyNonCrLfPrintableAscii(final Collection<String> values) { 403 if (values == null) { 404 return true; 405 } 406 final int asciiFirst = 0x20; 407 final int asciiLast = 0x7E; // included 408 for (final String value : values) { 409 if (TextUtils.isEmpty(value)) { 410 continue; 411 } 412 final int length = value.length(); 413 for (int i = 0; i < length; i = value.offsetByCodePoints(i, 1)) { 414 final int c = value.codePointAt(i); 415 if (!(asciiFirst <= c && c <= asciiLast)) { 416 return false; 417 } 418 } 419 } 420 return true; 421 } 422 423 private static final Set<Character> sUnAcceptableAsciiInV21WordSet = 424 new HashSet<Character>(Arrays.asList('[', ']', '=', ':', '.', ',', ' ')); 425 426 /** 427 * <p> 428 * This is useful since vCard 3.0 often requires the ("X-") properties and groups 429 * should contain only alphabets, digits, and hyphen. 430 * </p> 431 * <p> 432 * Note: It is already known some devices (wrongly) outputs properties with characters 433 * which should not be in the field. One example is "X-GOOGLE TALK". We accept 434 * such kind of input but must never output it unless the target is very specific 435 * to the device which is able to parse the malformed input. 436 * </p> 437 */ 438 public static boolean containsOnlyAlphaDigitHyphen(final String...values) { 439 if (values == null) { 440 return true; 441 } 442 return containsOnlyAlphaDigitHyphen(Arrays.asList(values)); 443 } 444 445 public static boolean containsOnlyAlphaDigitHyphen(final Collection<String> values) { 446 if (values == null) { 447 return true; 448 } 449 final int upperAlphabetFirst = 0x41; // A 450 final int upperAlphabetAfterLast = 0x5b; // [ 451 final int lowerAlphabetFirst = 0x61; // a 452 final int lowerAlphabetAfterLast = 0x7b; // { 453 final int digitFirst = 0x30; // 0 454 final int digitAfterLast = 0x3A; // : 455 final int hyphen = '-'; 456 for (final String str : values) { 457 if (TextUtils.isEmpty(str)) { 458 continue; 459 } 460 final int length = str.length(); 461 for (int i = 0; i < length; i = str.offsetByCodePoints(i, 1)) { 462 int codepoint = str.codePointAt(i); 463 if (!((lowerAlphabetFirst <= codepoint && codepoint < lowerAlphabetAfterLast) || 464 (upperAlphabetFirst <= codepoint && codepoint < upperAlphabetAfterLast) || 465 (digitFirst <= codepoint && codepoint < digitAfterLast) || 466 (codepoint == hyphen))) { 467 return false; 468 } 469 } 470 } 471 return true; 472 } 473 474 public static boolean containsOnlyWhiteSpaces(final String...values) { 475 if (values == null) { 476 return true; 477 } 478 return containsOnlyWhiteSpaces(Arrays.asList(values)); 479 } 480 481 public static boolean containsOnlyWhiteSpaces(final Collection<String> values) { 482 if (values == null) { 483 return true; 484 } 485 for (final String str : values) { 486 if (TextUtils.isEmpty(str)) { 487 continue; 488 } 489 final int length = str.length(); 490 for (int i = 0; i < length; i = str.offsetByCodePoints(i, 1)) { 491 if (!Character.isWhitespace(str.codePointAt(i))) { 492 return false; 493 } 494 } 495 } 496 return true; 497 } 498 499 /** 500 * <p> 501 * Returns true when the given String is categorized as "word" specified in vCard spec 2.1. 502 * </p> 503 * <p> 504 * vCard 2.1 specifies:<br /> 505 * word = <any printable 7bit us-ascii except []=:., > 506 * </p> 507 */ 508 public static boolean isV21Word(final String value) { 509 if (TextUtils.isEmpty(value)) { 510 return true; 511 } 512 final int asciiFirst = 0x20; 513 final int asciiLast = 0x7E; // included 514 final int length = value.length(); 515 for (int i = 0; i < length; i = value.offsetByCodePoints(i, 1)) { 516 final int c = value.codePointAt(i); 517 if (!(asciiFirst <= c && c <= asciiLast) || 518 sUnAcceptableAsciiInV21WordSet.contains((char)c)) { 519 return false; 520 } 521 } 522 return true; 523 } 524 525 /** 526 * <P> 527 * Returns String available as parameter value in vCard 3.0. 528 * </P> 529 * <P> 530 * RFC 2426 requires vCard composer to quote parameter values when it contains 531 * semi-colon, for example (See RFC 2426 for more information). 532 * This method checks whether the given String can be used without quotes. 533 * </P> 534 * <P> 535 * Note: We remove DQUOTE silently for now. 536 * </P> 537 */ 538 public static String toStringAvailableAsV30ParamValue(String value) { 539 if (TextUtils.isEmpty(value)) { 540 value = ""; 541 } 542 final int asciiFirst = 0x20; 543 final int asciiLast = 0x7E; // included 544 final StringBuilder builder = new StringBuilder(); 545 final int length = value.length(); 546 boolean needQuote = false; 547 for (int i = 0; i < length; i = value.offsetByCodePoints(i, 1)) { 548 final int codePoint = value.codePointAt(i); 549 if (codePoint < asciiFirst || codePoint == '"') { 550 // CTL characters and DQUOTE are never accepted. Remove them. 551 continue; 552 } 553 builder.appendCodePoint(codePoint); 554 if (codePoint == ':' || codePoint == ',' || codePoint == ' ') { 555 needQuote = true; 556 } 557 } 558 559 final String result = builder.toString(); 560 return ((result.isEmpty() || VCardUtils.containsOnlyWhiteSpaces(result)) 561 ? "" 562 : (needQuote ? ('"' + result + '"') 563 : result)); 564 } 565 566 public static String toHalfWidthString(final String orgString) { 567 if (TextUtils.isEmpty(orgString)) { 568 return null; 569 } 570 final StringBuilder builder = new StringBuilder(); 571 final int length = orgString.length(); 572 for (int i = 0; i < length; i = orgString.offsetByCodePoints(i, 1)) { 573 // All Japanese character is able to be expressed by char. 574 // Do not need to use String#codepPointAt(). 575 final char ch = orgString.charAt(i); 576 final String halfWidthText = JapaneseUtils.tryGetHalfWidthText(ch); 577 if (halfWidthText != null) { 578 builder.append(halfWidthText); 579 } else { 580 builder.append(ch); 581 } 582 } 583 return builder.toString(); 584 } 585 586 /** 587 * Guesses the format of input image. Currently just the first few bytes are used. 588 * The type "GIF", "PNG", or "JPEG" is returned when possible. Returns null when 589 * the guess failed. 590 * @param input Image as byte array. 591 * @return The image type or null when the type cannot be determined. 592 */ 593 public static String guessImageType(final byte[] input) { 594 if (input == null) { 595 return null; 596 } 597 if (input.length >= 3 && input[0] == 'G' && input[1] == 'I' && input[2] == 'F') { 598 return "GIF"; 599 } else if (input.length >= 4 && input[0] == (byte) 0x89 600 && input[1] == 'P' && input[2] == 'N' && input[3] == 'G') { 601 // Note: vCard 2.1 officially does not support PNG, but we may have it and 602 // using X- word like "X-PNG" may not let importers know it is PNG. 603 // So we use the String "PNG" as is... 604 return "PNG"; 605 } else if (input.length >= 2 && input[0] == (byte) 0xff 606 && input[1] == (byte) 0xd8) { 607 return "JPEG"; 608 } else { 609 return null; 610 } 611 } 612 613 /** 614 * @return True when all the given values are null or empty Strings. 615 */ 616 public static boolean areAllEmpty(final String...values) { 617 if (values == null) { 618 return true; 619 } 620 621 for (final String value : values) { 622 if (!TextUtils.isEmpty(value)) { 623 return false; 624 } 625 } 626 return true; 627 } 628 629 //// The methods bellow may be used by unit test. 630 631 /** 632 * Unquotes given Quoted-Printable value. value must not be null. 633 */ 634 public static String parseQuotedPrintable( 635 final String value, boolean strictLineBreaking, 636 String sourceCharset, String targetCharset) { 637 // "= " -> " ", "=\t" -> "\t". 638 // Previous code had done this replacement. Keep on the safe side. 639 final String quotedPrintable; 640 { 641 final StringBuilder builder = new StringBuilder(); 642 final int length = value.length(); 643 for (int i = 0; i < length; i++) { 644 char ch = value.charAt(i); 645 if (ch == '=' && i < length - 1) { 646 char nextCh = value.charAt(i + 1); 647 if (nextCh == ' ' || nextCh == '\t') { 648 builder.append(nextCh); 649 i++; 650 continue; 651 } 652 } 653 builder.append(ch); 654 } 655 quotedPrintable = builder.toString(); 656 } 657 658 String[] lines; 659 if (strictLineBreaking) { 660 lines = quotedPrintable.split("\r\n"); 661 } else { 662 StringBuilder builder = new StringBuilder(); 663 final int length = quotedPrintable.length(); 664 ArrayList<String> list = new ArrayList<String>(); 665 for (int i = 0; i < length; i++) { 666 char ch = quotedPrintable.charAt(i); 667 if (ch == '\n') { 668 list.add(builder.toString()); 669 builder = new StringBuilder(); 670 } else if (ch == '\r') { 671 list.add(builder.toString()); 672 builder = new StringBuilder(); 673 if (i < length - 1) { 674 char nextCh = quotedPrintable.charAt(i + 1); 675 if (nextCh == '\n') { 676 i++; 677 } 678 } 679 } else { 680 builder.append(ch); 681 } 682 } 683 final String lastLine = builder.toString(); 684 if (lastLine.length() > 0) { 685 list.add(lastLine); 686 } 687 lines = list.toArray(new String[0]); 688 } 689 690 final StringBuilder builder = new StringBuilder(); 691 for (String line : lines) { 692 if (line.endsWith("=")) { 693 line = line.substring(0, line.length() - 1); 694 } 695 builder.append(line); 696 } 697 698 final String rawString = builder.toString(); 699 if (TextUtils.isEmpty(rawString)) { 700 Log.w(LOG_TAG, "Given raw string is empty."); 701 } 702 703 byte[] rawBytes = null; 704 try { 705 rawBytes = rawString.getBytes(sourceCharset); 706 } catch (UnsupportedEncodingException e) { 707 Log.w(LOG_TAG, "Failed to decode: " + sourceCharset); 708 rawBytes = rawString.getBytes(); 709 } 710 711 byte[] decodedBytes = null; 712 try { 713 decodedBytes = QuotedPrintableCodec.decodeQuotedPrintable(rawBytes); 714 } catch (DecoderException e) { 715 Log.e(LOG_TAG, "DecoderException is thrown."); 716 decodedBytes = rawBytes; 717 } 718 719 try { 720 return new String(decodedBytes, targetCharset); 721 } catch (UnsupportedEncodingException e) { 722 Log.e(LOG_TAG, "Failed to encode: charset=" + targetCharset); 723 return new String(decodedBytes); 724 } 725 } 726 727 public static final VCardParser getAppropriateParser(int vcardType) 728 throws VCardException { 729 if (VCardConfig.isVersion21(vcardType)) { 730 return new VCardParser_V21(); 731 } else if (VCardConfig.isVersion30(vcardType)) { 732 return new VCardParser_V30(); 733 } else if (VCardConfig.isVersion40(vcardType)) { 734 return new VCardParser_V40(); 735 } else { 736 throw new VCardException("Version is not specified"); 737 } 738 } 739 740 public static final String convertStringCharset( 741 String originalString, String sourceCharset, String targetCharset) { 742 if (sourceCharset.equalsIgnoreCase(targetCharset)) { 743 return originalString; 744 } 745 final Charset charset = Charset.forName(sourceCharset); 746 final ByteBuffer byteBuffer = charset.encode(originalString); 747 // byteBuffer.array() "may" return byte array which is larger than 748 // byteBuffer.remaining(). Here, we keep on the safe side. 749 final byte[] bytes = new byte[byteBuffer.remaining()]; 750 byteBuffer.get(bytes); 751 try { 752 return new String(bytes, targetCharset); 753 } catch (UnsupportedEncodingException e) { 754 Log.e(LOG_TAG, "Failed to encode: charset=" + targetCharset); 755 return null; 756 } 757 } 758 759 // TODO: utilities for vCard 4.0: datetime, timestamp, integer, float, and boolean 760 761 private VCardUtils() { 762 } 763} 764