1 /* 2 * Copyright (C) 2009 The Libphonenumber 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.android.i18n.phonenumbers; 18 19 import com.android.i18n.phonenumbers.Phonemetadata.NumberFormat; 20 import com.android.i18n.phonenumbers.Phonemetadata.PhoneMetadata; 21 import com.android.i18n.phonenumbers.Phonemetadata.PhoneMetadataCollection; 22 import com.android.i18n.phonenumbers.Phonemetadata.PhoneNumberDesc; 23 import com.android.i18n.phonenumbers.Phonenumber.PhoneNumber; 24 import com.android.i18n.phonenumbers.Phonenumber.PhoneNumber.CountryCodeSource; 25 26 import java.io.IOException; 27 import java.io.InputStream; 28 import java.io.ObjectInput; 29 import java.io.ObjectInputStream; 30 import java.util.ArrayList; 31 import java.util.Arrays; 32 import java.util.Collections; 33 import java.util.HashMap; 34 import java.util.HashSet; 35 import java.util.Iterator; 36 import java.util.List; 37 import java.util.Map; 38 import java.util.Set; 39 import java.util.logging.Level; 40 import java.util.logging.Logger; 41 import java.util.regex.Matcher; 42 import java.util.regex.Pattern; 43 44 /** 45 * Utility for international phone numbers. Functionality includes formatting, parsing and 46 * validation. 47 * 48 * <p>If you use this library, and want to be notified about important changes, please sign up to 49 * our <a href="http://groups.google.com/group/libphonenumber-discuss/about">mailing list</a>. 50 * 51 * NOTE: A lot of methods in this class require Region Code strings. These must be provided using 52 * ISO 3166-1 two-letter country-code format. These should be in upper-case. The list of the codes 53 * can be found here: 54 * http://www.iso.org/iso/country_codes/iso_3166_code_lists/country_names_and_code_elements.htm 55 * 56 * @author Shaopeng Jia 57 */ 58 public class PhoneNumberUtil { 59 // @VisibleForTesting 60 static final MetadataLoader DEFAULT_METADATA_LOADER = new MetadataLoader() { 61 public InputStream loadMetadata(String metadataFileName) { 62 return PhoneNumberUtil.class.getResourceAsStream(metadataFileName); 63 } 64 }; 65 66 private static final Logger logger = Logger.getLogger(PhoneNumberUtil.class.getName()); 67 68 /** Flags to use when compiling regular expressions for phone numbers. */ 69 static final int REGEX_FLAGS = Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE; 70 // The minimum and maximum length of the national significant number. 71 private static final int MIN_LENGTH_FOR_NSN = 2; 72 // The ITU says the maximum length should be 15, but we have found longer numbers in Germany. 73 static final int MAX_LENGTH_FOR_NSN = 17; 74 // The maximum length of the country calling code. 75 static final int MAX_LENGTH_COUNTRY_CODE = 3; 76 // We don't allow input strings for parsing to be longer than 250 chars. This prevents malicious 77 // input from overflowing the regular-expression engine. 78 private static final int MAX_INPUT_STRING_LENGTH = 250; 79 80 private static final String META_DATA_FILE_PREFIX = 81 "/com/android/i18n/phonenumbers/data/PhoneNumberMetadataProto"; 82 83 // Region-code for the unknown region. 84 private static final String UNKNOWN_REGION = "ZZ"; 85 86 private static final int NANPA_COUNTRY_CODE = 1; 87 88 // The prefix that needs to be inserted in front of a Colombian landline number when dialed from 89 // a mobile phone in Colombia. 90 private static final String COLOMBIA_MOBILE_TO_FIXED_LINE_PREFIX = "3"; 91 92 // Map of country calling codes that use a mobile token before the area code. One example of when 93 // this is relevant is when determining the length of the national destination code, which should 94 // be the length of the area code plus the length of the mobile token. 95 private static final Map<Integer, String> MOBILE_TOKEN_MAPPINGS; 96 97 // The PLUS_SIGN signifies the international prefix. 98 static final char PLUS_SIGN = '+'; 99 100 private static final char STAR_SIGN = '*'; 101 102 private static final String RFC3966_EXTN_PREFIX = ";ext="; 103 private static final String RFC3966_PREFIX = "tel:"; 104 private static final String RFC3966_PHONE_CONTEXT = ";phone-context="; 105 private static final String RFC3966_ISDN_SUBADDRESS = ";isub="; 106 107 // A map that contains characters that are essential when dialling. That means any of the 108 // characters in this map must not be removed from a number when dialling, otherwise the call 109 // will not reach the intended destination. 110 private static final Map<Character, Character> DIALLABLE_CHAR_MAPPINGS; 111 112 // Only upper-case variants of alpha characters are stored. 113 private static final Map<Character, Character> ALPHA_MAPPINGS; 114 115 // For performance reasons, amalgamate both into one map. 116 private static final Map<Character, Character> ALPHA_PHONE_MAPPINGS; 117 118 // Separate map of all symbols that we wish to retain when formatting alpha numbers. This 119 // includes digits, ASCII letters and number grouping symbols such as "-" and " ". 120 private static final Map<Character, Character> ALL_PLUS_NUMBER_GROUPING_SYMBOLS; 121 122 static { 123 HashMap<Integer, String> mobileTokenMap = new HashMap<Integer, String>(); 124 mobileTokenMap.put(52, "1"); 125 mobileTokenMap.put(54, "9"); 126 MOBILE_TOKEN_MAPPINGS = Collections.unmodifiableMap(mobileTokenMap); 127 128 // Simple ASCII digits map used to populate ALPHA_PHONE_MAPPINGS and 129 // ALL_PLUS_NUMBER_GROUPING_SYMBOLS. 130 HashMap<Character, Character> asciiDigitMappings = new HashMap<Character, Character>(); 131 asciiDigitMappings.put('0', '0'); 132 asciiDigitMappings.put('1', '1'); 133 asciiDigitMappings.put('2', '2'); 134 asciiDigitMappings.put('3', '3'); 135 asciiDigitMappings.put('4', '4'); 136 asciiDigitMappings.put('5', '5'); 137 asciiDigitMappings.put('6', '6'); 138 asciiDigitMappings.put('7', '7'); 139 asciiDigitMappings.put('8', '8'); 140 asciiDigitMappings.put('9', '9'); 141 142 HashMap<Character, Character> alphaMap = new HashMap<Character, Character>(40); 143 alphaMap.put('A', '2'); 144 alphaMap.put('B', '2'); 145 alphaMap.put('C', '2'); 146 alphaMap.put('D', '3'); 147 alphaMap.put('E', '3'); 148 alphaMap.put('F', '3'); 149 alphaMap.put('G', '4'); 150 alphaMap.put('H', '4'); 151 alphaMap.put('I', '4'); 152 alphaMap.put('J', '5'); 153 alphaMap.put('K', '5'); 154 alphaMap.put('L', '5'); 155 alphaMap.put('M', '6'); 156 alphaMap.put('N', '6'); 157 alphaMap.put('O', '6'); 158 alphaMap.put('P', '7'); 159 alphaMap.put('Q', '7'); 160 alphaMap.put('R', '7'); 161 alphaMap.put('S', '7'); 162 alphaMap.put('T', '8'); 163 alphaMap.put('U', '8'); 164 alphaMap.put('V', '8'); 165 alphaMap.put('W', '9'); 166 alphaMap.put('X', '9'); 167 alphaMap.put('Y', '9'); 168 alphaMap.put('Z', '9'); 169 ALPHA_MAPPINGS = Collections.unmodifiableMap(alphaMap); 170 171 HashMap<Character, Character> combinedMap = new HashMap<Character, Character>(100); 172 combinedMap.putAll(ALPHA_MAPPINGS); 173 combinedMap.putAll(asciiDigitMappings); 174 ALPHA_PHONE_MAPPINGS = Collections.unmodifiableMap(combinedMap); 175 176 HashMap<Character, Character> diallableCharMap = new HashMap<Character, Character>(); 177 diallableCharMap.putAll(asciiDigitMappings); 178 diallableCharMap.put(PLUS_SIGN, PLUS_SIGN); 179 diallableCharMap.put('*', '*'); 180 DIALLABLE_CHAR_MAPPINGS = Collections.unmodifiableMap(diallableCharMap); 181 182 HashMap<Character, Character> allPlusNumberGroupings = new HashMap<Character, Character>(); 183 // Put (lower letter -> upper letter) and (upper letter -> upper letter) mappings. 184 for (char c : ALPHA_MAPPINGS.keySet()) { 185 allPlusNumberGroupings.put(Character.toLowerCase(c), c); 186 allPlusNumberGroupings.put(c, c); 187 } 188 allPlusNumberGroupings.putAll(asciiDigitMappings); 189 // Put grouping symbols. 190 allPlusNumberGroupings.put('-', '-'); 191 allPlusNumberGroupings.put('\uFF0D', '-'); 192 allPlusNumberGroupings.put('\u2010', '-'); 193 allPlusNumberGroupings.put('\u2011', '-'); 194 allPlusNumberGroupings.put('\u2012', '-'); 195 allPlusNumberGroupings.put('\u2013', '-'); 196 allPlusNumberGroupings.put('\u2014', '-'); 197 allPlusNumberGroupings.put('\u2015', '-'); 198 allPlusNumberGroupings.put('\u2212', '-'); 199 allPlusNumberGroupings.put('/', '/'); 200 allPlusNumberGroupings.put('\uFF0F', '/'); 201 allPlusNumberGroupings.put(' ', ' '); 202 allPlusNumberGroupings.put('\u3000', ' '); 203 allPlusNumberGroupings.put('\u2060', ' '); 204 allPlusNumberGroupings.put('.', '.'); 205 allPlusNumberGroupings.put('\uFF0E', '.'); 206 ALL_PLUS_NUMBER_GROUPING_SYMBOLS = Collections.unmodifiableMap(allPlusNumberGroupings); 207 } 208 209 // Pattern that makes it easy to distinguish whether a region has a unique international dialing 210 // prefix or not. If a region has a unique international prefix (e.g. 011 in USA), it will be 211 // represented as a string that contains a sequence of ASCII digits. If there are multiple 212 // available international prefixes in a region, they will be represented as a regex string that 213 // always contains character(s) other than ASCII digits. 214 // Note this regex also includes tilde, which signals waiting for the tone. 215 private static final Pattern UNIQUE_INTERNATIONAL_PREFIX = 216 Pattern.compile("[\\d]+(?:[~\u2053\u223C\uFF5E][\\d]+)?"); 217 218 // Regular expression of acceptable punctuation found in phone numbers. This excludes punctuation 219 // found as a leading character only. 220 // This consists of dash characters, white space characters, full stops, slashes, 221 // square brackets, parentheses and tildes. It also includes the letter 'x' as that is found as a 222 // placeholder for carrier information in some phone numbers. Full-width variants are also 223 // present. 224 static final String VALID_PUNCTUATION = "-x\u2010-\u2015\u2212\u30FC\uFF0D-\uFF0F " + 225 "\u00A0\u00AD\u200B\u2060\u3000()\uFF08\uFF09\uFF3B\uFF3D.\\[\\]/~\u2053\u223C\uFF5E"; 226 227 private static final String DIGITS = "\\p{Nd}"; 228 // We accept alpha characters in phone numbers, ASCII only, upper and lower case. 229 private static final String VALID_ALPHA = 230 Arrays.toString(ALPHA_MAPPINGS.keySet().toArray()).replaceAll("[, \\[\\]]", "") + 231 Arrays.toString(ALPHA_MAPPINGS.keySet().toArray()).toLowerCase().replaceAll("[, \\[\\]]", ""); 232 static final String PLUS_CHARS = "+\uFF0B"; 233 static final Pattern PLUS_CHARS_PATTERN = Pattern.compile("[" + PLUS_CHARS + "]+"); 234 private static final Pattern SEPARATOR_PATTERN = Pattern.compile("[" + VALID_PUNCTUATION + "]+"); 235 private static final Pattern CAPTURING_DIGIT_PATTERN = Pattern.compile("(" + DIGITS + ")"); 236 237 // Regular expression of acceptable characters that may start a phone number for the purposes of 238 // parsing. This allows us to strip away meaningless prefixes to phone numbers that may be 239 // mistakenly given to us. This consists of digits, the plus symbol and arabic-indic digits. This 240 // does not contain alpha characters, although they may be used later in the number. It also does 241 // not include other punctuation, as this will be stripped later during parsing and is of no 242 // information value when parsing a number. 243 private static final String VALID_START_CHAR = "[" + PLUS_CHARS + DIGITS + "]"; 244 private static final Pattern VALID_START_CHAR_PATTERN = Pattern.compile(VALID_START_CHAR); 245 246 // Regular expression of characters typically used to start a second phone number for the purposes 247 // of parsing. This allows us to strip off parts of the number that are actually the start of 248 // another number, such as for: (530) 583-6985 x302/x2303 -> the second extension here makes this 249 // actually two phone numbers, (530) 583-6985 x302 and (530) 583-6985 x2303. We remove the second 250 // extension so that the first number is parsed correctly. 251 private static final String SECOND_NUMBER_START = "[\\\\/] *x"; 252 static final Pattern SECOND_NUMBER_START_PATTERN = Pattern.compile(SECOND_NUMBER_START); 253 254 // Regular expression of trailing characters that we want to remove. We remove all characters that 255 // are not alpha or numerical characters. The hash character is retained here, as it may signify 256 // the previous block was an extension. 257 private static final String UNWANTED_END_CHARS = "[[\\P{N}&&\\P{L}]&&[^#]]+$"; 258 static final Pattern UNWANTED_END_CHAR_PATTERN = Pattern.compile(UNWANTED_END_CHARS); 259 260 // We use this pattern to check if the phone number has at least three letters in it - if so, then 261 // we treat it as a number where some phone-number digits are represented by letters. 262 private static final Pattern VALID_ALPHA_PHONE_PATTERN = Pattern.compile("(?:.*?[A-Za-z]){3}.*"); 263 264 // Regular expression of viable phone numbers. This is location independent. Checks we have at 265 // least three leading digits, and only valid punctuation, alpha characters and 266 // digits in the phone number. Does not include extension data. 267 // The symbol 'x' is allowed here as valid punctuation since it is often used as a placeholder for 268 // carrier codes, for example in Brazilian phone numbers. We also allow multiple "+" characters at 269 // the start. 270 // Corresponds to the following: 271 // [digits]{minLengthNsn}| 272 // plus_sign*(([punctuation]|[star])*[digits]){3,}([punctuation]|[star]|[digits]|[alpha])* 273 // 274 // The first reg-ex is to allow short numbers (two digits long) to be parsed if they are entered 275 // as "15" etc, but only if there is no punctuation in them. The second expression restricts the 276 // number of digits to three or more, but then allows them to be in international form, and to 277 // have alpha-characters and punctuation. 278 // 279 // Note VALID_PUNCTUATION starts with a -, so must be the first in the range. 280 private static final String VALID_PHONE_NUMBER = 281 DIGITS + "{" + MIN_LENGTH_FOR_NSN + "}" + "|" + 282 "[" + PLUS_CHARS + "]*+(?:[" + VALID_PUNCTUATION + STAR_SIGN + "]*" + DIGITS + "){3,}[" + 283 VALID_PUNCTUATION + STAR_SIGN + VALID_ALPHA + DIGITS + "]*"; 284 285 // Default extension prefix to use when formatting. This will be put in front of any extension 286 // component of the number, after the main national number is formatted. For example, if you wish 287 // the default extension formatting to be " extn: 3456", then you should specify " extn: " here 288 // as the default extension prefix. This can be overridden by region-specific preferences. 289 private static final String DEFAULT_EXTN_PREFIX = " ext. "; 290 291 // Pattern to capture digits used in an extension. Places a maximum length of "7" for an 292 // extension. 293 private static final String CAPTURING_EXTN_DIGITS = "(" + DIGITS + "{1,7})"; 294 // Regexp of all possible ways to write extensions, for use when parsing. This will be run as a 295 // case-insensitive regexp match. Wide character versions are also provided after each ASCII 296 // version. 297 private static final String EXTN_PATTERNS_FOR_PARSING; 298 static final String EXTN_PATTERNS_FOR_MATCHING; 299 static { 300 // One-character symbols that can be used to indicate an extension. 301 String singleExtnSymbolsForMatching = "x\uFF58#\uFF03~\uFF5E"; 302 // For parsing, we are slightly more lenient in our interpretation than for matching. Here we 303 // allow a "comma" as a possible extension indicator. When matching, this is hardly ever used to 304 // indicate this. 305 String singleExtnSymbolsForParsing = "," + singleExtnSymbolsForMatching; 306 307 EXTN_PATTERNS_FOR_PARSING = createExtnPattern(singleExtnSymbolsForParsing); 308 EXTN_PATTERNS_FOR_MATCHING = createExtnPattern(singleExtnSymbolsForMatching); 309 } 310 311 /** 312 * Helper initialiser method to create the regular-expression pattern to match extensions, 313 * allowing the one-char extension symbols provided by {@code singleExtnSymbols}. 314 */ 315 private static String createExtnPattern(String singleExtnSymbols) { 316 // There are three regular expressions here. The first covers RFC 3966 format, where the 317 // extension is added using ";ext=". The second more generic one starts with optional white 318 // space and ends with an optional full stop (.), followed by zero or more spaces/tabs and then 319 // the numbers themselves. The other one covers the special case of American numbers where the 320 // extension is written with a hash at the end, such as "- 503#". 321 // Note that the only capturing groups should be around the digits that you want to capture as 322 // part of the extension, or else parsing will fail! 323 // Canonical-equivalence doesn't seem to be an option with Android java, so we allow two options 324 // for representing the accented o - the character itself, and one in the unicode decomposed 325 // form with the combining acute accent. 326 return (RFC3966_EXTN_PREFIX + CAPTURING_EXTN_DIGITS + "|" + "[ \u00A0\\t,]*" + 327 "(?:e?xt(?:ensi(?:o\u0301?|\u00F3))?n?|\uFF45?\uFF58\uFF54\uFF4E?|" + 328 "[" + singleExtnSymbols + "]|int|anexo|\uFF49\uFF4E\uFF54)" + 329 "[:\\.\uFF0E]?[ \u00A0\\t,-]*" + CAPTURING_EXTN_DIGITS + "#?|" + 330 "[- ]+(" + DIGITS + "{1,5})#"); 331 } 332 333 // Regexp of all known extension prefixes used by different regions followed by 1 or more valid 334 // digits, for use when parsing. 335 private static final Pattern EXTN_PATTERN = 336 Pattern.compile("(?:" + EXTN_PATTERNS_FOR_PARSING + ")$", REGEX_FLAGS); 337 338 // We append optionally the extension pattern to the end here, as a valid phone number may 339 // have an extension prefix appended, followed by 1 or more digits. 340 private static final Pattern VALID_PHONE_NUMBER_PATTERN = 341 Pattern.compile(VALID_PHONE_NUMBER + "(?:" + EXTN_PATTERNS_FOR_PARSING + ")?", REGEX_FLAGS); 342 343 static final Pattern NON_DIGITS_PATTERN = Pattern.compile("(\\D+)"); 344 345 // The FIRST_GROUP_PATTERN was originally set to $1 but there are some countries for which the 346 // first group is not used in the national pattern (e.g. Argentina) so the $1 group does not match 347 // correctly. Therefore, we use \d, so that the first group actually used in the pattern will be 348 // matched. 349 private static final Pattern FIRST_GROUP_PATTERN = Pattern.compile("(\\$\\d)"); 350 private static final Pattern NP_PATTERN = Pattern.compile("\\$NP"); 351 private static final Pattern FG_PATTERN = Pattern.compile("\\$FG"); 352 private static final Pattern CC_PATTERN = Pattern.compile("\\$CC"); 353 354 // A pattern that is used to determine if the national prefix formatting rule has the first group 355 // only, i.e., does not start with the national prefix. Note that the pattern explicitly allows 356 // for unbalanced parentheses. 357 private static final Pattern FIRST_GROUP_ONLY_PREFIX_PATTERN = Pattern.compile("\\(?\\$1\\)?"); 358 359 private static PhoneNumberUtil instance = null; 360 361 public static final String REGION_CODE_FOR_NON_GEO_ENTITY = "001"; 362 363 /** 364 * INTERNATIONAL and NATIONAL formats are consistent with the definition in ITU-T Recommendation 365 * E123. For example, the number of the Google Switzerland office will be written as 366 * "+41 44 668 1800" in INTERNATIONAL format, and as "044 668 1800" in NATIONAL format. 367 * E164 format is as per INTERNATIONAL format but with no formatting applied, e.g. 368 * "+41446681800". RFC3966 is as per INTERNATIONAL format, but with all spaces and other 369 * separating symbols replaced with a hyphen, and with any phone number extension appended with 370 * ";ext=". It also will have a prefix of "tel:" added, e.g. "tel:+41-44-668-1800". 371 * 372 * Note: If you are considering storing the number in a neutral format, you are highly advised to 373 * use the PhoneNumber class. 374 */ 375 public enum PhoneNumberFormat { 376 E164, 377 INTERNATIONAL, 378 NATIONAL, 379 RFC3966 380 } 381 382 /** 383 * Type of phone numbers. 384 */ 385 public enum PhoneNumberType { 386 FIXED_LINE, 387 MOBILE, 388 // In some regions (e.g. the USA), it is impossible to distinguish between fixed-line and 389 // mobile numbers by looking at the phone number itself. 390 FIXED_LINE_OR_MOBILE, 391 // Freephone lines 392 TOLL_FREE, 393 PREMIUM_RATE, 394 // The cost of this call is shared between the caller and the recipient, and is hence typically 395 // less than PREMIUM_RATE calls. See // http://en.wikipedia.org/wiki/Shared_Cost_Service for 396 // more information. 397 SHARED_COST, 398 // Voice over IP numbers. This includes TSoIP (Telephony Service over IP). 399 VOIP, 400 // A personal number is associated with a particular person, and may be routed to either a 401 // MOBILE or FIXED_LINE number. Some more information can be found here: 402 // http://en.wikipedia.org/wiki/Personal_Numbers 403 PERSONAL_NUMBER, 404 PAGER, 405 // Used for "Universal Access Numbers" or "Company Numbers". They may be further routed to 406 // specific offices, but allow one number to be used for a company. 407 UAN, 408 // Used for "Voice Mail Access Numbers". 409 VOICEMAIL, 410 // A phone number is of type UNKNOWN when it does not fit any of the known patterns for a 411 // specific region. 412 UNKNOWN 413 } 414 415 /** 416 * Types of phone number matches. See detailed description beside the isNumberMatch() method. 417 */ 418 public enum MatchType { 419 NOT_A_NUMBER, 420 NO_MATCH, 421 SHORT_NSN_MATCH, 422 NSN_MATCH, 423 EXACT_MATCH, 424 } 425 426 /** 427 * Possible outcomes when testing if a PhoneNumber is possible. 428 */ 429 public enum ValidationResult { 430 IS_POSSIBLE, 431 INVALID_COUNTRY_CODE, 432 TOO_SHORT, 433 TOO_LONG, 434 } 435 436 /** 437 * Leniency when {@linkplain PhoneNumberUtil#findNumbers finding} potential phone numbers in text 438 * segments. The levels here are ordered in increasing strictness. 439 */ 440 public enum Leniency { 441 /** 442 * Phone numbers accepted are {@linkplain PhoneNumberUtil#isPossibleNumber(PhoneNumber) 443 * possible}, but not necessarily {@linkplain PhoneNumberUtil#isValidNumber(PhoneNumber) valid}. 444 */ 445 POSSIBLE { 446 @Override 447 boolean verify(PhoneNumber number, String candidate, PhoneNumberUtil util) { 448 return util.isPossibleNumber(number); 449 } 450 }, 451 /** 452 * Phone numbers accepted are {@linkplain PhoneNumberUtil#isPossibleNumber(PhoneNumber) 453 * possible} and {@linkplain PhoneNumberUtil#isValidNumber(PhoneNumber) valid}. Numbers written 454 * in national format must have their national-prefix present if it is usually written for a 455 * number of this type. 456 */ 457 VALID { 458 @Override 459 boolean verify(PhoneNumber number, String candidate, PhoneNumberUtil util) { 460 if (!util.isValidNumber(number) || 461 !PhoneNumberMatcher.containsOnlyValidXChars(number, candidate, util)) { 462 return false; 463 } 464 return PhoneNumberMatcher.isNationalPrefixPresentIfRequired(number, util); 465 } 466 }, 467 /** 468 * Phone numbers accepted are {@linkplain PhoneNumberUtil#isValidNumber(PhoneNumber) valid} and 469 * are grouped in a possible way for this locale. For example, a US number written as 470 * "65 02 53 00 00" and "650253 0000" are not accepted at this leniency level, whereas 471 * "650 253 0000", "650 2530000" or "6502530000" are. 472 * Numbers with more than one '/' symbol in the national significant number are also dropped at 473 * this level. 474 * <p> 475 * Warning: This level might result in lower coverage especially for regions outside of country 476 * code "+1". If you are not sure about which level to use, email the discussion group 477 * libphonenumber-discuss (at) googlegroups.com. 478 */ 479 STRICT_GROUPING { 480 @Override 481 boolean verify(PhoneNumber number, String candidate, PhoneNumberUtil util) { 482 if (!util.isValidNumber(number) || 483 !PhoneNumberMatcher.containsOnlyValidXChars(number, candidate, util) || 484 PhoneNumberMatcher.containsMoreThanOneSlashInNationalNumber(number, candidate) || 485 !PhoneNumberMatcher.isNationalPrefixPresentIfRequired(number, util)) { 486 return false; 487 } 488 return PhoneNumberMatcher.checkNumberGroupingIsValid( 489 number, candidate, util, new PhoneNumberMatcher.NumberGroupingChecker() { 490 public boolean checkGroups(PhoneNumberUtil util, PhoneNumber number, 491 StringBuilder normalizedCandidate, 492 String[] expectedNumberGroups) { 493 return PhoneNumberMatcher.allNumberGroupsRemainGrouped( 494 util, number, normalizedCandidate, expectedNumberGroups); 495 } 496 }); 497 } 498 }, 499 /** 500 * Phone numbers accepted are {@linkplain PhoneNumberUtil#isValidNumber(PhoneNumber) valid} and 501 * are grouped in the same way that we would have formatted it, or as a single block. For 502 * example, a US number written as "650 2530000" is not accepted at this leniency level, whereas 503 * "650 253 0000" or "6502530000" are. 504 * Numbers with more than one '/' symbol are also dropped at this level. 505 * <p> 506 * Warning: This level might result in lower coverage especially for regions outside of country 507 * code "+1". If you are not sure about which level to use, email the discussion group 508 * libphonenumber-discuss (at) googlegroups.com. 509 */ 510 EXACT_GROUPING { 511 @Override 512 boolean verify(PhoneNumber number, String candidate, PhoneNumberUtil util) { 513 if (!util.isValidNumber(number) || 514 !PhoneNumberMatcher.containsOnlyValidXChars(number, candidate, util) || 515 PhoneNumberMatcher.containsMoreThanOneSlashInNationalNumber(number, candidate) || 516 !PhoneNumberMatcher.isNationalPrefixPresentIfRequired(number, util)) { 517 return false; 518 } 519 return PhoneNumberMatcher.checkNumberGroupingIsValid( 520 number, candidate, util, new PhoneNumberMatcher.NumberGroupingChecker() { 521 public boolean checkGroups(PhoneNumberUtil util, PhoneNumber number, 522 StringBuilder normalizedCandidate, 523 String[] expectedNumberGroups) { 524 return PhoneNumberMatcher.allNumberGroupsAreExactlyPresent( 525 util, number, normalizedCandidate, expectedNumberGroups); 526 } 527 }); 528 } 529 }; 530 531 /** Returns true if {@code number} is a verified number according to this leniency. */ 532 abstract boolean verify(PhoneNumber number, String candidate, PhoneNumberUtil util); 533 } 534 535 // A mapping from a country calling code to the region codes which denote the region represented 536 // by that country calling code. In the case of multiple regions sharing a calling code, such as 537 // the NANPA regions, the one indicated with "isMainCountryForCode" in the metadata should be 538 // first. 539 private final Map<Integer, List<String>> countryCallingCodeToRegionCodeMap; 540 541 // The set of regions that share country calling code 1. 542 // There are roughly 26 regions and we set the initial capacity of the HashSet to 35 to offer a 543 // load factor of roughly 0.75. 544 private final Set<String> nanpaRegions = new HashSet<String>(35); 545 546 // A mapping from a region code to the PhoneMetadata for that region. 547 // Note: Synchronization, though only needed for the Android version of the library, is used in 548 // all versions for consistency. 549 private final Map<String, PhoneMetadata> regionToMetadataMap = 550 Collections.synchronizedMap(new HashMap<String, PhoneMetadata>()); 551 552 // A mapping from a country calling code for a non-geographical entity to the PhoneMetadata for 553 // that country calling code. Examples of the country calling codes include 800 (International 554 // Toll Free Service) and 808 (International Shared Cost Service). 555 // Note: Synchronization, though only needed for the Android version of the library, is used in 556 // all versions for consistency. 557 private final Map<Integer, PhoneMetadata> countryCodeToNonGeographicalMetadataMap = 558 Collections.synchronizedMap(new HashMap<Integer, PhoneMetadata>()); 559 560 // A cache for frequently used region-specific regular expressions. 561 // The initial capacity is set to 100 as this seems to be an optimal value for Android, based on 562 // performance measurements. 563 private final RegexCache regexCache = new RegexCache(100); 564 565 // The set of regions the library supports. 566 // There are roughly 240 of them and we set the initial capacity of the HashSet to 320 to offer a 567 // load factor of roughly 0.75. 568 private final Set<String> supportedRegions = new HashSet<String>(320); 569 570 // The set of county calling codes that map to the non-geo entity region ("001"). This set 571 // currently contains < 12 elements so the default capacity of 16 (load factor=0.75) is fine. 572 private final Set<Integer> countryCodesForNonGeographicalRegion = new HashSet<Integer>(); 573 574 // The prefix of the metadata files from which region data is loaded. 575 private final String currentFilePrefix; 576 // The metadata loader used to inject alternative metadata sources. 577 private final MetadataLoader metadataLoader; 578 579 /** 580 * This class implements a singleton, so the only constructor is private. 581 */ 582 // @VisibleForTesting 583 PhoneNumberUtil(String filePrefix, MetadataLoader metadataLoader, 584 Map<Integer, List<String>> countryCallingCodeToRegionCodeMap) { 585 this.currentFilePrefix = filePrefix; 586 this.metadataLoader = metadataLoader; 587 this.countryCallingCodeToRegionCodeMap = countryCallingCodeToRegionCodeMap; 588 for (Map.Entry<Integer, List<String>> entry : countryCallingCodeToRegionCodeMap.entrySet()) { 589 List<String> regionCodes = entry.getValue(); 590 // We can assume that if the county calling code maps to the non-geo entity region code then 591 // that's the only region code it maps to. 592 if (regionCodes.size() == 1 && REGION_CODE_FOR_NON_GEO_ENTITY.equals(regionCodes.get(0))) { 593 // This is the subset of all country codes that map to the non-geo entity region code. 594 countryCodesForNonGeographicalRegion.add(entry.getKey()); 595 } else { 596 // The supported regions set does not include the "001" non-geo entity region code. 597 supportedRegions.addAll(regionCodes); 598 } 599 } 600 // If the non-geo entity still got added to the set of supported regions it must be because 601 // there are entries that list the non-geo entity alongside normal regions (which is wrong). 602 // If we discover this, remove the non-geo entity from the set of supported regions and log. 603 if (supportedRegions.remove(REGION_CODE_FOR_NON_GEO_ENTITY)) { 604 logger.log(Level.WARNING, "invalid metadata " + 605 "(country calling code was mapped to the non-geo entity as well as specific region(s))"); 606 } 607 nanpaRegions.addAll(countryCallingCodeToRegionCodeMap.get(NANPA_COUNTRY_CODE)); 608 } 609 610 // @VisibleForTesting 611 void loadMetadataFromFile(String filePrefix, String regionCode, int countryCallingCode, 612 MetadataLoader metadataLoader) { 613 boolean isNonGeoRegion = REGION_CODE_FOR_NON_GEO_ENTITY.equals(regionCode); 614 String fileName = filePrefix + "_" + 615 (isNonGeoRegion ? String.valueOf(countryCallingCode) : regionCode); 616 InputStream source = metadataLoader.loadMetadata(fileName); 617 if (source == null) { 618 logger.log(Level.SEVERE, "missing metadata: " + fileName); 619 throw new IllegalStateException("missing metadata: " + fileName); 620 } 621 ObjectInputStream in = null; 622 try { 623 in = new ObjectInputStream(source); 624 PhoneMetadataCollection metadataCollection = loadMetadataAndCloseInput(in); 625 List<PhoneMetadata> metadataList = metadataCollection.getMetadataList(); 626 if (metadataList.isEmpty()) { 627 logger.log(Level.SEVERE, "empty metadata: " + fileName); 628 throw new IllegalStateException("empty metadata: " + fileName); 629 } 630 if (metadataList.size() > 1) { 631 logger.log(Level.WARNING, "invalid metadata (too many entries): " + fileName); 632 } 633 PhoneMetadata metadata = metadataList.get(0); 634 if (isNonGeoRegion) { 635 countryCodeToNonGeographicalMetadataMap.put(countryCallingCode, metadata); 636 } else { 637 regionToMetadataMap.put(regionCode, metadata); 638 } 639 } catch (IOException e) { 640 logger.log(Level.SEVERE, "cannot load/parse metadata: " + fileName, e); 641 throw new RuntimeException("cannot load/parse metadata: " + fileName, e); 642 } 643 } 644 645 /** 646 * Loads the metadata protocol buffer from the given stream and closes the stream afterwards. Any 647 * exceptions that occur while reading the stream are propagated (though exceptions that occur 648 * when the stream is closed will be ignored). 649 * 650 * @param source the non-null stream from which metadata is to be read. 651 * @return the loaded metadata protocol buffer. 652 */ 653 private static PhoneMetadataCollection loadMetadataAndCloseInput(ObjectInputStream source) { 654 PhoneMetadataCollection metadataCollection = new PhoneMetadataCollection(); 655 try { 656 metadataCollection.readExternal(source); 657 } catch (IOException e) { 658 logger.log(Level.WARNING, "error reading input (ignored)", e); 659 } finally { 660 try { 661 source.close(); 662 } catch (IOException e) { 663 logger.log(Level.WARNING, "error closing input stream (ignored)", e); 664 } finally { 665 return metadataCollection; 666 } 667 } 668 } 669 670 /** 671 * Attempts to extract a possible number from the string passed in. This currently strips all 672 * leading characters that cannot be used to start a phone number. Characters that can be used to 673 * start a phone number are defined in the VALID_START_CHAR_PATTERN. If none of these characters 674 * are found in the number passed in, an empty string is returned. This function also attempts to 675 * strip off any alternative extensions or endings if two or more are present, such as in the case 676 * of: (530) 583-6985 x302/x2303. The second extension here makes this actually two phone numbers, 677 * (530) 583-6985 x302 and (530) 583-6985 x2303. We remove the second extension so that the first 678 * number is parsed correctly. 679 * 680 * @param number the string that might contain a phone number 681 * @return the number, stripped of any non-phone-number prefix (such as "Tel:") or an empty 682 * string if no character used to start phone numbers (such as + or any digit) is 683 * found in the number 684 */ 685 static String extractPossibleNumber(String number) { 686 Matcher m = VALID_START_CHAR_PATTERN.matcher(number); 687 if (m.find()) { 688 number = number.substring(m.start()); 689 // Remove trailing non-alpha non-numerical characters. 690 Matcher trailingCharsMatcher = UNWANTED_END_CHAR_PATTERN.matcher(number); 691 if (trailingCharsMatcher.find()) { 692 number = number.substring(0, trailingCharsMatcher.start()); 693 logger.log(Level.FINER, "Stripped trailing characters: " + number); 694 } 695 // Check for extra numbers at the end. 696 Matcher secondNumber = SECOND_NUMBER_START_PATTERN.matcher(number); 697 if (secondNumber.find()) { 698 number = number.substring(0, secondNumber.start()); 699 } 700 return number; 701 } else { 702 return ""; 703 } 704 } 705 706 /** 707 * Checks to see if the string of characters could possibly be a phone number at all. At the 708 * moment, checks to see that the string begins with at least 2 digits, ignoring any punctuation 709 * commonly found in phone numbers. 710 * This method does not require the number to be normalized in advance - but does assume that 711 * leading non-number symbols have been removed, such as by the method extractPossibleNumber. 712 * 713 * @param number string to be checked for viability as a phone number 714 * @return true if the number could be a phone number of some sort, otherwise false 715 */ 716 // @VisibleForTesting 717 static boolean isViablePhoneNumber(String number) { 718 if (number.length() < MIN_LENGTH_FOR_NSN) { 719 return false; 720 } 721 Matcher m = VALID_PHONE_NUMBER_PATTERN.matcher(number); 722 return m.matches(); 723 } 724 725 /** 726 * Normalizes a string of characters representing a phone number. This performs the following 727 * conversions: 728 * Punctuation is stripped. 729 * For ALPHA/VANITY numbers: 730 * Letters are converted to their numeric representation on a telephone keypad. The keypad 731 * used here is the one defined in ITU Recommendation E.161. This is only done if there are 732 * 3 or more letters in the number, to lessen the risk that such letters are typos. 733 * For other numbers: 734 * Wide-ascii digits are converted to normal ASCII (European) digits. 735 * Arabic-Indic numerals are converted to European numerals. 736 * Spurious alpha characters are stripped. 737 * 738 * @param number a string of characters representing a phone number 739 * @return the normalized string version of the phone number 740 */ 741 static String normalize(String number) { 742 Matcher m = VALID_ALPHA_PHONE_PATTERN.matcher(number); 743 if (m.matches()) { 744 return normalizeHelper(number, ALPHA_PHONE_MAPPINGS, true); 745 } else { 746 return normalizeDigitsOnly(number); 747 } 748 } 749 750 /** 751 * Normalizes a string of characters representing a phone number. This is a wrapper for 752 * normalize(String number) but does in-place normalization of the StringBuilder provided. 753 * 754 * @param number a StringBuilder of characters representing a phone number that will be 755 * normalized in place 756 */ 757 static void normalize(StringBuilder number) { 758 String normalizedNumber = normalize(number.toString()); 759 number.replace(0, number.length(), normalizedNumber); 760 } 761 762 /** 763 * Normalizes a string of characters representing a phone number. This converts wide-ascii and 764 * arabic-indic numerals to European numerals, and strips punctuation and alpha characters. 765 * 766 * @param number a string of characters representing a phone number 767 * @return the normalized string version of the phone number 768 */ 769 public static String normalizeDigitsOnly(String number) { 770 return normalizeDigits(number, false /* strip non-digits */).toString(); 771 } 772 773 static StringBuilder normalizeDigits(String number, boolean keepNonDigits) { 774 StringBuilder normalizedDigits = new StringBuilder(number.length()); 775 for (char c : number.toCharArray()) { 776 int digit = Character.digit(c, 10); 777 if (digit != -1) { 778 normalizedDigits.append(digit); 779 } else if (keepNonDigits) { 780 normalizedDigits.append(c); 781 } 782 } 783 return normalizedDigits; 784 } 785 786 /** 787 * Normalizes a string of characters representing a phone number. This strips all characters which 788 * are not diallable on a mobile phone keypad (including all non-ASCII digits). 789 * 790 * @param number a string of characters representing a phone number 791 * @return the normalized string version of the phone number 792 */ 793 static String normalizeDiallableCharsOnly(String number) { 794 return normalizeHelper(number, DIALLABLE_CHAR_MAPPINGS, true /* remove non matches */); 795 } 796 797 /** 798 * Converts all alpha characters in a number to their respective digits on a keypad, but retains 799 * existing formatting. 800 */ 801 public static String convertAlphaCharactersInNumber(String number) { 802 return normalizeHelper(number, ALPHA_PHONE_MAPPINGS, false); 803 } 804 805 /** 806 * Gets the length of the geographical area code from the {@code nationalNumber_} field of the 807 * PhoneNumber object passed in, so that clients could use it to split a national significant 808 * number into geographical area code and subscriber number. It works in such a way that the 809 * resultant subscriber number should be diallable, at least on some devices. An example of how 810 * this could be used: 811 * 812 * <pre> 813 * PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance(); 814 * PhoneNumber number = phoneUtil.parse("16502530000", "US"); 815 * String nationalSignificantNumber = phoneUtil.getNationalSignificantNumber(number); 816 * String areaCode; 817 * String subscriberNumber; 818 * 819 * int areaCodeLength = phoneUtil.getLengthOfGeographicalAreaCode(number); 820 * if (areaCodeLength > 0) { 821 * areaCode = nationalSignificantNumber.substring(0, areaCodeLength); 822 * subscriberNumber = nationalSignificantNumber.substring(areaCodeLength); 823 * } else { 824 * areaCode = ""; 825 * subscriberNumber = nationalSignificantNumber; 826 * } 827 * </pre> 828 * 829 * N.B.: area code is a very ambiguous concept, so the I18N team generally recommends against 830 * using it for most purposes, but recommends using the more general {@code national_number} 831 * instead. Read the following carefully before deciding to use this method: 832 * <ul> 833 * <li> geographical area codes change over time, and this method honors those changes; 834 * therefore, it doesn't guarantee the stability of the result it produces. 835 * <li> subscriber numbers may not be diallable from all devices (notably mobile devices, which 836 * typically requires the full national_number to be dialled in most regions). 837 * <li> most non-geographical numbers have no area codes, including numbers from non-geographical 838 * entities 839 * <li> some geographical numbers have no area codes. 840 * </ul> 841 * @param number the PhoneNumber object for which clients want to know the length of the area 842 * code. 843 * @return the length of area code of the PhoneNumber object passed in. 844 */ 845 public int getLengthOfGeographicalAreaCode(PhoneNumber number) { 846 PhoneMetadata metadata = getMetadataForRegion(getRegionCodeForNumber(number)); 847 if (metadata == null) { 848 return 0; 849 } 850 // If a country doesn't use a national prefix, and this number doesn't have an Italian leading 851 // zero, we assume it is a closed dialling plan with no area codes. 852 if (!metadata.hasNationalPrefix() && !number.isItalianLeadingZero()) { 853 return 0; 854 } 855 856 if (!isNumberGeographical(number)) { 857 return 0; 858 } 859 860 return getLengthOfNationalDestinationCode(number); 861 } 862 863 /** 864 * Gets the length of the national destination code (NDC) from the PhoneNumber object passed in, 865 * so that clients could use it to split a national significant number into NDC and subscriber 866 * number. The NDC of a phone number is normally the first group of digit(s) right after the 867 * country calling code when the number is formatted in the international format, if there is a 868 * subscriber number part that follows. An example of how this could be used: 869 * 870 * <pre> 871 * PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance(); 872 * PhoneNumber number = phoneUtil.parse("18002530000", "US"); 873 * String nationalSignificantNumber = phoneUtil.getNationalSignificantNumber(number); 874 * String nationalDestinationCode; 875 * String subscriberNumber; 876 * 877 * int nationalDestinationCodeLength = phoneUtil.getLengthOfNationalDestinationCode(number); 878 * if (nationalDestinationCodeLength > 0) { 879 * nationalDestinationCode = nationalSignificantNumber.substring(0, 880 * nationalDestinationCodeLength); 881 * subscriberNumber = nationalSignificantNumber.substring(nationalDestinationCodeLength); 882 * } else { 883 * nationalDestinationCode = ""; 884 * subscriberNumber = nationalSignificantNumber; 885 * } 886 * </pre> 887 * 888 * Refer to the unittests to see the difference between this function and 889 * {@link #getLengthOfGeographicalAreaCode}. 890 * 891 * @param number the PhoneNumber object for which clients want to know the length of the NDC. 892 * @return the length of NDC of the PhoneNumber object passed in. 893 */ 894 public int getLengthOfNationalDestinationCode(PhoneNumber number) { 895 PhoneNumber copiedProto; 896 if (number.hasExtension()) { 897 // We don't want to alter the proto given to us, but we don't want to include the extension 898 // when we format it, so we copy it and clear the extension here. 899 copiedProto = new PhoneNumber(); 900 copiedProto.mergeFrom(number); 901 copiedProto.clearExtension(); 902 } else { 903 copiedProto = number; 904 } 905 906 String nationalSignificantNumber = format(copiedProto, 907 PhoneNumberUtil.PhoneNumberFormat.INTERNATIONAL); 908 String[] numberGroups = NON_DIGITS_PATTERN.split(nationalSignificantNumber); 909 // The pattern will start with "+COUNTRY_CODE " so the first group will always be the empty 910 // string (before the + symbol) and the second group will be the country calling code. The third 911 // group will be area code if it is not the last group. 912 if (numberGroups.length <= 3) { 913 return 0; 914 } 915 916 if (getNumberType(number) == PhoneNumberType.MOBILE) { 917 // For example Argentinian mobile numbers, when formatted in the international format, are in 918 // the form of +54 9 NDC XXXX.... As a result, we take the length of the third group (NDC) and 919 // add the length of the second group (which is the mobile token), which also forms part of 920 // the national significant number. This assumes that the mobile token is always formatted 921 // separately from the rest of the phone number. 922 String mobileToken = getCountryMobileToken(number.getCountryCode()); 923 if (!mobileToken.equals("")) { 924 return numberGroups[2].length() + numberGroups[3].length(); 925 } 926 } 927 return numberGroups[2].length(); 928 } 929 930 /** 931 * Returns the mobile token for the provided country calling code if it has one, otherwise 932 * returns an empty string. A mobile token is a number inserted before the area code when dialing 933 * a mobile number from that country from abroad. 934 * 935 * @param countryCallingCode the country calling code for which we want the mobile token 936 * @return the mobile token, as a string, for the given country calling code 937 */ 938 public static String getCountryMobileToken(int countryCallingCode) { 939 if (MOBILE_TOKEN_MAPPINGS.containsKey(countryCallingCode)) { 940 return MOBILE_TOKEN_MAPPINGS.get(countryCallingCode); 941 } 942 return ""; 943 } 944 945 /** 946 * Normalizes a string of characters representing a phone number by replacing all characters found 947 * in the accompanying map with the values therein, and stripping all other characters if 948 * removeNonMatches is true. 949 * 950 * @param number a string of characters representing a phone number 951 * @param normalizationReplacements a mapping of characters to what they should be replaced by in 952 * the normalized version of the phone number 953 * @param removeNonMatches indicates whether characters that are not able to be replaced 954 * should be stripped from the number. If this is false, they 955 * will be left unchanged in the number. 956 * @return the normalized string version of the phone number 957 */ 958 private static String normalizeHelper(String number, 959 Map<Character, Character> normalizationReplacements, 960 boolean removeNonMatches) { 961 StringBuilder normalizedNumber = new StringBuilder(number.length()); 962 for (int i = 0; i < number.length(); i++) { 963 char character = number.charAt(i); 964 Character newDigit = normalizationReplacements.get(Character.toUpperCase(character)); 965 if (newDigit != null) { 966 normalizedNumber.append(newDigit); 967 } else if (!removeNonMatches) { 968 normalizedNumber.append(character); 969 } 970 // If neither of the above are true, we remove this character. 971 } 972 return normalizedNumber.toString(); 973 } 974 975 /** 976 * Sets or resets the PhoneNumberUtil singleton instance. If set to null, the next call to 977 * {@code getInstance()} will load (and return) the default instance. 978 */ 979 // @VisibleForTesting 980 static synchronized void setInstance(PhoneNumberUtil util) { 981 instance = util; 982 } 983 984 /** 985 * Convenience method to get a list of what regions the library has metadata for. 986 */ 987 public Set<String> getSupportedRegions() { 988 return Collections.unmodifiableSet(supportedRegions); 989 } 990 991 /** 992 * Convenience method to get a list of what global network calling codes the library has metadata 993 * for. 994 */ 995 public Set<Integer> getSupportedGlobalNetworkCallingCodes() { 996 return Collections.unmodifiableSet(countryCodesForNonGeographicalRegion); 997 } 998 999 /** 1000 * Gets a {@link PhoneNumberUtil} instance to carry out international phone number formatting, 1001 * parsing, or validation. The instance is loaded with phone number metadata for a number of most 1002 * commonly used regions. 1003 * 1004 * <p>The {@link PhoneNumberUtil} is implemented as a singleton. Therefore, calling getInstance 1005 * multiple times will only result in one instance being created. 1006 * 1007 * @return a PhoneNumberUtil instance 1008 */ 1009 public static synchronized PhoneNumberUtil getInstance() { 1010 if (instance == null) { 1011 setInstance(createInstance(DEFAULT_METADATA_LOADER)); 1012 } 1013 return instance; 1014 } 1015 1016 /** 1017 * Create a new {@link PhoneNumberUtil} instance to carry out international phone number 1018 * formatting, parsing, or validation. The instance is loaded with all metadata by 1019 * using the metadataLoader specified. 1020 * 1021 * This method should only be used in the rare case in which you want to manage your own 1022 * metadata loading. Calling this method multiple times is very expensive, as each time 1023 * a new instance is created from scratch. When in doubt, use {@link #getInstance}. 1024 * 1025 * @param metadataLoader Customized metadata loader. If null, default metadata loader will 1026 * be used. This should not be null. 1027 * @return a PhoneNumberUtil instance 1028 */ 1029 public static PhoneNumberUtil createInstance(MetadataLoader metadataLoader) { 1030 if (metadataLoader == null) { 1031 throw new IllegalArgumentException("metadataLoader could not be null."); 1032 } 1033 return new PhoneNumberUtil(META_DATA_FILE_PREFIX, metadataLoader, 1034 CountryCodeToRegionCodeMap.getCountryCodeToRegionCodeMap()); 1035 } 1036 1037 /** 1038 * Helper function to check if the national prefix formatting rule has the first group only, i.e., 1039 * does not start with the national prefix. 1040 */ 1041 static boolean formattingRuleHasFirstGroupOnly(String nationalPrefixFormattingRule) { 1042 return nationalPrefixFormattingRule.length() == 0 || 1043 FIRST_GROUP_ONLY_PREFIX_PATTERN.matcher(nationalPrefixFormattingRule).matches(); 1044 } 1045 1046 /** 1047 * Tests whether a phone number has a geographical association. It checks if the number is 1048 * associated to a certain region in the country where it belongs to. Note that this doesn't 1049 * verify if the number is actually in use. 1050 */ 1051 boolean isNumberGeographical(PhoneNumber phoneNumber) { 1052 PhoneNumberType numberType = getNumberType(phoneNumber); 1053 // TODO: Include mobile phone numbers from countries like Indonesia, which has some 1054 // mobile numbers that are geographical. 1055 return numberType == PhoneNumberType.FIXED_LINE || 1056 numberType == PhoneNumberType.FIXED_LINE_OR_MOBILE; 1057 } 1058 1059 /** 1060 * Helper function to check region code is not unknown or null. 1061 */ 1062 private boolean isValidRegionCode(String regionCode) { 1063 return regionCode != null && supportedRegions.contains(regionCode); 1064 } 1065 1066 /** 1067 * Helper function to check the country calling code is valid. 1068 */ 1069 private boolean hasValidCountryCallingCode(int countryCallingCode) { 1070 return countryCallingCodeToRegionCodeMap.containsKey(countryCallingCode); 1071 } 1072 1073 /** 1074 * Formats a phone number in the specified format using default rules. Note that this does not 1075 * promise to produce a phone number that the user can dial from where they are - although we do 1076 * format in either 'national' or 'international' format depending on what the client asks for, we 1077 * do not currently support a more abbreviated format, such as for users in the same "area" who 1078 * could potentially dial the number without area code. Note that if the phone number has a 1079 * country calling code of 0 or an otherwise invalid country calling code, we cannot work out 1080 * which formatting rules to apply so we return the national significant number with no formatting 1081 * applied. 1082 * 1083 * @param number the phone number to be formatted 1084 * @param numberFormat the format the phone number should be formatted into 1085 * @return the formatted phone number 1086 */ 1087 public String format(PhoneNumber number, PhoneNumberFormat numberFormat) { 1088 if (number.getNationalNumber() == 0 && number.hasRawInput()) { 1089 // Unparseable numbers that kept their raw input just use that. 1090 // This is the only case where a number can be formatted as E164 without a 1091 // leading '+' symbol (but the original number wasn't parseable anyway). 1092 // TODO: Consider removing the 'if' above so that unparseable 1093 // strings without raw input format to the empty string instead of "+00" 1094 String rawInput = number.getRawInput(); 1095 if (rawInput.length() > 0) { 1096 return rawInput; 1097 } 1098 } 1099 StringBuilder formattedNumber = new StringBuilder(20); 1100 format(number, numberFormat, formattedNumber); 1101 return formattedNumber.toString(); 1102 } 1103 1104 /** 1105 * Same as {@link #format(PhoneNumber, PhoneNumberFormat)}, but accepts a mutable StringBuilder as 1106 * a parameter to decrease object creation when invoked many times. 1107 */ 1108 public void format(PhoneNumber number, PhoneNumberFormat numberFormat, 1109 StringBuilder formattedNumber) { 1110 // Clear the StringBuilder first. 1111 formattedNumber.setLength(0); 1112 int countryCallingCode = number.getCountryCode(); 1113 String nationalSignificantNumber = getNationalSignificantNumber(number); 1114 if (numberFormat == PhoneNumberFormat.E164) { 1115 // Early exit for E164 case (even if the country calling code is invalid) since no formatting 1116 // of the national number needs to be applied. Extensions are not formatted. 1117 formattedNumber.append(nationalSignificantNumber); 1118 prefixNumberWithCountryCallingCode(countryCallingCode, PhoneNumberFormat.E164, 1119 formattedNumber); 1120 return; 1121 } 1122 if (!hasValidCountryCallingCode(countryCallingCode)) { 1123 formattedNumber.append(nationalSignificantNumber); 1124 return; 1125 } 1126 // Note getRegionCodeForCountryCode() is used because formatting information for regions which 1127 // share a country calling code is contained by only one region for performance reasons. For 1128 // example, for NANPA regions it will be contained in the metadata for US. 1129 String regionCode = getRegionCodeForCountryCode(countryCallingCode); 1130 // Metadata cannot be null because the country calling code is valid (which means that the 1131 // region code cannot be ZZ and must be one of our supported region codes). 1132 PhoneMetadata metadata = 1133 getMetadataForRegionOrCallingCode(countryCallingCode, regionCode); 1134 formattedNumber.append(formatNsn(nationalSignificantNumber, metadata, numberFormat)); 1135 maybeAppendFormattedExtension(number, metadata, numberFormat, formattedNumber); 1136 prefixNumberWithCountryCallingCode(countryCallingCode, numberFormat, formattedNumber); 1137 } 1138 1139 /** 1140 * Formats a phone number in the specified format using client-defined formatting rules. Note that 1141 * if the phone number has a country calling code of zero or an otherwise invalid country calling 1142 * code, we cannot work out things like whether there should be a national prefix applied, or how 1143 * to format extensions, so we return the national significant number with no formatting applied. 1144 * 1145 * @param number the phone number to be formatted 1146 * @param numberFormat the format the phone number should be formatted into 1147 * @param userDefinedFormats formatting rules specified by clients 1148 * @return the formatted phone number 1149 */ 1150 public String formatByPattern(PhoneNumber number, 1151 PhoneNumberFormat numberFormat, 1152 List<NumberFormat> userDefinedFormats) { 1153 int countryCallingCode = number.getCountryCode(); 1154 String nationalSignificantNumber = getNationalSignificantNumber(number); 1155 if (!hasValidCountryCallingCode(countryCallingCode)) { 1156 return nationalSignificantNumber; 1157 } 1158 // Note getRegionCodeForCountryCode() is used because formatting information for regions which 1159 // share a country calling code is contained by only one region for performance reasons. For 1160 // example, for NANPA regions it will be contained in the metadata for US. 1161 String regionCode = getRegionCodeForCountryCode(countryCallingCode); 1162 // Metadata cannot be null because the country calling code is valid 1163 PhoneMetadata metadata = 1164 getMetadataForRegionOrCallingCode(countryCallingCode, regionCode); 1165 1166 StringBuilder formattedNumber = new StringBuilder(20); 1167 1168 NumberFormat formattingPattern = 1169 chooseFormattingPatternForNumber(userDefinedFormats, nationalSignificantNumber); 1170 if (formattingPattern == null) { 1171 // If no pattern above is matched, we format the number as a whole. 1172 formattedNumber.append(nationalSignificantNumber); 1173 } else { 1174 NumberFormat numFormatCopy = new NumberFormat(); 1175 // Before we do a replacement of the national prefix pattern $NP with the national prefix, we 1176 // need to copy the rule so that subsequent replacements for different numbers have the 1177 // appropriate national prefix. 1178 numFormatCopy.mergeFrom(formattingPattern); 1179 String nationalPrefixFormattingRule = formattingPattern.getNationalPrefixFormattingRule(); 1180 if (nationalPrefixFormattingRule.length() > 0) { 1181 String nationalPrefix = metadata.getNationalPrefix(); 1182 if (nationalPrefix.length() > 0) { 1183 // Replace $NP with national prefix and $FG with the first group ($1). 1184 nationalPrefixFormattingRule = 1185 NP_PATTERN.matcher(nationalPrefixFormattingRule).replaceFirst(nationalPrefix); 1186 nationalPrefixFormattingRule = 1187 FG_PATTERN.matcher(nationalPrefixFormattingRule).replaceFirst("\\$1"); 1188 numFormatCopy.setNationalPrefixFormattingRule(nationalPrefixFormattingRule); 1189 } else { 1190 // We don't want to have a rule for how to format the national prefix if there isn't one. 1191 numFormatCopy.clearNationalPrefixFormattingRule(); 1192 } 1193 } 1194 formattedNumber.append( 1195 formatNsnUsingPattern(nationalSignificantNumber, numFormatCopy, numberFormat)); 1196 } 1197 maybeAppendFormattedExtension(number, metadata, numberFormat, formattedNumber); 1198 prefixNumberWithCountryCallingCode(countryCallingCode, numberFormat, formattedNumber); 1199 return formattedNumber.toString(); 1200 } 1201 1202 /** 1203 * Formats a phone number in national format for dialing using the carrier as specified in the 1204 * {@code carrierCode}. The {@code carrierCode} will always be used regardless of whether the 1205 * phone number already has a preferred domestic carrier code stored. If {@code carrierCode} 1206 * contains an empty string, returns the number in national format without any carrier code. 1207 * 1208 * @param number the phone number to be formatted 1209 * @param carrierCode the carrier selection code to be used 1210 * @return the formatted phone number in national format for dialing using the carrier as 1211 * specified in the {@code carrierCode} 1212 */ 1213 public String formatNationalNumberWithCarrierCode(PhoneNumber number, String carrierCode) { 1214 int countryCallingCode = number.getCountryCode(); 1215 String nationalSignificantNumber = getNationalSignificantNumber(number); 1216 if (!hasValidCountryCallingCode(countryCallingCode)) { 1217 return nationalSignificantNumber; 1218 } 1219 1220 // Note getRegionCodeForCountryCode() is used because formatting information for regions which 1221 // share a country calling code is contained by only one region for performance reasons. For 1222 // example, for NANPA regions it will be contained in the metadata for US. 1223 String regionCode = getRegionCodeForCountryCode(countryCallingCode); 1224 // Metadata cannot be null because the country calling code is valid. 1225 PhoneMetadata metadata = getMetadataForRegionOrCallingCode(countryCallingCode, regionCode); 1226 1227 StringBuilder formattedNumber = new StringBuilder(20); 1228 formattedNumber.append(formatNsn(nationalSignificantNumber, metadata, 1229 PhoneNumberFormat.NATIONAL, carrierCode)); 1230 maybeAppendFormattedExtension(number, metadata, PhoneNumberFormat.NATIONAL, formattedNumber); 1231 prefixNumberWithCountryCallingCode(countryCallingCode, PhoneNumberFormat.NATIONAL, 1232 formattedNumber); 1233 return formattedNumber.toString(); 1234 } 1235 1236 private PhoneMetadata getMetadataForRegionOrCallingCode( 1237 int countryCallingCode, String regionCode) { 1238 return REGION_CODE_FOR_NON_GEO_ENTITY.equals(regionCode) 1239 ? getMetadataForNonGeographicalRegion(countryCallingCode) 1240 : getMetadataForRegion(regionCode); 1241 } 1242 1243 /** 1244 * Formats a phone number in national format for dialing using the carrier as specified in the 1245 * preferredDomesticCarrierCode field of the PhoneNumber object passed in. If that is missing, 1246 * use the {@code fallbackCarrierCode} passed in instead. If there is no 1247 * {@code preferredDomesticCarrierCode}, and the {@code fallbackCarrierCode} contains an empty 1248 * string, return the number in national format without any carrier code. 1249 * 1250 * <p>Use {@link #formatNationalNumberWithCarrierCode} instead if the carrier code passed in 1251 * should take precedence over the number's {@code preferredDomesticCarrierCode} when formatting. 1252 * 1253 * @param number the phone number to be formatted 1254 * @param fallbackCarrierCode the carrier selection code to be used, if none is found in the 1255 * phone number itself 1256 * @return the formatted phone number in national format for dialing using the number's 1257 * {@code preferredDomesticCarrierCode}, or the {@code fallbackCarrierCode} passed in if 1258 * none is found 1259 */ 1260 public String formatNationalNumberWithPreferredCarrierCode(PhoneNumber number, 1261 String fallbackCarrierCode) { 1262 return formatNationalNumberWithCarrierCode(number, number.hasPreferredDomesticCarrierCode() 1263 ? number.getPreferredDomesticCarrierCode() 1264 : fallbackCarrierCode); 1265 } 1266 1267 /** 1268 * Returns a number formatted in such a way that it can be dialed from a mobile phone in a 1269 * specific region. If the number cannot be reached from the region (e.g. some countries block 1270 * toll-free numbers from being called outside of the country), the method returns an empty 1271 * string. 1272 * 1273 * @param number the phone number to be formatted 1274 * @param regionCallingFrom the region where the call is being placed 1275 * @param withFormatting whether the number should be returned with formatting symbols, such as 1276 * spaces and dashes. 1277 * @return the formatted phone number 1278 */ 1279 public String formatNumberForMobileDialing(PhoneNumber number, String regionCallingFrom, 1280 boolean withFormatting) { 1281 int countryCallingCode = number.getCountryCode(); 1282 if (!hasValidCountryCallingCode(countryCallingCode)) { 1283 return number.hasRawInput() ? number.getRawInput() : ""; 1284 } 1285 1286 String formattedNumber = ""; 1287 // Clear the extension, as that part cannot normally be dialed together with the main number. 1288 PhoneNumber numberNoExt = new PhoneNumber().mergeFrom(number).clearExtension(); 1289 String regionCode = getRegionCodeForCountryCode(countryCallingCode); 1290 PhoneNumberType numberType = getNumberType(numberNoExt); 1291 boolean isValidNumber = (numberType != PhoneNumberType.UNKNOWN); 1292 if (regionCallingFrom.equals(regionCode)) { 1293 boolean isFixedLineOrMobile = 1294 (numberType == PhoneNumberType.FIXED_LINE) || (numberType == PhoneNumberType.MOBILE) || 1295 (numberType == PhoneNumberType.FIXED_LINE_OR_MOBILE); 1296 // Carrier codes may be needed in some countries. We handle this here. 1297 if (regionCode.equals("CO") && numberType == PhoneNumberType.FIXED_LINE) { 1298 formattedNumber = 1299 formatNationalNumberWithCarrierCode(numberNoExt, COLOMBIA_MOBILE_TO_FIXED_LINE_PREFIX); 1300 } else if (regionCode.equals("BR") && isFixedLineOrMobile) { 1301 formattedNumber = numberNoExt.hasPreferredDomesticCarrierCode() 1302 ? formattedNumber = formatNationalNumberWithPreferredCarrierCode(numberNoExt, "") 1303 // Brazilian fixed line and mobile numbers need to be dialed with a carrier code when 1304 // called within Brazil. Without that, most of the carriers won't connect the call. 1305 // Because of that, we return an empty string here. 1306 : ""; 1307 } else if (isValidNumber && regionCode.equals("HU")) { 1308 // The national format for HU numbers doesn't contain the national prefix, because that is 1309 // how numbers are normally written down. However, the national prefix is obligatory when 1310 // dialing from a mobile phone, except for short numbers. As a result, we add it back here 1311 // if it is a valid regular length phone number. 1312 formattedNumber = 1313 getNddPrefixForRegion(regionCode, true /* strip non-digits */) + 1314 " " + format(numberNoExt, PhoneNumberFormat.NATIONAL); 1315 } else if (countryCallingCode == NANPA_COUNTRY_CODE) { 1316 // For NANPA countries, we output international format for numbers that can be dialed 1317 // internationally, since that always works, except for numbers which might potentially be 1318 // short numbers, which are always dialled in national format. 1319 PhoneMetadata regionMetadata = getMetadataForRegion(regionCallingFrom); 1320 if (canBeInternationallyDialled(numberNoExt) && 1321 !isShorterThanPossibleNormalNumber(regionMetadata, 1322 getNationalSignificantNumber(numberNoExt))) { 1323 formattedNumber = format(numberNoExt, PhoneNumberFormat.INTERNATIONAL); 1324 } else { 1325 formattedNumber = format(numberNoExt, PhoneNumberFormat.NATIONAL); 1326 } 1327 } else { 1328 // For non-geographical countries, and Mexican and Chilean fixed line and mobile numbers, we 1329 // output international format for numbers that can be dialed internationally as that always 1330 // works. 1331 if ((regionCode.equals(REGION_CODE_FOR_NON_GEO_ENTITY) || 1332 // MX fixed line and mobile numbers should always be formatted in international format, 1333 // even when dialed within MX. For national format to work, a carrier code needs to be 1334 // used, and the correct carrier code depends on if the caller and callee are from the 1335 // same local area. It is trickier to get that to work correctly than using 1336 // international format, which is tested to work fine on all carriers. 1337 // CL fixed line numbers need the national prefix when dialing in the national format, 1338 // but don't have it when used for display. The reverse is true for mobile numbers. 1339 // As a result, we output them in the international format to make it work. 1340 ((regionCode.equals("MX") || regionCode.equals("CL")) && isFixedLineOrMobile)) && 1341 canBeInternationallyDialled(numberNoExt)) { 1342 formattedNumber = format(numberNoExt, PhoneNumberFormat.INTERNATIONAL); 1343 } else { 1344 formattedNumber = format(numberNoExt, PhoneNumberFormat.NATIONAL); 1345 } 1346 } 1347 } else if (isValidNumber && canBeInternationallyDialled(numberNoExt)) { 1348 // We assume that short numbers are not diallable from outside their region, so if a number 1349 // is not a valid regular length phone number, we treat it as if it cannot be internationally 1350 // dialled. 1351 return withFormatting ? format(numberNoExt, PhoneNumberFormat.INTERNATIONAL) 1352 : format(numberNoExt, PhoneNumberFormat.E164); 1353 } 1354 return withFormatting ? formattedNumber 1355 : normalizeDiallableCharsOnly(formattedNumber); 1356 } 1357 1358 /** 1359 * Formats a phone number for out-of-country dialing purposes. If no regionCallingFrom is 1360 * supplied, we format the number in its INTERNATIONAL format. If the country calling code is the 1361 * same as that of the region where the number is from, then NATIONAL formatting will be applied. 1362 * 1363 * <p>If the number itself has a country calling code of zero or an otherwise invalid country 1364 * calling code, then we return the number with no formatting applied. 1365 * 1366 * <p>Note this function takes care of the case for calling inside of NANPA and between Russia and 1367 * Kazakhstan (who share the same country calling code). In those cases, no international prefix 1368 * is used. For regions which have multiple international prefixes, the number in its 1369 * INTERNATIONAL format will be returned instead. 1370 * 1371 * @param number the phone number to be formatted 1372 * @param regionCallingFrom the region where the call is being placed 1373 * @return the formatted phone number 1374 */ 1375 public String formatOutOfCountryCallingNumber(PhoneNumber number, 1376 String regionCallingFrom) { 1377 if (!isValidRegionCode(regionCallingFrom)) { 1378 logger.log(Level.WARNING, 1379 "Trying to format number from invalid region " 1380 + regionCallingFrom 1381 + ". International formatting applied."); 1382 return format(number, PhoneNumberFormat.INTERNATIONAL); 1383 } 1384 int countryCallingCode = number.getCountryCode(); 1385 String nationalSignificantNumber = getNationalSignificantNumber(number); 1386 if (!hasValidCountryCallingCode(countryCallingCode)) { 1387 return nationalSignificantNumber; 1388 } 1389 if (countryCallingCode == NANPA_COUNTRY_CODE) { 1390 if (isNANPACountry(regionCallingFrom)) { 1391 // For NANPA regions, return the national format for these regions but prefix it with the 1392 // country calling code. 1393 return countryCallingCode + " " + format(number, PhoneNumberFormat.NATIONAL); 1394 } 1395 } else if (countryCallingCode == getCountryCodeForValidRegion(regionCallingFrom)) { 1396 // If regions share a country calling code, the country calling code need not be dialled. 1397 // This also applies when dialling within a region, so this if clause covers both these cases. 1398 // Technically this is the case for dialling from La Reunion to other overseas departments of 1399 // France (French Guiana, Martinique, Guadeloupe), but not vice versa - so we don't cover this 1400 // edge case for now and for those cases return the version including country calling code. 1401 // Details here: http://www.petitfute.com/voyage/225-info-pratiques-reunion 1402 return format(number, PhoneNumberFormat.NATIONAL); 1403 } 1404 // Metadata cannot be null because we checked 'isValidRegionCode()' above. 1405 PhoneMetadata metadataForRegionCallingFrom = getMetadataForRegion(regionCallingFrom); 1406 String internationalPrefix = metadataForRegionCallingFrom.getInternationalPrefix(); 1407 1408 // For regions that have multiple international prefixes, the international format of the 1409 // number is returned, unless there is a preferred international prefix. 1410 String internationalPrefixForFormatting = ""; 1411 if (UNIQUE_INTERNATIONAL_PREFIX.matcher(internationalPrefix).matches()) { 1412 internationalPrefixForFormatting = internationalPrefix; 1413 } else if (metadataForRegionCallingFrom.hasPreferredInternationalPrefix()) { 1414 internationalPrefixForFormatting = 1415 metadataForRegionCallingFrom.getPreferredInternationalPrefix(); 1416 } 1417 1418 String regionCode = getRegionCodeForCountryCode(countryCallingCode); 1419 // Metadata cannot be null because the country calling code is valid. 1420 PhoneMetadata metadataForRegion = 1421 getMetadataForRegionOrCallingCode(countryCallingCode, regionCode); 1422 String formattedNationalNumber = 1423 formatNsn(nationalSignificantNumber, metadataForRegion, PhoneNumberFormat.INTERNATIONAL); 1424 StringBuilder formattedNumber = new StringBuilder(formattedNationalNumber); 1425 maybeAppendFormattedExtension(number, metadataForRegion, PhoneNumberFormat.INTERNATIONAL, 1426 formattedNumber); 1427 if (internationalPrefixForFormatting.length() > 0) { 1428 formattedNumber.insert(0, " ").insert(0, countryCallingCode).insert(0, " ") 1429 .insert(0, internationalPrefixForFormatting); 1430 } else { 1431 prefixNumberWithCountryCallingCode(countryCallingCode, 1432 PhoneNumberFormat.INTERNATIONAL, 1433 formattedNumber); 1434 } 1435 return formattedNumber.toString(); 1436 } 1437 1438 /** 1439 * Formats a phone number using the original phone number format that the number is parsed from. 1440 * The original format is embedded in the country_code_source field of the PhoneNumber object 1441 * passed in. If such information is missing, the number will be formatted into the NATIONAL 1442 * format by default. When the number contains a leading zero and this is unexpected for this 1443 * country, or we don't have a formatting pattern for the number, the method returns the raw input 1444 * when it is available. 1445 * 1446 * Note this method guarantees no digit will be inserted, removed or modified as a result of 1447 * formatting. 1448 * 1449 * @param number the phone number that needs to be formatted in its original number format 1450 * @param regionCallingFrom the region whose IDD needs to be prefixed if the original number 1451 * has one 1452 * @return the formatted phone number in its original number format 1453 */ 1454 public String formatInOriginalFormat(PhoneNumber number, String regionCallingFrom) { 1455 if (number.hasRawInput() && 1456 (hasUnexpectedItalianLeadingZero(number) || !hasFormattingPatternForNumber(number))) { 1457 // We check if we have the formatting pattern because without that, we might format the number 1458 // as a group without national prefix. 1459 return number.getRawInput(); 1460 } 1461 if (!number.hasCountryCodeSource()) { 1462 return format(number, PhoneNumberFormat.NATIONAL); 1463 } 1464 String formattedNumber; 1465 switch (number.getCountryCodeSource()) { 1466 case FROM_NUMBER_WITH_PLUS_SIGN: 1467 formattedNumber = format(number, PhoneNumberFormat.INTERNATIONAL); 1468 break; 1469 case FROM_NUMBER_WITH_IDD: 1470 formattedNumber = formatOutOfCountryCallingNumber(number, regionCallingFrom); 1471 break; 1472 case FROM_NUMBER_WITHOUT_PLUS_SIGN: 1473 formattedNumber = format(number, PhoneNumberFormat.INTERNATIONAL).substring(1); 1474 break; 1475 case FROM_DEFAULT_COUNTRY: 1476 // Fall-through to default case. 1477 default: 1478 String regionCode = getRegionCodeForCountryCode(number.getCountryCode()); 1479 // We strip non-digits from the NDD here, and from the raw input later, so that we can 1480 // compare them easily. 1481 String nationalPrefix = getNddPrefixForRegion(regionCode, true /* strip non-digits */); 1482 String nationalFormat = format(number, PhoneNumberFormat.NATIONAL); 1483 if (nationalPrefix == null || nationalPrefix.length() == 0) { 1484 // If the region doesn't have a national prefix at all, we can safely return the national 1485 // format without worrying about a national prefix being added. 1486 formattedNumber = nationalFormat; 1487 break; 1488 } 1489 // Otherwise, we check if the original number was entered with a national prefix. 1490 if (rawInputContainsNationalPrefix( 1491 number.getRawInput(), nationalPrefix, regionCode)) { 1492 // If so, we can safely return the national format. 1493 formattedNumber = nationalFormat; 1494 break; 1495 } 1496 // Metadata cannot be null here because getNddPrefixForRegion() (above) returns null if 1497 // there is no metadata for the region. 1498 PhoneMetadata metadata = getMetadataForRegion(regionCode); 1499 String nationalNumber = getNationalSignificantNumber(number); 1500 NumberFormat formatRule = 1501 chooseFormattingPatternForNumber(metadata.numberFormats(), nationalNumber); 1502 // The format rule could still be null here if the national number was 0 and there was no 1503 // raw input (this should not be possible for numbers generated by the phonenumber library 1504 // as they would also not have a country calling code and we would have exited earlier). 1505 if (formatRule == null) { 1506 formattedNumber = nationalFormat; 1507 break; 1508 } 1509 // When the format we apply to this number doesn't contain national prefix, we can just 1510 // return the national format. 1511 // TODO: Refactor the code below with the code in isNationalPrefixPresentIfRequired. 1512 String candidateNationalPrefixRule = formatRule.getNationalPrefixFormattingRule(); 1513 // We assume that the first-group symbol will never be _before_ the national prefix. 1514 int indexOfFirstGroup = candidateNationalPrefixRule.indexOf("$1"); 1515 if (indexOfFirstGroup <= 0) { 1516 formattedNumber = nationalFormat; 1517 break; 1518 } 1519 candidateNationalPrefixRule = 1520 candidateNationalPrefixRule.substring(0, indexOfFirstGroup); 1521 candidateNationalPrefixRule = normalizeDigitsOnly(candidateNationalPrefixRule); 1522 if (candidateNationalPrefixRule.length() == 0) { 1523 // National prefix not used when formatting this number. 1524 formattedNumber = nationalFormat; 1525 break; 1526 } 1527 // Otherwise, we need to remove the national prefix from our output. 1528 NumberFormat numFormatCopy = new NumberFormat(); 1529 numFormatCopy.mergeFrom(formatRule); 1530 numFormatCopy.clearNationalPrefixFormattingRule(); 1531 List<NumberFormat> numberFormats = new ArrayList<NumberFormat>(1); 1532 numberFormats.add(numFormatCopy); 1533 formattedNumber = formatByPattern(number, PhoneNumberFormat.NATIONAL, numberFormats); 1534 break; 1535 } 1536 String rawInput = number.getRawInput(); 1537 // If no digit is inserted/removed/modified as a result of our formatting, we return the 1538 // formatted phone number; otherwise we return the raw input the user entered. 1539 if (formattedNumber != null && rawInput.length() > 0) { 1540 String normalizedFormattedNumber = normalizeDiallableCharsOnly(formattedNumber); 1541 String normalizedRawInput = normalizeDiallableCharsOnly(rawInput); 1542 if (!normalizedFormattedNumber.equals(normalizedRawInput)) { 1543 formattedNumber = rawInput; 1544 } 1545 } 1546 return formattedNumber; 1547 } 1548 1549 // Check if rawInput, which is assumed to be in the national format, has a national prefix. The 1550 // national prefix is assumed to be in digits-only form. 1551 private boolean rawInputContainsNationalPrefix(String rawInput, String nationalPrefix, 1552 String regionCode) { 1553 String normalizedNationalNumber = normalizeDigitsOnly(rawInput); 1554 if (normalizedNationalNumber.startsWith(nationalPrefix)) { 1555 try { 1556 // Some Japanese numbers (e.g. 00777123) might be mistaken to contain the national prefix 1557 // when written without it (e.g. 0777123) if we just do prefix matching. To tackle that, we 1558 // check the validity of the number if the assumed national prefix is removed (777123 won't 1559 // be valid in Japan). 1560 return isValidNumber( 1561 parse(normalizedNationalNumber.substring(nationalPrefix.length()), regionCode)); 1562 } catch (NumberParseException e) { 1563 return false; 1564 } 1565 } 1566 return false; 1567 } 1568 1569 /** 1570 * Returns true if a number is from a region whose national significant number couldn't contain a 1571 * leading zero, but has the italian_leading_zero field set to true. 1572 */ 1573 private boolean hasUnexpectedItalianLeadingZero(PhoneNumber number) { 1574 return number.isItalianLeadingZero() && !isLeadingZeroPossible(number.getCountryCode()); 1575 } 1576 1577 private boolean hasFormattingPatternForNumber(PhoneNumber number) { 1578 int countryCallingCode = number.getCountryCode(); 1579 String phoneNumberRegion = getRegionCodeForCountryCode(countryCallingCode); 1580 PhoneMetadata metadata = 1581 getMetadataForRegionOrCallingCode(countryCallingCode, phoneNumberRegion); 1582 if (metadata == null) { 1583 return false; 1584 } 1585 String nationalNumber = getNationalSignificantNumber(number); 1586 NumberFormat formatRule = 1587 chooseFormattingPatternForNumber(metadata.numberFormats(), nationalNumber); 1588 return formatRule != null; 1589 } 1590 1591 /** 1592 * Formats a phone number for out-of-country dialing purposes. 1593 * 1594 * Note that in this version, if the number was entered originally using alpha characters and 1595 * this version of the number is stored in raw_input, this representation of the number will be 1596 * used rather than the digit representation. Grouping information, as specified by characters 1597 * such as "-" and " ", will be retained. 1598 * 1599 * <p><b>Caveats:</b></p> 1600 * <ul> 1601 * <li> This will not produce good results if the country calling code is both present in the raw 1602 * input _and_ is the start of the national number. This is not a problem in the regions 1603 * which typically use alpha numbers. 1604 * <li> This will also not produce good results if the raw input has any grouping information 1605 * within the first three digits of the national number, and if the function needs to strip 1606 * preceding digits/words in the raw input before these digits. Normally people group the 1607 * first three digits together so this is not a huge problem - and will be fixed if it 1608 * proves to be so. 1609 * </ul> 1610 * 1611 * @param number the phone number that needs to be formatted 1612 * @param regionCallingFrom the region where the call is being placed 1613 * @return the formatted phone number 1614 */ 1615 public String formatOutOfCountryKeepingAlphaChars(PhoneNumber number, 1616 String regionCallingFrom) { 1617 String rawInput = number.getRawInput(); 1618 // If there is no raw input, then we can't keep alpha characters because there aren't any. 1619 // In this case, we return formatOutOfCountryCallingNumber. 1620 if (rawInput.length() == 0) { 1621 return formatOutOfCountryCallingNumber(number, regionCallingFrom); 1622 } 1623 int countryCode = number.getCountryCode(); 1624 if (!hasValidCountryCallingCode(countryCode)) { 1625 return rawInput; 1626 } 1627 // Strip any prefix such as country calling code, IDD, that was present. We do this by comparing 1628 // the number in raw_input with the parsed number. 1629 // To do this, first we normalize punctuation. We retain number grouping symbols such as " " 1630 // only. 1631 rawInput = normalizeHelper(rawInput, ALL_PLUS_NUMBER_GROUPING_SYMBOLS, true); 1632 // Now we trim everything before the first three digits in the parsed number. We choose three 1633 // because all valid alpha numbers have 3 digits at the start - if it does not, then we don't 1634 // trim anything at all. Similarly, if the national number was less than three digits, we don't 1635 // trim anything at all. 1636 String nationalNumber = getNationalSignificantNumber(number); 1637 if (nationalNumber.length() > 3) { 1638 int firstNationalNumberDigit = rawInput.indexOf(nationalNumber.substring(0, 3)); 1639 if (firstNationalNumberDigit != -1) { 1640 rawInput = rawInput.substring(firstNationalNumberDigit); 1641 } 1642 } 1643 PhoneMetadata metadataForRegionCallingFrom = getMetadataForRegion(regionCallingFrom); 1644 if (countryCode == NANPA_COUNTRY_CODE) { 1645 if (isNANPACountry(regionCallingFrom)) { 1646 return countryCode + " " + rawInput; 1647 } 1648 } else if (metadataForRegionCallingFrom != null && 1649 countryCode == getCountryCodeForValidRegion(regionCallingFrom)) { 1650 NumberFormat formattingPattern = 1651 chooseFormattingPatternForNumber(metadataForRegionCallingFrom.numberFormats(), 1652 nationalNumber); 1653 if (formattingPattern == null) { 1654 // If no pattern above is matched, we format the original input. 1655 return rawInput; 1656 } 1657 NumberFormat newFormat = new NumberFormat(); 1658 newFormat.mergeFrom(formattingPattern); 1659 // The first group is the first group of digits that the user wrote together. 1660 newFormat.setPattern("(\\d+)(.*)"); 1661 // Here we just concatenate them back together after the national prefix has been fixed. 1662 newFormat.setFormat("$1$2"); 1663 // Now we format using this pattern instead of the default pattern, but with the national 1664 // prefix prefixed if necessary. 1665 // This will not work in the cases where the pattern (and not the leading digits) decide 1666 // whether a national prefix needs to be used, since we have overridden the pattern to match 1667 // anything, but that is not the case in the metadata to date. 1668 return formatNsnUsingPattern(rawInput, newFormat, PhoneNumberFormat.NATIONAL); 1669 } 1670 String internationalPrefixForFormatting = ""; 1671 // If an unsupported region-calling-from is entered, or a country with multiple international 1672 // prefixes, the international format of the number is returned, unless there is a preferred 1673 // international prefix. 1674 if (metadataForRegionCallingFrom != null) { 1675 String internationalPrefix = metadataForRegionCallingFrom.getInternationalPrefix(); 1676 internationalPrefixForFormatting = 1677 UNIQUE_INTERNATIONAL_PREFIX.matcher(internationalPrefix).matches() 1678 ? internationalPrefix 1679 : metadataForRegionCallingFrom.getPreferredInternationalPrefix(); 1680 } 1681 StringBuilder formattedNumber = new StringBuilder(rawInput); 1682 String regionCode = getRegionCodeForCountryCode(countryCode); 1683 // Metadata cannot be null because the country calling code is valid. 1684 PhoneMetadata metadataForRegion = getMetadataForRegionOrCallingCode(countryCode, regionCode); 1685 maybeAppendFormattedExtension(number, metadataForRegion, 1686 PhoneNumberFormat.INTERNATIONAL, formattedNumber); 1687 if (internationalPrefixForFormatting.length() > 0) { 1688 formattedNumber.insert(0, " ").insert(0, countryCode).insert(0, " ") 1689 .insert(0, internationalPrefixForFormatting); 1690 } else { 1691 // Invalid region entered as country-calling-from (so no metadata was found for it) or the 1692 // region chosen has multiple international dialling prefixes. 1693 logger.log(Level.WARNING, 1694 "Trying to format number from invalid region " 1695 + regionCallingFrom 1696 + ". International formatting applied."); 1697 prefixNumberWithCountryCallingCode(countryCode, 1698 PhoneNumberFormat.INTERNATIONAL, 1699 formattedNumber); 1700 } 1701 return formattedNumber.toString(); 1702 } 1703 1704 /** 1705 * Gets the national significant number of the a phone number. Note a national significant number 1706 * doesn't contain a national prefix or any formatting. 1707 * 1708 * @param number the phone number for which the national significant number is needed 1709 * @return the national significant number of the PhoneNumber object passed in 1710 */ 1711 public String getNationalSignificantNumber(PhoneNumber number) { 1712 // If leading zero(s) have been set, we prefix this now. Note this is not a national prefix. 1713 StringBuilder nationalNumber = new StringBuilder(); 1714 if (number.isItalianLeadingZero()) { 1715 char[] zeros = new char[number.getNumberOfLeadingZeros()]; 1716 Arrays.fill(zeros, '0'); 1717 nationalNumber.append(new String(zeros)); 1718 } 1719 nationalNumber.append(number.getNationalNumber()); 1720 return nationalNumber.toString(); 1721 } 1722 1723 /** 1724 * A helper function that is used by format and formatByPattern. 1725 */ 1726 private void prefixNumberWithCountryCallingCode(int countryCallingCode, 1727 PhoneNumberFormat numberFormat, 1728 StringBuilder formattedNumber) { 1729 switch (numberFormat) { 1730 case E164: 1731 formattedNumber.insert(0, countryCallingCode).insert(0, PLUS_SIGN); 1732 return; 1733 case INTERNATIONAL: 1734 formattedNumber.insert(0, " ").insert(0, countryCallingCode).insert(0, PLUS_SIGN); 1735 return; 1736 case RFC3966: 1737 formattedNumber.insert(0, "-").insert(0, countryCallingCode).insert(0, PLUS_SIGN) 1738 .insert(0, RFC3966_PREFIX); 1739 return; 1740 case NATIONAL: 1741 default: 1742 return; 1743 } 1744 } 1745 1746 // Simple wrapper of formatNsn for the common case of no carrier code. 1747 private String formatNsn(String number, PhoneMetadata metadata, PhoneNumberFormat numberFormat) { 1748 return formatNsn(number, metadata, numberFormat, null); 1749 } 1750 1751 // Note in some regions, the national number can be written in two completely different ways 1752 // depending on whether it forms part of the NATIONAL format or INTERNATIONAL format. The 1753 // numberFormat parameter here is used to specify which format to use for those cases. If a 1754 // carrierCode is specified, this will be inserted into the formatted string to replace $CC. 1755 private String formatNsn(String number, 1756 PhoneMetadata metadata, 1757 PhoneNumberFormat numberFormat, 1758 String carrierCode) { 1759 List<NumberFormat> intlNumberFormats = metadata.intlNumberFormats(); 1760 // When the intlNumberFormats exists, we use that to format national number for the 1761 // INTERNATIONAL format instead of using the numberDesc.numberFormats. 1762 List<NumberFormat> availableFormats = 1763 (intlNumberFormats.size() == 0 || numberFormat == PhoneNumberFormat.NATIONAL) 1764 ? metadata.numberFormats() 1765 : metadata.intlNumberFormats(); 1766 NumberFormat formattingPattern = chooseFormattingPatternForNumber(availableFormats, number); 1767 return (formattingPattern == null) 1768 ? number 1769 : formatNsnUsingPattern(number, formattingPattern, numberFormat, carrierCode); 1770 } 1771 1772 NumberFormat chooseFormattingPatternForNumber(List<NumberFormat> availableFormats, 1773 String nationalNumber) { 1774 for (NumberFormat numFormat : availableFormats) { 1775 int size = numFormat.leadingDigitsPatternSize(); 1776 if (size == 0 || regexCache.getPatternForRegex( 1777 // We always use the last leading_digits_pattern, as it is the most detailed. 1778 numFormat.getLeadingDigitsPattern(size - 1)).matcher(nationalNumber).lookingAt()) { 1779 Matcher m = regexCache.getPatternForRegex(numFormat.getPattern()).matcher(nationalNumber); 1780 if (m.matches()) { 1781 return numFormat; 1782 } 1783 } 1784 } 1785 return null; 1786 } 1787 1788 // Simple wrapper of formatNsnUsingPattern for the common case of no carrier code. 1789 String formatNsnUsingPattern(String nationalNumber, 1790 NumberFormat formattingPattern, 1791 PhoneNumberFormat numberFormat) { 1792 return formatNsnUsingPattern(nationalNumber, formattingPattern, numberFormat, null); 1793 } 1794 1795 // Note that carrierCode is optional - if null or an empty string, no carrier code replacement 1796 // will take place. 1797 private String formatNsnUsingPattern(String nationalNumber, 1798 NumberFormat formattingPattern, 1799 PhoneNumberFormat numberFormat, 1800 String carrierCode) { 1801 String numberFormatRule = formattingPattern.getFormat(); 1802 Matcher m = 1803 regexCache.getPatternForRegex(formattingPattern.getPattern()).matcher(nationalNumber); 1804 String formattedNationalNumber = ""; 1805 if (numberFormat == PhoneNumberFormat.NATIONAL && 1806 carrierCode != null && carrierCode.length() > 0 && 1807 formattingPattern.getDomesticCarrierCodeFormattingRule().length() > 0) { 1808 // Replace the $CC in the formatting rule with the desired carrier code. 1809 String carrierCodeFormattingRule = formattingPattern.getDomesticCarrierCodeFormattingRule(); 1810 carrierCodeFormattingRule = 1811 CC_PATTERN.matcher(carrierCodeFormattingRule).replaceFirst(carrierCode); 1812 // Now replace the $FG in the formatting rule with the first group and the carrier code 1813 // combined in the appropriate way. 1814 numberFormatRule = FIRST_GROUP_PATTERN.matcher(numberFormatRule) 1815 .replaceFirst(carrierCodeFormattingRule); 1816 formattedNationalNumber = m.replaceAll(numberFormatRule); 1817 } else { 1818 // Use the national prefix formatting rule instead. 1819 String nationalPrefixFormattingRule = formattingPattern.getNationalPrefixFormattingRule(); 1820 if (numberFormat == PhoneNumberFormat.NATIONAL && 1821 nationalPrefixFormattingRule != null && 1822 nationalPrefixFormattingRule.length() > 0) { 1823 Matcher firstGroupMatcher = FIRST_GROUP_PATTERN.matcher(numberFormatRule); 1824 formattedNationalNumber = 1825 m.replaceAll(firstGroupMatcher.replaceFirst(nationalPrefixFormattingRule)); 1826 } else { 1827 formattedNationalNumber = m.replaceAll(numberFormatRule); 1828 } 1829 } 1830 if (numberFormat == PhoneNumberFormat.RFC3966) { 1831 // Strip any leading punctuation. 1832 Matcher matcher = SEPARATOR_PATTERN.matcher(formattedNationalNumber); 1833 if (matcher.lookingAt()) { 1834 formattedNationalNumber = matcher.replaceFirst(""); 1835 } 1836 // Replace the rest with a dash between each number group. 1837 formattedNationalNumber = matcher.reset(formattedNationalNumber).replaceAll("-"); 1838 } 1839 return formattedNationalNumber; 1840 } 1841 1842 /** 1843 * Gets a valid number for the specified region. 1844 * 1845 * @param regionCode the region for which an example number is needed 1846 * @return a valid fixed-line number for the specified region. Returns null when the metadata 1847 * does not contain such information, or the region 001 is passed in. For 001 (representing 1848 * non-geographical numbers), call {@link #getExampleNumberForNonGeoEntity} instead. 1849 */ 1850 public PhoneNumber getExampleNumber(String regionCode) { 1851 return getExampleNumberForType(regionCode, PhoneNumberType.FIXED_LINE); 1852 } 1853 1854 /** 1855 * Gets a valid number for the specified region and number type. 1856 * 1857 * @param regionCode the region for which an example number is needed 1858 * @param type the type of number that is needed 1859 * @return a valid number for the specified region and type. Returns null when the metadata 1860 * does not contain such information or if an invalid region or region 001 was entered. 1861 * For 001 (representing non-geographical numbers), call 1862 * {@link #getExampleNumberForNonGeoEntity} instead. 1863 */ 1864 public PhoneNumber getExampleNumberForType(String regionCode, PhoneNumberType type) { 1865 // Check the region code is valid. 1866 if (!isValidRegionCode(regionCode)) { 1867 logger.log(Level.WARNING, "Invalid or unknown region code provided: " + regionCode); 1868 return null; 1869 } 1870 PhoneNumberDesc desc = getNumberDescByType(getMetadataForRegion(regionCode), type); 1871 try { 1872 if (desc.hasExampleNumber()) { 1873 return parse(desc.getExampleNumber(), regionCode); 1874 } 1875 } catch (NumberParseException e) { 1876 logger.log(Level.SEVERE, e.toString()); 1877 } 1878 return null; 1879 } 1880 1881 /** 1882 * Gets a valid number for the specified country calling code for a non-geographical entity. 1883 * 1884 * @param countryCallingCode the country calling code for a non-geographical entity 1885 * @return a valid number for the non-geographical entity. Returns null when the metadata 1886 * does not contain such information, or the country calling code passed in does not belong 1887 * to a non-geographical entity. 1888 */ 1889 public PhoneNumber getExampleNumberForNonGeoEntity(int countryCallingCode) { 1890 PhoneMetadata metadata = getMetadataForNonGeographicalRegion(countryCallingCode); 1891 if (metadata != null) { 1892 PhoneNumberDesc desc = metadata.getGeneralDesc(); 1893 try { 1894 if (desc.hasExampleNumber()) { 1895 return parse("+" + countryCallingCode + desc.getExampleNumber(), "ZZ"); 1896 } 1897 } catch (NumberParseException e) { 1898 logger.log(Level.SEVERE, e.toString()); 1899 } 1900 } else { 1901 logger.log(Level.WARNING, 1902 "Invalid or unknown country calling code provided: " + countryCallingCode); 1903 } 1904 return null; 1905 } 1906 1907 /** 1908 * Appends the formatted extension of a phone number to formattedNumber, if the phone number had 1909 * an extension specified. 1910 */ 1911 private void maybeAppendFormattedExtension(PhoneNumber number, PhoneMetadata metadata, 1912 PhoneNumberFormat numberFormat, 1913 StringBuilder formattedNumber) { 1914 if (number.hasExtension() && number.getExtension().length() > 0) { 1915 if (numberFormat == PhoneNumberFormat.RFC3966) { 1916 formattedNumber.append(RFC3966_EXTN_PREFIX).append(number.getExtension()); 1917 } else { 1918 if (metadata.hasPreferredExtnPrefix()) { 1919 formattedNumber.append(metadata.getPreferredExtnPrefix()).append(number.getExtension()); 1920 } else { 1921 formattedNumber.append(DEFAULT_EXTN_PREFIX).append(number.getExtension()); 1922 } 1923 } 1924 } 1925 } 1926 1927 PhoneNumberDesc getNumberDescByType(PhoneMetadata metadata, PhoneNumberType type) { 1928 switch (type) { 1929 case PREMIUM_RATE: 1930 return metadata.getPremiumRate(); 1931 case TOLL_FREE: 1932 return metadata.getTollFree(); 1933 case MOBILE: 1934 return metadata.getMobile(); 1935 case FIXED_LINE: 1936 case FIXED_LINE_OR_MOBILE: 1937 return metadata.getFixedLine(); 1938 case SHARED_COST: 1939 return metadata.getSharedCost(); 1940 case VOIP: 1941 return metadata.getVoip(); 1942 case PERSONAL_NUMBER: 1943 return metadata.getPersonalNumber(); 1944 case PAGER: 1945 return metadata.getPager(); 1946 case UAN: 1947 return metadata.getUan(); 1948 case VOICEMAIL: 1949 return metadata.getVoicemail(); 1950 default: 1951 return metadata.getGeneralDesc(); 1952 } 1953 } 1954 1955 /** 1956 * Gets the type of a phone number. 1957 * 1958 * @param number the phone number that we want to know the type 1959 * @return the type of the phone number 1960 */ 1961 public PhoneNumberType getNumberType(PhoneNumber number) { 1962 String regionCode = getRegionCodeForNumber(number); 1963 PhoneMetadata metadata = getMetadataForRegionOrCallingCode(number.getCountryCode(), regionCode); 1964 if (metadata == null) { 1965 return PhoneNumberType.UNKNOWN; 1966 } 1967 String nationalSignificantNumber = getNationalSignificantNumber(number); 1968 return getNumberTypeHelper(nationalSignificantNumber, metadata); 1969 } 1970 1971 private PhoneNumberType getNumberTypeHelper(String nationalNumber, PhoneMetadata metadata) { 1972 PhoneNumberDesc generalNumberDesc = metadata.getGeneralDesc(); 1973 if (!generalNumberDesc.hasNationalNumberPattern() || 1974 !isNumberMatchingDesc(nationalNumber, generalNumberDesc)) { 1975 return PhoneNumberType.UNKNOWN; 1976 } 1977 1978 if (isNumberMatchingDesc(nationalNumber, metadata.getPremiumRate())) { 1979 return PhoneNumberType.PREMIUM_RATE; 1980 } 1981 if (isNumberMatchingDesc(nationalNumber, metadata.getTollFree())) { 1982 return PhoneNumberType.TOLL_FREE; 1983 } 1984 if (isNumberMatchingDesc(nationalNumber, metadata.getSharedCost())) { 1985 return PhoneNumberType.SHARED_COST; 1986 } 1987 if (isNumberMatchingDesc(nationalNumber, metadata.getVoip())) { 1988 return PhoneNumberType.VOIP; 1989 } 1990 if (isNumberMatchingDesc(nationalNumber, metadata.getPersonalNumber())) { 1991 return PhoneNumberType.PERSONAL_NUMBER; 1992 } 1993 if (isNumberMatchingDesc(nationalNumber, metadata.getPager())) { 1994 return PhoneNumberType.PAGER; 1995 } 1996 if (isNumberMatchingDesc(nationalNumber, metadata.getUan())) { 1997 return PhoneNumberType.UAN; 1998 } 1999 if (isNumberMatchingDesc(nationalNumber, metadata.getVoicemail())) { 2000 return PhoneNumberType.VOICEMAIL; 2001 } 2002 2003 boolean isFixedLine = isNumberMatchingDesc(nationalNumber, metadata.getFixedLine()); 2004 if (isFixedLine) { 2005 if (metadata.isSameMobileAndFixedLinePattern()) { 2006 return PhoneNumberType.FIXED_LINE_OR_MOBILE; 2007 } else if (isNumberMatchingDesc(nationalNumber, metadata.getMobile())) { 2008 return PhoneNumberType.FIXED_LINE_OR_MOBILE; 2009 } 2010 return PhoneNumberType.FIXED_LINE; 2011 } 2012 // Otherwise, test to see if the number is mobile. Only do this if certain that the patterns for 2013 // mobile and fixed line aren't the same. 2014 if (!metadata.isSameMobileAndFixedLinePattern() && 2015 isNumberMatchingDesc(nationalNumber, metadata.getMobile())) { 2016 return PhoneNumberType.MOBILE; 2017 } 2018 return PhoneNumberType.UNKNOWN; 2019 } 2020 2021 /** 2022 * Returns the metadata for the given region code or {@code null} if the region code is invalid 2023 * or unknown. 2024 */ 2025 PhoneMetadata getMetadataForRegion(String regionCode) { 2026 if (!isValidRegionCode(regionCode)) { 2027 return null; 2028 } 2029 synchronized (regionToMetadataMap) { 2030 if (!regionToMetadataMap.containsKey(regionCode)) { 2031 // The regionCode here will be valid and won't be '001', so we don't need to worry about 2032 // what to pass in for the country calling code. 2033 loadMetadataFromFile(currentFilePrefix, regionCode, 0, metadataLoader); 2034 } 2035 } 2036 return regionToMetadataMap.get(regionCode); 2037 } 2038 2039 PhoneMetadata getMetadataForNonGeographicalRegion(int countryCallingCode) { 2040 synchronized (countryCodeToNonGeographicalMetadataMap) { 2041 if (!countryCallingCodeToRegionCodeMap.containsKey(countryCallingCode)) { 2042 return null; 2043 } 2044 if (!countryCodeToNonGeographicalMetadataMap.containsKey(countryCallingCode)) { 2045 loadMetadataFromFile( 2046 currentFilePrefix, REGION_CODE_FOR_NON_GEO_ENTITY, countryCallingCode, metadataLoader); 2047 } 2048 } 2049 return countryCodeToNonGeographicalMetadataMap.get(countryCallingCode); 2050 } 2051 2052 boolean isNumberPossibleForDesc(String nationalNumber, PhoneNumberDesc numberDesc) { 2053 Matcher possibleNumberPatternMatcher = 2054 regexCache.getPatternForRegex(numberDesc.getPossibleNumberPattern()) 2055 .matcher(nationalNumber); 2056 return possibleNumberPatternMatcher.matches(); 2057 } 2058 2059 boolean isNumberMatchingDesc(String nationalNumber, PhoneNumberDesc numberDesc) { 2060 Matcher nationalNumberPatternMatcher = 2061 regexCache.getPatternForRegex(numberDesc.getNationalNumberPattern()) 2062 .matcher(nationalNumber); 2063 return isNumberPossibleForDesc(nationalNumber, numberDesc) && 2064 nationalNumberPatternMatcher.matches(); 2065 } 2066 2067 /** 2068 * Tests whether a phone number matches a valid pattern. Note this doesn't verify the number 2069 * is actually in use, which is impossible to tell by just looking at a number itself. 2070 * 2071 * @param number the phone number that we want to validate 2072 * @return a boolean that indicates whether the number is of a valid pattern 2073 */ 2074 public boolean isValidNumber(PhoneNumber number) { 2075 String regionCode = getRegionCodeForNumber(number); 2076 return isValidNumberForRegion(number, regionCode); 2077 } 2078 2079 /** 2080 * Tests whether a phone number is valid for a certain region. Note this doesn't verify the number 2081 * is actually in use, which is impossible to tell by just looking at a number itself. If the 2082 * country calling code is not the same as the country calling code for the region, this 2083 * immediately exits with false. After this, the specific number pattern rules for the region are 2084 * examined. This is useful for determining for example whether a particular number is valid for 2085 * Canada, rather than just a valid NANPA number. 2086 * Warning: In most cases, you want to use {@link #isValidNumber} instead. For example, this 2087 * method will mark numbers from British Crown dependencies such as the Isle of Man as invalid for 2088 * the region "GB" (United Kingdom), since it has its own region code, "IM", which may be 2089 * undesirable. 2090 * 2091 * @param number the phone number that we want to validate 2092 * @param regionCode the region that we want to validate the phone number for 2093 * @return a boolean that indicates whether the number is of a valid pattern 2094 */ 2095 public boolean isValidNumberForRegion(PhoneNumber number, String regionCode) { 2096 int countryCode = number.getCountryCode(); 2097 PhoneMetadata metadata = getMetadataForRegionOrCallingCode(countryCode, regionCode); 2098 if ((metadata == null) || 2099 (!REGION_CODE_FOR_NON_GEO_ENTITY.equals(regionCode) && 2100 countryCode != getCountryCodeForValidRegion(regionCode))) { 2101 // Either the region code was invalid, or the country calling code for this number does not 2102 // match that of the region code. 2103 return false; 2104 } 2105 PhoneNumberDesc generalNumDesc = metadata.getGeneralDesc(); 2106 String nationalSignificantNumber = getNationalSignificantNumber(number); 2107 2108 // For regions where we don't have metadata for PhoneNumberDesc, we treat any number passed in 2109 // as a valid number if its national significant number is between the minimum and maximum 2110 // lengths defined by ITU for a national significant number. 2111 if (!generalNumDesc.hasNationalNumberPattern()) { 2112 int numberLength = nationalSignificantNumber.length(); 2113 return numberLength > MIN_LENGTH_FOR_NSN && numberLength <= MAX_LENGTH_FOR_NSN; 2114 } 2115 return getNumberTypeHelper(nationalSignificantNumber, metadata) != PhoneNumberType.UNKNOWN; 2116 } 2117 2118 /** 2119 * Returns the region where a phone number is from. This could be used for geocoding at the region 2120 * level. 2121 * 2122 * @param number the phone number whose origin we want to know 2123 * @return the region where the phone number is from, or null if no region matches this calling 2124 * code 2125 */ 2126 public String getRegionCodeForNumber(PhoneNumber number) { 2127 int countryCode = number.getCountryCode(); 2128 List<String> regions = countryCallingCodeToRegionCodeMap.get(countryCode); 2129 if (regions == null) { 2130 String numberString = getNationalSignificantNumber(number); 2131 logger.log(Level.WARNING, 2132 "Missing/invalid country_code (" + countryCode + ") for number " + numberString); 2133 return null; 2134 } 2135 if (regions.size() == 1) { 2136 return regions.get(0); 2137 } else { 2138 return getRegionCodeForNumberFromRegionList(number, regions); 2139 } 2140 } 2141 2142 private String getRegionCodeForNumberFromRegionList(PhoneNumber number, 2143 List<String> regionCodes) { 2144 String nationalNumber = getNationalSignificantNumber(number); 2145 for (String regionCode : regionCodes) { 2146 // If leadingDigits is present, use this. Otherwise, do full validation. 2147 // Metadata cannot be null because the region codes come from the country calling code map. 2148 PhoneMetadata metadata = getMetadataForRegion(regionCode); 2149 if (metadata.hasLeadingDigits()) { 2150 if (regexCache.getPatternForRegex(metadata.getLeadingDigits()) 2151 .matcher(nationalNumber).lookingAt()) { 2152 return regionCode; 2153 } 2154 } else if (getNumberTypeHelper(nationalNumber, metadata) != PhoneNumberType.UNKNOWN) { 2155 return regionCode; 2156 } 2157 } 2158 return null; 2159 } 2160 2161 /** 2162 * Returns the region code that matches the specific country calling code. In the case of no 2163 * region code being found, ZZ will be returned. In the case of multiple regions, the one 2164 * designated in the metadata as the "main" region for this calling code will be returned. If the 2165 * countryCallingCode entered is valid but doesn't match a specific region (such as in the case of 2166 * non-geographical calling codes like 800) the value "001" will be returned (corresponding to 2167 * the value for World in the UN M.49 schema). 2168 */ 2169 public String getRegionCodeForCountryCode(int countryCallingCode) { 2170 List<String> regionCodes = countryCallingCodeToRegionCodeMap.get(countryCallingCode); 2171 return regionCodes == null ? UNKNOWN_REGION : regionCodes.get(0); 2172 } 2173 2174 /** 2175 * Returns a list with the region codes that match the specific country calling code. For 2176 * non-geographical country calling codes, the region code 001 is returned. Also, in the case 2177 * of no region code being found, an empty list is returned. 2178 */ 2179 public List<String> getRegionCodesForCountryCode(int countryCallingCode) { 2180 List<String> regionCodes = countryCallingCodeToRegionCodeMap.get(countryCallingCode); 2181 return Collections.unmodifiableList(regionCodes == null ? new ArrayList<String>(0) 2182 : regionCodes); 2183 } 2184 2185 /** 2186 * Returns the country calling code for a specific region. For example, this would be 1 for the 2187 * United States, and 64 for New Zealand. 2188 * 2189 * @param regionCode the region that we want to get the country calling code for 2190 * @return the country calling code for the region denoted by regionCode 2191 */ 2192 public int getCountryCodeForRegion(String regionCode) { 2193 if (!isValidRegionCode(regionCode)) { 2194 logger.log(Level.WARNING, 2195 "Invalid or missing region code (" 2196 + ((regionCode == null) ? "null" : regionCode) 2197 + ") provided."); 2198 return 0; 2199 } 2200 return getCountryCodeForValidRegion(regionCode); 2201 } 2202 2203 /** 2204 * Returns the country calling code for a specific region. For example, this would be 1 for the 2205 * United States, and 64 for New Zealand. Assumes the region is already valid. 2206 * 2207 * @param regionCode the region that we want to get the country calling code for 2208 * @return the country calling code for the region denoted by regionCode 2209 * @throws IllegalArgumentException if the region is invalid 2210 */ 2211 private int getCountryCodeForValidRegion(String regionCode) { 2212 PhoneMetadata metadata = getMetadataForRegion(regionCode); 2213 if (metadata == null) { 2214 throw new IllegalArgumentException("Invalid region code: " + regionCode); 2215 } 2216 return metadata.getCountryCode(); 2217 } 2218 2219 /** 2220 * Returns the national dialling prefix for a specific region. For example, this would be 1 for 2221 * the United States, and 0 for New Zealand. Set stripNonDigits to true to strip symbols like "~" 2222 * (which indicates a wait for a dialling tone) from the prefix returned. If no national prefix is 2223 * present, we return null. 2224 * 2225 * <p>Warning: Do not use this method for do-your-own formatting - for some regions, the 2226 * national dialling prefix is used only for certain types of numbers. Use the library's 2227 * formatting functions to prefix the national prefix when required. 2228 * 2229 * @param regionCode the region that we want to get the dialling prefix for 2230 * @param stripNonDigits true to strip non-digits from the national dialling prefix 2231 * @return the dialling prefix for the region denoted by regionCode 2232 */ 2233 public String getNddPrefixForRegion(String regionCode, boolean stripNonDigits) { 2234 PhoneMetadata metadata = getMetadataForRegion(regionCode); 2235 if (metadata == null) { 2236 logger.log(Level.WARNING, 2237 "Invalid or missing region code (" 2238 + ((regionCode == null) ? "null" : regionCode) 2239 + ") provided."); 2240 return null; 2241 } 2242 String nationalPrefix = metadata.getNationalPrefix(); 2243 // If no national prefix was found, we return null. 2244 if (nationalPrefix.length() == 0) { 2245 return null; 2246 } 2247 if (stripNonDigits) { 2248 // Note: if any other non-numeric symbols are ever used in national prefixes, these would have 2249 // to be removed here as well. 2250 nationalPrefix = nationalPrefix.replace("~", ""); 2251 } 2252 return nationalPrefix; 2253 } 2254 2255 /** 2256 * Checks if this is a region under the North American Numbering Plan Administration (NANPA). 2257 * 2258 * @return true if regionCode is one of the regions under NANPA 2259 */ 2260 public boolean isNANPACountry(String regionCode) { 2261 return nanpaRegions.contains(regionCode); 2262 } 2263 2264 /** 2265 * Checks whether the country calling code is from a region whose national significant number 2266 * could contain a leading zero. An example of such a region is Italy. Returns false if no 2267 * metadata for the country is found. 2268 */ 2269 boolean isLeadingZeroPossible(int countryCallingCode) { 2270 PhoneMetadata mainMetadataForCallingCode = 2271 getMetadataForRegionOrCallingCode(countryCallingCode, 2272 getRegionCodeForCountryCode(countryCallingCode)); 2273 if (mainMetadataForCallingCode == null) { 2274 return false; 2275 } 2276 return mainMetadataForCallingCode.isLeadingZeroPossible(); 2277 } 2278 2279 /** 2280 * Checks if the number is a valid vanity (alpha) number such as 800 MICROSOFT. A valid vanity 2281 * number will start with at least 3 digits and will have three or more alpha characters. This 2282 * does not do region-specific checks - to work out if this number is actually valid for a region, 2283 * it should be parsed and methods such as {@link #isPossibleNumberWithReason} and 2284 * {@link #isValidNumber} should be used. 2285 * 2286 * @param number the number that needs to be checked 2287 * @return true if the number is a valid vanity number 2288 */ 2289 public boolean isAlphaNumber(String number) { 2290 if (!isViablePhoneNumber(number)) { 2291 // Number is too short, or doesn't match the basic phone number pattern. 2292 return false; 2293 } 2294 StringBuilder strippedNumber = new StringBuilder(number); 2295 maybeStripExtension(strippedNumber); 2296 return VALID_ALPHA_PHONE_PATTERN.matcher(strippedNumber).matches(); 2297 } 2298 2299 /** 2300 * Convenience wrapper around {@link #isPossibleNumberWithReason}. Instead of returning the reason 2301 * for failure, this method returns a boolean value. 2302 * @param number the number that needs to be checked 2303 * @return true if the number is possible 2304 */ 2305 public boolean isPossibleNumber(PhoneNumber number) { 2306 return isPossibleNumberWithReason(number) == ValidationResult.IS_POSSIBLE; 2307 } 2308 2309 /** 2310 * Helper method to check a number against a particular pattern and determine whether it matches, 2311 * or is too short or too long. Currently, if a number pattern suggests that numbers of length 7 2312 * and 10 are possible, and a number in between these possible lengths is entered, such as of 2313 * length 8, this will return TOO_LONG. 2314 */ 2315 private ValidationResult testNumberLengthAgainstPattern(Pattern numberPattern, String number) { 2316 Matcher numberMatcher = numberPattern.matcher(number); 2317 if (numberMatcher.matches()) { 2318 return ValidationResult.IS_POSSIBLE; 2319 } 2320 if (numberMatcher.lookingAt()) { 2321 return ValidationResult.TOO_LONG; 2322 } else { 2323 return ValidationResult.TOO_SHORT; 2324 } 2325 } 2326 2327 /** 2328 * Helper method to check whether a number is too short to be a regular length phone number in a 2329 * region. 2330 */ 2331 private boolean isShorterThanPossibleNormalNumber(PhoneMetadata regionMetadata, String number) { 2332 Pattern possibleNumberPattern = regexCache.getPatternForRegex( 2333 regionMetadata.getGeneralDesc().getPossibleNumberPattern()); 2334 return testNumberLengthAgainstPattern(possibleNumberPattern, number) == 2335 ValidationResult.TOO_SHORT; 2336 } 2337 2338 /** 2339 * Check whether a phone number is a possible number. It provides a more lenient check than 2340 * {@link #isValidNumber} in the following sense: 2341 *<ol> 2342 * <li> It only checks the length of phone numbers. In particular, it doesn't check starting 2343 * digits of the number. 2344 * <li> It doesn't attempt to figure out the type of the number, but uses general rules which 2345 * applies to all types of phone numbers in a region. Therefore, it is much faster than 2346 * isValidNumber. 2347 * <li> For fixed line numbers, many regions have the concept of area code, which together with 2348 * subscriber number constitute the national significant number. It is sometimes okay to dial 2349 * the subscriber number only when dialing in the same area. This function will return 2350 * true if the subscriber-number-only version is passed in. On the other hand, because 2351 * isValidNumber validates using information on both starting digits (for fixed line 2352 * numbers, that would most likely be area codes) and length (obviously includes the 2353 * length of area codes for fixed line numbers), it will return false for the 2354 * subscriber-number-only version. 2355 * </ol> 2356 * @param number the number that needs to be checked 2357 * @return a ValidationResult object which indicates whether the number is possible 2358 */ 2359 public ValidationResult isPossibleNumberWithReason(PhoneNumber number) { 2360 String nationalNumber = getNationalSignificantNumber(number); 2361 int countryCode = number.getCountryCode(); 2362 // Note: For Russian Fed and NANPA numbers, we just use the rules from the default region (US or 2363 // Russia) since the getRegionCodeForNumber will not work if the number is possible but not 2364 // valid. This would need to be revisited if the possible number pattern ever differed between 2365 // various regions within those plans. 2366 if (!hasValidCountryCallingCode(countryCode)) { 2367 return ValidationResult.INVALID_COUNTRY_CODE; 2368 } 2369 String regionCode = getRegionCodeForCountryCode(countryCode); 2370 // Metadata cannot be null because the country calling code is valid. 2371 PhoneMetadata metadata = getMetadataForRegionOrCallingCode(countryCode, regionCode); 2372 PhoneNumberDesc generalNumDesc = metadata.getGeneralDesc(); 2373 // Handling case of numbers with no metadata. 2374 if (!generalNumDesc.hasNationalNumberPattern()) { 2375 logger.log(Level.FINER, "Checking if number is possible with incomplete metadata."); 2376 int numberLength = nationalNumber.length(); 2377 if (numberLength < MIN_LENGTH_FOR_NSN) { 2378 return ValidationResult.TOO_SHORT; 2379 } else if (numberLength > MAX_LENGTH_FOR_NSN) { 2380 return ValidationResult.TOO_LONG; 2381 } else { 2382 return ValidationResult.IS_POSSIBLE; 2383 } 2384 } 2385 Pattern possibleNumberPattern = 2386 regexCache.getPatternForRegex(generalNumDesc.getPossibleNumberPattern()); 2387 return testNumberLengthAgainstPattern(possibleNumberPattern, nationalNumber); 2388 } 2389 2390 /** 2391 * Check whether a phone number is a possible number given a number in the form of a string, and 2392 * the region where the number could be dialed from. It provides a more lenient check than 2393 * {@link #isValidNumber}. See {@link #isPossibleNumber(PhoneNumber)} for details. 2394 * 2395 * <p>This method first parses the number, then invokes {@link #isPossibleNumber(PhoneNumber)} 2396 * with the resultant PhoneNumber object. 2397 * 2398 * @param number the number that needs to be checked, in the form of a string 2399 * @param regionDialingFrom the region that we are expecting the number to be dialed from. 2400 * Note this is different from the region where the number belongs. For example, the number 2401 * +1 650 253 0000 is a number that belongs to US. When written in this form, it can be 2402 * dialed from any region. When it is written as 00 1 650 253 0000, it can be dialed from any 2403 * region which uses an international dialling prefix of 00. When it is written as 2404 * 650 253 0000, it can only be dialed from within the US, and when written as 253 0000, it 2405 * can only be dialed from within a smaller area in the US (Mountain View, CA, to be more 2406 * specific). 2407 * @return true if the number is possible 2408 */ 2409 public boolean isPossibleNumber(String number, String regionDialingFrom) { 2410 try { 2411 return isPossibleNumber(parse(number, regionDialingFrom)); 2412 } catch (NumberParseException e) { 2413 return false; 2414 } 2415 } 2416 2417 /** 2418 * Attempts to extract a valid number from a phone number that is too long to be valid, and resets 2419 * the PhoneNumber object passed in to that valid version. If no valid number could be extracted, 2420 * the PhoneNumber object passed in will not be modified. 2421 * @param number a PhoneNumber object which contains a number that is too long to be valid. 2422 * @return true if a valid phone number can be successfully extracted. 2423 */ 2424 public boolean truncateTooLongNumber(PhoneNumber number) { 2425 if (isValidNumber(number)) { 2426 return true; 2427 } 2428 PhoneNumber numberCopy = new PhoneNumber(); 2429 numberCopy.mergeFrom(number); 2430 long nationalNumber = number.getNationalNumber(); 2431 do { 2432 nationalNumber /= 10; 2433 numberCopy.setNationalNumber(nationalNumber); 2434 if (isPossibleNumberWithReason(numberCopy) == ValidationResult.TOO_SHORT || 2435 nationalNumber == 0) { 2436 return false; 2437 } 2438 } while (!isValidNumber(numberCopy)); 2439 number.setNationalNumber(nationalNumber); 2440 return true; 2441 } 2442 2443 /** 2444 * Gets an {@link com.android.i18n.phonenumbers.AsYouTypeFormatter} for the specific region. 2445 * 2446 * @param regionCode the region where the phone number is being entered 2447 * @return an {@link com.android.i18n.phonenumbers.AsYouTypeFormatter} object, which can be used 2448 * to format phone numbers in the specific region "as you type" 2449 */ 2450 public AsYouTypeFormatter getAsYouTypeFormatter(String regionCode) { 2451 return new AsYouTypeFormatter(regionCode); 2452 } 2453 2454 // Extracts country calling code from fullNumber, returns it and places the remaining number in 2455 // nationalNumber. It assumes that the leading plus sign or IDD has already been removed. Returns 2456 // 0 if fullNumber doesn't start with a valid country calling code, and leaves nationalNumber 2457 // unmodified. 2458 int extractCountryCode(StringBuilder fullNumber, StringBuilder nationalNumber) { 2459 if ((fullNumber.length() == 0) || (fullNumber.charAt(0) == '0')) { 2460 // Country codes do not begin with a '0'. 2461 return 0; 2462 } 2463 int potentialCountryCode; 2464 int numberLength = fullNumber.length(); 2465 for (int i = 1; i <= MAX_LENGTH_COUNTRY_CODE && i <= numberLength; i++) { 2466 potentialCountryCode = Integer.parseInt(fullNumber.substring(0, i)); 2467 if (countryCallingCodeToRegionCodeMap.containsKey(potentialCountryCode)) { 2468 nationalNumber.append(fullNumber.substring(i)); 2469 return potentialCountryCode; 2470 } 2471 } 2472 return 0; 2473 } 2474 2475 /** 2476 * Tries to extract a country calling code from a number. This method will return zero if no 2477 * country calling code is considered to be present. Country calling codes are extracted in the 2478 * following ways: 2479 * <ul> 2480 * <li> by stripping the international dialing prefix of the region the person is dialing from, 2481 * if this is present in the number, and looking at the next digits 2482 * <li> by stripping the '+' sign if present and then looking at the next digits 2483 * <li> by comparing the start of the number and the country calling code of the default region. 2484 * If the number is not considered possible for the numbering plan of the default region 2485 * initially, but starts with the country calling code of this region, validation will be 2486 * reattempted after stripping this country calling code. If this number is considered a 2487 * possible number, then the first digits will be considered the country calling code and 2488 * removed as such. 2489 * </ul> 2490 * It will throw a NumberParseException if the number starts with a '+' but the country calling 2491 * code supplied after this does not match that of any known region. 2492 * 2493 * @param number non-normalized telephone number that we wish to extract a country calling 2494 * code from - may begin with '+' 2495 * @param defaultRegionMetadata metadata about the region this number may be from 2496 * @param nationalNumber a string buffer to store the national significant number in, in the case 2497 * that a country calling code was extracted. The number is appended to any existing contents. 2498 * If no country calling code was extracted, this will be left unchanged. 2499 * @param keepRawInput true if the country_code_source and preferred_carrier_code fields of 2500 * phoneNumber should be populated. 2501 * @param phoneNumber the PhoneNumber object where the country_code and country_code_source need 2502 * to be populated. Note the country_code is always populated, whereas country_code_source is 2503 * only populated when keepCountryCodeSource is true. 2504 * @return the country calling code extracted or 0 if none could be extracted 2505 */ 2506 // @VisibleForTesting 2507 int maybeExtractCountryCode(String number, PhoneMetadata defaultRegionMetadata, 2508 StringBuilder nationalNumber, boolean keepRawInput, 2509 PhoneNumber phoneNumber) 2510 throws NumberParseException { 2511 if (number.length() == 0) { 2512 return 0; 2513 } 2514 StringBuilder fullNumber = new StringBuilder(number); 2515 // Set the default prefix to be something that will never match. 2516 String possibleCountryIddPrefix = "NonMatch"; 2517 if (defaultRegionMetadata != null) { 2518 possibleCountryIddPrefix = defaultRegionMetadata.getInternationalPrefix(); 2519 } 2520 2521 CountryCodeSource countryCodeSource = 2522 maybeStripInternationalPrefixAndNormalize(fullNumber, possibleCountryIddPrefix); 2523 if (keepRawInput) { 2524 phoneNumber.setCountryCodeSource(countryCodeSource); 2525 } 2526 if (countryCodeSource != CountryCodeSource.FROM_DEFAULT_COUNTRY) { 2527 if (fullNumber.length() <= MIN_LENGTH_FOR_NSN) { 2528 throw new NumberParseException(NumberParseException.ErrorType.TOO_SHORT_AFTER_IDD, 2529 "Phone number had an IDD, but after this was not " 2530 + "long enough to be a viable phone number."); 2531 } 2532 int potentialCountryCode = extractCountryCode(fullNumber, nationalNumber); 2533 if (potentialCountryCode != 0) { 2534 phoneNumber.setCountryCode(potentialCountryCode); 2535 return potentialCountryCode; 2536 } 2537 2538 // If this fails, they must be using a strange country calling code that we don't recognize, 2539 // or that doesn't exist. 2540 throw new NumberParseException(NumberParseException.ErrorType.INVALID_COUNTRY_CODE, 2541 "Country calling code supplied was not recognised."); 2542 } else if (defaultRegionMetadata != null) { 2543 // Check to see if the number starts with the country calling code for the default region. If 2544 // so, we remove the country calling code, and do some checks on the validity of the number 2545 // before and after. 2546 int defaultCountryCode = defaultRegionMetadata.getCountryCode(); 2547 String defaultCountryCodeString = String.valueOf(defaultCountryCode); 2548 String normalizedNumber = fullNumber.toString(); 2549 if (normalizedNumber.startsWith(defaultCountryCodeString)) { 2550 StringBuilder potentialNationalNumber = 2551 new StringBuilder(normalizedNumber.substring(defaultCountryCodeString.length())); 2552 PhoneNumberDesc generalDesc = defaultRegionMetadata.getGeneralDesc(); 2553 Pattern validNumberPattern = 2554 regexCache.getPatternForRegex(generalDesc.getNationalNumberPattern()); 2555 maybeStripNationalPrefixAndCarrierCode( 2556 potentialNationalNumber, defaultRegionMetadata, null /* Don't need the carrier code */); 2557 Pattern possibleNumberPattern = 2558 regexCache.getPatternForRegex(generalDesc.getPossibleNumberPattern()); 2559 // If the number was not valid before but is valid now, or if it was too long before, we 2560 // consider the number with the country calling code stripped to be a better result and 2561 // keep that instead. 2562 if ((!validNumberPattern.matcher(fullNumber).matches() && 2563 validNumberPattern.matcher(potentialNationalNumber).matches()) || 2564 testNumberLengthAgainstPattern(possibleNumberPattern, fullNumber.toString()) 2565 == ValidationResult.TOO_LONG) { 2566 nationalNumber.append(potentialNationalNumber); 2567 if (keepRawInput) { 2568 phoneNumber.setCountryCodeSource(CountryCodeSource.FROM_NUMBER_WITHOUT_PLUS_SIGN); 2569 } 2570 phoneNumber.setCountryCode(defaultCountryCode); 2571 return defaultCountryCode; 2572 } 2573 } 2574 } 2575 // No country calling code present. 2576 phoneNumber.setCountryCode(0); 2577 return 0; 2578 } 2579 2580 /** 2581 * Strips the IDD from the start of the number if present. Helper function used by 2582 * maybeStripInternationalPrefixAndNormalize. 2583 */ 2584 private boolean parsePrefixAsIdd(Pattern iddPattern, StringBuilder number) { 2585 Matcher m = iddPattern.matcher(number); 2586 if (m.lookingAt()) { 2587 int matchEnd = m.end(); 2588 // Only strip this if the first digit after the match is not a 0, since country calling codes 2589 // cannot begin with 0. 2590 Matcher digitMatcher = CAPTURING_DIGIT_PATTERN.matcher(number.substring(matchEnd)); 2591 if (digitMatcher.find()) { 2592 String normalizedGroup = normalizeDigitsOnly(digitMatcher.group(1)); 2593 if (normalizedGroup.equals("0")) { 2594 return false; 2595 } 2596 } 2597 number.delete(0, matchEnd); 2598 return true; 2599 } 2600 return false; 2601 } 2602 2603 /** 2604 * Strips any international prefix (such as +, 00, 011) present in the number provided, normalizes 2605 * the resulting number, and indicates if an international prefix was present. 2606 * 2607 * @param number the non-normalized telephone number that we wish to strip any international 2608 * dialing prefix from. 2609 * @param possibleIddPrefix the international direct dialing prefix from the region we 2610 * think this number may be dialed in 2611 * @return the corresponding CountryCodeSource if an international dialing prefix could be 2612 * removed from the number, otherwise CountryCodeSource.FROM_DEFAULT_COUNTRY if the number did 2613 * not seem to be in international format. 2614 */ 2615 // @VisibleForTesting 2616 CountryCodeSource maybeStripInternationalPrefixAndNormalize( 2617 StringBuilder number, 2618 String possibleIddPrefix) { 2619 if (number.length() == 0) { 2620 return CountryCodeSource.FROM_DEFAULT_COUNTRY; 2621 } 2622 // Check to see if the number begins with one or more plus signs. 2623 Matcher m = PLUS_CHARS_PATTERN.matcher(number); 2624 if (m.lookingAt()) { 2625 number.delete(0, m.end()); 2626 // Can now normalize the rest of the number since we've consumed the "+" sign at the start. 2627 normalize(number); 2628 return CountryCodeSource.FROM_NUMBER_WITH_PLUS_SIGN; 2629 } 2630 // Attempt to parse the first digits as an international prefix. 2631 Pattern iddPattern = regexCache.getPatternForRegex(possibleIddPrefix); 2632 normalize(number); 2633 return parsePrefixAsIdd(iddPattern, number) 2634 ? CountryCodeSource.FROM_NUMBER_WITH_IDD 2635 : CountryCodeSource.FROM_DEFAULT_COUNTRY; 2636 } 2637 2638 /** 2639 * Strips any national prefix (such as 0, 1) present in the number provided. 2640 * 2641 * @param number the normalized telephone number that we wish to strip any national 2642 * dialing prefix from 2643 * @param metadata the metadata for the region that we think this number is from 2644 * @param carrierCode a place to insert the carrier code if one is extracted 2645 * @return true if a national prefix or carrier code (or both) could be extracted. 2646 */ 2647 // @VisibleForTesting 2648 boolean maybeStripNationalPrefixAndCarrierCode( 2649 StringBuilder number, PhoneMetadata metadata, StringBuilder carrierCode) { 2650 int numberLength = number.length(); 2651 String possibleNationalPrefix = metadata.getNationalPrefixForParsing(); 2652 if (numberLength == 0 || possibleNationalPrefix.length() == 0) { 2653 // Early return for numbers of zero length. 2654 return false; 2655 } 2656 // Attempt to parse the first digits as a national prefix. 2657 Matcher prefixMatcher = regexCache.getPatternForRegex(possibleNationalPrefix).matcher(number); 2658 if (prefixMatcher.lookingAt()) { 2659 Pattern nationalNumberRule = 2660 regexCache.getPatternForRegex(metadata.getGeneralDesc().getNationalNumberPattern()); 2661 // Check if the original number is viable. 2662 boolean isViableOriginalNumber = nationalNumberRule.matcher(number).matches(); 2663 // prefixMatcher.group(numOfGroups) == null implies nothing was captured by the capturing 2664 // groups in possibleNationalPrefix; therefore, no transformation is necessary, and we just 2665 // remove the national prefix. 2666 int numOfGroups = prefixMatcher.groupCount(); 2667 String transformRule = metadata.getNationalPrefixTransformRule(); 2668 if (transformRule == null || transformRule.length() == 0 || 2669 prefixMatcher.group(numOfGroups) == null) { 2670 // If the original number was viable, and the resultant number is not, we return. 2671 if (isViableOriginalNumber && 2672 !nationalNumberRule.matcher(number.substring(prefixMatcher.end())).matches()) { 2673 return false; 2674 } 2675 if (carrierCode != null && numOfGroups > 0 && prefixMatcher.group(numOfGroups) != null) { 2676 carrierCode.append(prefixMatcher.group(1)); 2677 } 2678 number.delete(0, prefixMatcher.end()); 2679 return true; 2680 } else { 2681 // Check that the resultant number is still viable. If not, return. Check this by copying 2682 // the string buffer and making the transformation on the copy first. 2683 StringBuilder transformedNumber = new StringBuilder(number); 2684 transformedNumber.replace(0, numberLength, prefixMatcher.replaceFirst(transformRule)); 2685 if (isViableOriginalNumber && 2686 !nationalNumberRule.matcher(transformedNumber.toString()).matches()) { 2687 return false; 2688 } 2689 if (carrierCode != null && numOfGroups > 1) { 2690 carrierCode.append(prefixMatcher.group(1)); 2691 } 2692 number.replace(0, number.length(), transformedNumber.toString()); 2693 return true; 2694 } 2695 } 2696 return false; 2697 } 2698 2699 /** 2700 * Strips any extension (as in, the part of the number dialled after the call is connected, 2701 * usually indicated with extn, ext, x or similar) from the end of the number, and returns it. 2702 * 2703 * @param number the non-normalized telephone number that we wish to strip the extension from 2704 * @return the phone extension 2705 */ 2706 // @VisibleForTesting 2707 String maybeStripExtension(StringBuilder number) { 2708 Matcher m = EXTN_PATTERN.matcher(number); 2709 // If we find a potential extension, and the number preceding this is a viable number, we assume 2710 // it is an extension. 2711 if (m.find() && isViablePhoneNumber(number.substring(0, m.start()))) { 2712 // The numbers are captured into groups in the regular expression. 2713 for (int i = 1, length = m.groupCount(); i <= length; i++) { 2714 if (m.group(i) != null) { 2715 // We go through the capturing groups until we find one that captured some digits. If none 2716 // did, then we will return the empty string. 2717 String extension = m.group(i); 2718 number.delete(m.start(), number.length()); 2719 return extension; 2720 } 2721 } 2722 } 2723 return ""; 2724 } 2725 2726 /** 2727 * Checks to see that the region code used is valid, or if it is not valid, that the number to 2728 * parse starts with a + symbol so that we can attempt to infer the region from the number. 2729 * Returns false if it cannot use the region provided and the region cannot be inferred. 2730 */ 2731 private boolean checkRegionForParsing(String numberToParse, String defaultRegion) { 2732 if (!isValidRegionCode(defaultRegion)) { 2733 // If the number is null or empty, we can't infer the region. 2734 if (numberToParse == null || numberToParse.length() == 0 || 2735 !PLUS_CHARS_PATTERN.matcher(numberToParse).lookingAt()) { 2736 return false; 2737 } 2738 } 2739 return true; 2740 } 2741 2742 /** 2743 * Parses a string and returns it in proto buffer format. This method will throw a 2744 * {@link com.android.i18n.phonenumbers.NumberParseException} if the number is not considered to be 2745 * a possible number. Note that validation of whether the number is actually a valid number for a 2746 * particular region is not performed. This can be done separately with {@link #isValidNumber}. 2747 * 2748 * @param numberToParse number that we are attempting to parse. This can contain formatting 2749 * such as +, ( and -, as well as a phone number extension. It can also 2750 * be provided in RFC3966 format. 2751 * @param defaultRegion region that we are expecting the number to be from. This is only used 2752 * if the number being parsed is not written in international format. 2753 * The country_code for the number in this case would be stored as that 2754 * of the default region supplied. If the number is guaranteed to 2755 * start with a '+' followed by the country calling code, then 2756 * "ZZ" or null can be supplied. 2757 * @return a phone number proto buffer filled with the parsed number 2758 * @throws NumberParseException if the string is not considered to be a viable phone number or if 2759 * no default region was supplied and the number is not in 2760 * international format (does not start with +) 2761 */ 2762 public PhoneNumber parse(String numberToParse, String defaultRegion) 2763 throws NumberParseException { 2764 PhoneNumber phoneNumber = new PhoneNumber(); 2765 parse(numberToParse, defaultRegion, phoneNumber); 2766 return phoneNumber; 2767 } 2768 2769 /** 2770 * Same as {@link #parse(String, String)}, but accepts mutable PhoneNumber as a parameter to 2771 * decrease object creation when invoked many times. 2772 */ 2773 public void parse(String numberToParse, String defaultRegion, PhoneNumber phoneNumber) 2774 throws NumberParseException { 2775 parseHelper(numberToParse, defaultRegion, false, true, phoneNumber); 2776 } 2777 2778 /** 2779 * Parses a string and returns it in proto buffer format. This method differs from {@link #parse} 2780 * in that it always populates the raw_input field of the protocol buffer with numberToParse as 2781 * well as the country_code_source field. 2782 * 2783 * @param numberToParse number that we are attempting to parse. This can contain formatting 2784 * such as +, ( and -, as well as a phone number extension. 2785 * @param defaultRegion region that we are expecting the number to be from. This is only used 2786 * if the number being parsed is not written in international format. 2787 * The country calling code for the number in this case would be stored 2788 * as that of the default region supplied. 2789 * @return a phone number proto buffer filled with the parsed number 2790 * @throws NumberParseException if the string is not considered to be a viable phone number or if 2791 * no default region was supplied 2792 */ 2793 public PhoneNumber parseAndKeepRawInput(String numberToParse, String defaultRegion) 2794 throws NumberParseException { 2795 PhoneNumber phoneNumber = new PhoneNumber(); 2796 parseAndKeepRawInput(numberToParse, defaultRegion, phoneNumber); 2797 return phoneNumber; 2798 } 2799 2800 /** 2801 * Same as{@link #parseAndKeepRawInput(String, String)}, but accepts a mutable PhoneNumber as 2802 * a parameter to decrease object creation when invoked many times. 2803 */ 2804 public void parseAndKeepRawInput(String numberToParse, String defaultRegion, 2805 PhoneNumber phoneNumber) 2806 throws NumberParseException { 2807 parseHelper(numberToParse, defaultRegion, true, true, phoneNumber); 2808 } 2809 2810 /** 2811 * Returns an iterable over all {@link PhoneNumberMatch PhoneNumberMatches} in {@code text}. This 2812 * is a shortcut for {@link #findNumbers(CharSequence, String, Leniency, long) 2813 * getMatcher(text, defaultRegion, Leniency.VALID, Long.MAX_VALUE)}. 2814 * 2815 * @param text the text to search for phone numbers, null for no text 2816 * @param defaultRegion region that we are expecting the number to be from. This is only used 2817 * if the number being parsed is not written in international format. The 2818 * country_code for the number in this case would be stored as that of 2819 * the default region supplied. May be null if only international 2820 * numbers are expected. 2821 */ 2822 public Iterable<PhoneNumberMatch> findNumbers(CharSequence text, String defaultRegion) { 2823 return findNumbers(text, defaultRegion, Leniency.VALID, Long.MAX_VALUE); 2824 } 2825 2826 /** 2827 * Returns an iterable over all {@link PhoneNumberMatch PhoneNumberMatches} in {@code text}. 2828 * 2829 * @param text the text to search for phone numbers, null for no text 2830 * @param defaultRegion region that we are expecting the number to be from. This is only used 2831 * if the number being parsed is not written in international format. The 2832 * country_code for the number in this case would be stored as that of 2833 * the default region supplied. May be null if only international 2834 * numbers are expected. 2835 * @param leniency the leniency to use when evaluating candidate phone numbers 2836 * @param maxTries the maximum number of invalid numbers to try before giving up on the 2837 * text. This is to cover degenerate cases where the text has a lot of 2838 * false positives in it. Must be {@code >= 0}. 2839 */ 2840 public Iterable<PhoneNumberMatch> findNumbers( 2841 final CharSequence text, final String defaultRegion, final Leniency leniency, 2842 final long maxTries) { 2843 2844 return new Iterable<PhoneNumberMatch>() { 2845 public Iterator<PhoneNumberMatch> iterator() { 2846 return new PhoneNumberMatcher( 2847 PhoneNumberUtil.this, text, defaultRegion, leniency, maxTries); 2848 } 2849 }; 2850 } 2851 2852 /** 2853 * A helper function to set the values related to leading zeros in a PhoneNumber. 2854 */ 2855 static void setItalianLeadingZerosForPhoneNumber(String nationalNumber, PhoneNumber phoneNumber) { 2856 if (nationalNumber.length() > 1 && nationalNumber.charAt(0) == '0') { 2857 phoneNumber.setItalianLeadingZero(true); 2858 int numberOfLeadingZeros = 1; 2859 // Note that if the national number is all "0"s, the last "0" is not counted as a leading 2860 // zero. 2861 while (numberOfLeadingZeros < nationalNumber.length() - 1 && 2862 nationalNumber.charAt(numberOfLeadingZeros) == '0') { 2863 numberOfLeadingZeros++; 2864 } 2865 if (numberOfLeadingZeros != 1) { 2866 phoneNumber.setNumberOfLeadingZeros(numberOfLeadingZeros); 2867 } 2868 } 2869 } 2870 2871 /** 2872 * Parses a string and fills up the phoneNumber. This method is the same as the public 2873 * parse() method, with the exception that it allows the default region to be null, for use by 2874 * isNumberMatch(). checkRegion should be set to false if it is permitted for the default region 2875 * to be null or unknown ("ZZ"). 2876 */ 2877 private void parseHelper(String numberToParse, String defaultRegion, boolean keepRawInput, 2878 boolean checkRegion, PhoneNumber phoneNumber) 2879 throws NumberParseException { 2880 if (numberToParse == null) { 2881 throw new NumberParseException(NumberParseException.ErrorType.NOT_A_NUMBER, 2882 "The phone number supplied was null."); 2883 } else if (numberToParse.length() > MAX_INPUT_STRING_LENGTH) { 2884 throw new NumberParseException(NumberParseException.ErrorType.TOO_LONG, 2885 "The string supplied was too long to parse."); 2886 } 2887 2888 StringBuilder nationalNumber = new StringBuilder(); 2889 buildNationalNumberForParsing(numberToParse, nationalNumber); 2890 2891 if (!isViablePhoneNumber(nationalNumber.toString())) { 2892 throw new NumberParseException(NumberParseException.ErrorType.NOT_A_NUMBER, 2893 "The string supplied did not seem to be a phone number."); 2894 } 2895 2896 // Check the region supplied is valid, or that the extracted number starts with some sort of + 2897 // sign so the number's region can be determined. 2898 if (checkRegion && !checkRegionForParsing(nationalNumber.toString(), defaultRegion)) { 2899 throw new NumberParseException(NumberParseException.ErrorType.INVALID_COUNTRY_CODE, 2900 "Missing or invalid default region."); 2901 } 2902 2903 if (keepRawInput) { 2904 phoneNumber.setRawInput(numberToParse); 2905 } 2906 // Attempt to parse extension first, since it doesn't require region-specific data and we want 2907 // to have the non-normalised number here. 2908 String extension = maybeStripExtension(nationalNumber); 2909 if (extension.length() > 0) { 2910 phoneNumber.setExtension(extension); 2911 } 2912 2913 PhoneMetadata regionMetadata = getMetadataForRegion(defaultRegion); 2914 // Check to see if the number is given in international format so we know whether this number is 2915 // from the default region or not. 2916 StringBuilder normalizedNationalNumber = new StringBuilder(); 2917 int countryCode = 0; 2918 try { 2919 // TODO: This method should really just take in the string buffer that has already 2920 // been created, and just remove the prefix, rather than taking in a string and then 2921 // outputting a string buffer. 2922 countryCode = maybeExtractCountryCode(nationalNumber.toString(), regionMetadata, 2923 normalizedNationalNumber, keepRawInput, phoneNumber); 2924 } catch (NumberParseException e) { 2925 Matcher matcher = PLUS_CHARS_PATTERN.matcher(nationalNumber.toString()); 2926 if (e.getErrorType() == NumberParseException.ErrorType.INVALID_COUNTRY_CODE && 2927 matcher.lookingAt()) { 2928 // Strip the plus-char, and try again. 2929 countryCode = maybeExtractCountryCode(nationalNumber.substring(matcher.end()), 2930 regionMetadata, normalizedNationalNumber, 2931 keepRawInput, phoneNumber); 2932 if (countryCode == 0) { 2933 throw new NumberParseException(NumberParseException.ErrorType.INVALID_COUNTRY_CODE, 2934 "Could not interpret numbers after plus-sign."); 2935 } 2936 } else { 2937 throw new NumberParseException(e.getErrorType(), e.getMessage()); 2938 } 2939 } 2940 if (countryCode != 0) { 2941 String phoneNumberRegion = getRegionCodeForCountryCode(countryCode); 2942 if (!phoneNumberRegion.equals(defaultRegion)) { 2943 // Metadata cannot be null because the country calling code is valid. 2944 regionMetadata = getMetadataForRegionOrCallingCode(countryCode, phoneNumberRegion); 2945 } 2946 } else { 2947 // If no extracted country calling code, use the region supplied instead. The national number 2948 // is just the normalized version of the number we were given to parse. 2949 normalize(nationalNumber); 2950 normalizedNationalNumber.append(nationalNumber); 2951 if (defaultRegion != null) { 2952 countryCode = regionMetadata.getCountryCode(); 2953 phoneNumber.setCountryCode(countryCode); 2954 } else if (keepRawInput) { 2955 phoneNumber.clearCountryCodeSource(); 2956 } 2957 } 2958 if (normalizedNationalNumber.length() < MIN_LENGTH_FOR_NSN) { 2959 throw new NumberParseException(NumberParseException.ErrorType.TOO_SHORT_NSN, 2960 "The string supplied is too short to be a phone number."); 2961 } 2962 if (regionMetadata != null) { 2963 StringBuilder carrierCode = new StringBuilder(); 2964 StringBuilder potentialNationalNumber = new StringBuilder(normalizedNationalNumber); 2965 maybeStripNationalPrefixAndCarrierCode(potentialNationalNumber, regionMetadata, carrierCode); 2966 // We require that the NSN remaining after stripping the national prefix and carrier code be 2967 // of a possible length for the region. Otherwise, we don't do the stripping, since the 2968 // original number could be a valid short number. 2969 if (!isShorterThanPossibleNormalNumber(regionMetadata, potentialNationalNumber.toString())) { 2970 normalizedNationalNumber = potentialNationalNumber; 2971 if (keepRawInput) { 2972 phoneNumber.setPreferredDomesticCarrierCode(carrierCode.toString()); 2973 } 2974 } 2975 } 2976 int lengthOfNationalNumber = normalizedNationalNumber.length(); 2977 if (lengthOfNationalNumber < MIN_LENGTH_FOR_NSN) { 2978 throw new NumberParseException(NumberParseException.ErrorType.TOO_SHORT_NSN, 2979 "The string supplied is too short to be a phone number."); 2980 } 2981 if (lengthOfNationalNumber > MAX_LENGTH_FOR_NSN) { 2982 throw new NumberParseException(NumberParseException.ErrorType.TOO_LONG, 2983 "The string supplied is too long to be a phone number."); 2984 } 2985 setItalianLeadingZerosForPhoneNumber(normalizedNationalNumber.toString(), phoneNumber); 2986 phoneNumber.setNationalNumber(Long.parseLong(normalizedNationalNumber.toString())); 2987 } 2988 2989 /** 2990 * Converts numberToParse to a form that we can parse and write it to nationalNumber if it is 2991 * written in RFC3966; otherwise extract a possible number out of it and write to nationalNumber. 2992 */ 2993 private void buildNationalNumberForParsing(String numberToParse, StringBuilder nationalNumber) { 2994 int indexOfPhoneContext = numberToParse.indexOf(RFC3966_PHONE_CONTEXT); 2995 if (indexOfPhoneContext > 0) { 2996 int phoneContextStart = indexOfPhoneContext + RFC3966_PHONE_CONTEXT.length(); 2997 // If the phone context contains a phone number prefix, we need to capture it, whereas domains 2998 // will be ignored. 2999 if (numberToParse.charAt(phoneContextStart) == PLUS_SIGN) { 3000 // Additional parameters might follow the phone context. If so, we will remove them here 3001 // because the parameters after phone context are not important for parsing the 3002 // phone number. 3003 int phoneContextEnd = numberToParse.indexOf(';', phoneContextStart); 3004 if (phoneContextEnd > 0) { 3005 nationalNumber.append(numberToParse.substring(phoneContextStart, phoneContextEnd)); 3006 } else { 3007 nationalNumber.append(numberToParse.substring(phoneContextStart)); 3008 } 3009 } 3010 3011 // Now append everything between the "tel:" prefix and the phone-context. This should include 3012 // the national number, an optional extension or isdn-subaddress component. 3013 nationalNumber.append(numberToParse.substring( 3014 numberToParse.indexOf(RFC3966_PREFIX) + RFC3966_PREFIX.length(), indexOfPhoneContext)); 3015 } else { 3016 // Extract a possible number from the string passed in (this strips leading characters that 3017 // could not be the start of a phone number.) 3018 nationalNumber.append(extractPossibleNumber(numberToParse)); 3019 } 3020 3021 // Delete the isdn-subaddress and everything after it if it is present. Note extension won't 3022 // appear at the same time with isdn-subaddress according to paragraph 5.3 of the RFC3966 spec, 3023 int indexOfIsdn = nationalNumber.indexOf(RFC3966_ISDN_SUBADDRESS); 3024 if (indexOfIsdn > 0) { 3025 nationalNumber.delete(indexOfIsdn, nationalNumber.length()); 3026 } 3027 // If both phone context and isdn-subaddress are absent but other parameters are present, the 3028 // parameters are left in nationalNumber. This is because we are concerned about deleting 3029 // content from a potential number string when there is no strong evidence that the number is 3030 // actually written in RFC3966. 3031 } 3032 3033 /** 3034 * Takes two phone numbers and compares them for equality. 3035 * 3036 * <p>Returns EXACT_MATCH if the country_code, NSN, presence of a leading zero for Italian numbers 3037 * and any extension present are the same. 3038 * Returns NSN_MATCH if either or both has no region specified, and the NSNs and extensions are 3039 * the same. 3040 * Returns SHORT_NSN_MATCH if either or both has no region specified, or the region specified is 3041 * the same, and one NSN could be a shorter version of the other number. This includes the case 3042 * where one has an extension specified, and the other does not. 3043 * Returns NO_MATCH otherwise. 3044 * For example, the numbers +1 345 657 1234 and 657 1234 are a SHORT_NSN_MATCH. 3045 * The numbers +1 345 657 1234 and 345 657 are a NO_MATCH. 3046 * 3047 * @param firstNumberIn first number to compare 3048 * @param secondNumberIn second number to compare 3049 * 3050 * @return NO_MATCH, SHORT_NSN_MATCH, NSN_MATCH or EXACT_MATCH depending on the level of equality 3051 * of the two numbers, described in the method definition. 3052 */ 3053 public MatchType isNumberMatch(PhoneNumber firstNumberIn, PhoneNumber secondNumberIn) { 3054 // Make copies of the phone number so that the numbers passed in are not edited. 3055 PhoneNumber firstNumber = new PhoneNumber(); 3056 firstNumber.mergeFrom(firstNumberIn); 3057 PhoneNumber secondNumber = new PhoneNumber(); 3058 secondNumber.mergeFrom(secondNumberIn); 3059 // First clear raw_input, country_code_source and preferred_domestic_carrier_code fields and any 3060 // empty-string extensions so that we can use the proto-buffer equality method. 3061 firstNumber.clearRawInput(); 3062 firstNumber.clearCountryCodeSource(); 3063 firstNumber.clearPreferredDomesticCarrierCode(); 3064 secondNumber.clearRawInput(); 3065 secondNumber.clearCountryCodeSource(); 3066 secondNumber.clearPreferredDomesticCarrierCode(); 3067 if (firstNumber.hasExtension() && 3068 firstNumber.getExtension().length() == 0) { 3069 firstNumber.clearExtension(); 3070 } 3071 if (secondNumber.hasExtension() && 3072 secondNumber.getExtension().length() == 0) { 3073 secondNumber.clearExtension(); 3074 } 3075 // Early exit if both had extensions and these are different. 3076 if (firstNumber.hasExtension() && secondNumber.hasExtension() && 3077 !firstNumber.getExtension().equals(secondNumber.getExtension())) { 3078 return MatchType.NO_MATCH; 3079 } 3080 int firstNumberCountryCode = firstNumber.getCountryCode(); 3081 int secondNumberCountryCode = secondNumber.getCountryCode(); 3082 // Both had country_code specified. 3083 if (firstNumberCountryCode != 0 && secondNumberCountryCode != 0) { 3084 if (firstNumber.exactlySameAs(secondNumber)) { 3085 return MatchType.EXACT_MATCH; 3086 } else if (firstNumberCountryCode == secondNumberCountryCode && 3087 isNationalNumberSuffixOfTheOther(firstNumber, secondNumber)) { 3088 // A SHORT_NSN_MATCH occurs if there is a difference because of the presence or absence of 3089 // an 'Italian leading zero', the presence or absence of an extension, or one NSN being a 3090 // shorter variant of the other. 3091 return MatchType.SHORT_NSN_MATCH; 3092 } 3093 // This is not a match. 3094 return MatchType.NO_MATCH; 3095 } 3096 // Checks cases where one or both country_code fields were not specified. To make equality 3097 // checks easier, we first set the country_code fields to be equal. 3098 firstNumber.setCountryCode(secondNumberCountryCode); 3099 // If all else was the same, then this is an NSN_MATCH. 3100 if (firstNumber.exactlySameAs(secondNumber)) { 3101 return MatchType.NSN_MATCH; 3102 } 3103 if (isNationalNumberSuffixOfTheOther(firstNumber, secondNumber)) { 3104 return MatchType.SHORT_NSN_MATCH; 3105 } 3106 return MatchType.NO_MATCH; 3107 } 3108 3109 // Returns true when one national number is the suffix of the other or both are the same. 3110 private boolean isNationalNumberSuffixOfTheOther(PhoneNumber firstNumber, 3111 PhoneNumber secondNumber) { 3112 String firstNumberNationalNumber = String.valueOf(firstNumber.getNationalNumber()); 3113 String secondNumberNationalNumber = String.valueOf(secondNumber.getNationalNumber()); 3114 // Note that endsWith returns true if the numbers are equal. 3115 return firstNumberNationalNumber.endsWith(secondNumberNationalNumber) || 3116 secondNumberNationalNumber.endsWith(firstNumberNationalNumber); 3117 } 3118 3119 /** 3120 * Takes two phone numbers as strings and compares them for equality. This is a convenience 3121 * wrapper for {@link #isNumberMatch(PhoneNumber, PhoneNumber)}. No default region is known. 3122 * 3123 * @param firstNumber first number to compare. Can contain formatting, and can have country 3124 * calling code specified with + at the start. 3125 * @param secondNumber second number to compare. Can contain formatting, and can have country 3126 * calling code specified with + at the start. 3127 * @return NOT_A_NUMBER, NO_MATCH, SHORT_NSN_MATCH, NSN_MATCH, EXACT_MATCH. See 3128 * {@link #isNumberMatch(PhoneNumber, PhoneNumber)} for more details. 3129 */ 3130 public MatchType isNumberMatch(String firstNumber, String secondNumber) { 3131 try { 3132 PhoneNumber firstNumberAsProto = parse(firstNumber, UNKNOWN_REGION); 3133 return isNumberMatch(firstNumberAsProto, secondNumber); 3134 } catch (NumberParseException e) { 3135 if (e.getErrorType() == NumberParseException.ErrorType.INVALID_COUNTRY_CODE) { 3136 try { 3137 PhoneNumber secondNumberAsProto = parse(secondNumber, UNKNOWN_REGION); 3138 return isNumberMatch(secondNumberAsProto, firstNumber); 3139 } catch (NumberParseException e2) { 3140 if (e2.getErrorType() == NumberParseException.ErrorType.INVALID_COUNTRY_CODE) { 3141 try { 3142 PhoneNumber firstNumberProto = new PhoneNumber(); 3143 PhoneNumber secondNumberProto = new PhoneNumber(); 3144 parseHelper(firstNumber, null, false, false, firstNumberProto); 3145 parseHelper(secondNumber, null, false, false, secondNumberProto); 3146 return isNumberMatch(firstNumberProto, secondNumberProto); 3147 } catch (NumberParseException e3) { 3148 // Fall through and return MatchType.NOT_A_NUMBER. 3149 } 3150 } 3151 } 3152 } 3153 } 3154 // One or more of the phone numbers we are trying to match is not a viable phone number. 3155 return MatchType.NOT_A_NUMBER; 3156 } 3157 3158 /** 3159 * Takes two phone numbers and compares them for equality. This is a convenience wrapper for 3160 * {@link #isNumberMatch(PhoneNumber, PhoneNumber)}. No default region is known. 3161 * 3162 * @param firstNumber first number to compare in proto buffer format. 3163 * @param secondNumber second number to compare. Can contain formatting, and can have country 3164 * calling code specified with + at the start. 3165 * @return NOT_A_NUMBER, NO_MATCH, SHORT_NSN_MATCH, NSN_MATCH, EXACT_MATCH. See 3166 * {@link #isNumberMatch(PhoneNumber, PhoneNumber)} for more details. 3167 */ 3168 public MatchType isNumberMatch(PhoneNumber firstNumber, String secondNumber) { 3169 // First see if the second number has an implicit country calling code, by attempting to parse 3170 // it. 3171 try { 3172 PhoneNumber secondNumberAsProto = parse(secondNumber, UNKNOWN_REGION); 3173 return isNumberMatch(firstNumber, secondNumberAsProto); 3174 } catch (NumberParseException e) { 3175 if (e.getErrorType() == NumberParseException.ErrorType.INVALID_COUNTRY_CODE) { 3176 // The second number has no country calling code. EXACT_MATCH is no longer possible. 3177 // We parse it as if the region was the same as that for the first number, and if 3178 // EXACT_MATCH is returned, we replace this with NSN_MATCH. 3179 String firstNumberRegion = getRegionCodeForCountryCode(firstNumber.getCountryCode()); 3180 try { 3181 if (!firstNumberRegion.equals(UNKNOWN_REGION)) { 3182 PhoneNumber secondNumberWithFirstNumberRegion = parse(secondNumber, firstNumberRegion); 3183 MatchType match = isNumberMatch(firstNumber, secondNumberWithFirstNumberRegion); 3184 if (match == MatchType.EXACT_MATCH) { 3185 return MatchType.NSN_MATCH; 3186 } 3187 return match; 3188 } else { 3189 // If the first number didn't have a valid country calling code, then we parse the 3190 // second number without one as well. 3191 PhoneNumber secondNumberProto = new PhoneNumber(); 3192 parseHelper(secondNumber, null, false, false, secondNumberProto); 3193 return isNumberMatch(firstNumber, secondNumberProto); 3194 } 3195 } catch (NumberParseException e2) { 3196 // Fall-through to return NOT_A_NUMBER. 3197 } 3198 } 3199 } 3200 // One or more of the phone numbers we are trying to match is not a viable phone number. 3201 return MatchType.NOT_A_NUMBER; 3202 } 3203 3204 /** 3205 * Returns true if the number can be dialled from outside the region, or unknown. If the number 3206 * can only be dialled from within the region, returns false. Does not check the number is a valid 3207 * number. 3208 * TODO: Make this method public when we have enough metadata to make it worthwhile. 3209 * 3210 * @param number the phone-number for which we want to know whether it is diallable from 3211 * outside the region 3212 */ 3213 // @VisibleForTesting 3214 boolean canBeInternationallyDialled(PhoneNumber number) { 3215 PhoneMetadata metadata = getMetadataForRegion(getRegionCodeForNumber(number)); 3216 if (metadata == null) { 3217 // Note numbers belonging to non-geographical entities (e.g. +800 numbers) are always 3218 // internationally diallable, and will be caught here. 3219 return true; 3220 } 3221 String nationalSignificantNumber = getNationalSignificantNumber(number); 3222 return !isNumberMatchingDesc(nationalSignificantNumber, metadata.getNoInternationalDialling()); 3223 } 3224 3225 /** 3226 * Returns true if the supplied region supports mobile number portability. Returns false for 3227 * invalid, unknown or regions that don't support mobile number portability. 3228 * 3229 * @param regionCode the region for which we want to know whether it supports mobile number 3230 * portability or not. 3231 */ 3232 public boolean isMobileNumberPortableRegion(String regionCode) { 3233 PhoneMetadata metadata = getMetadataForRegion(regionCode); 3234 if (metadata == null) { 3235 logger.log(Level.WARNING, "Invalid or unknown region code provided: " + regionCode); 3236 return false; 3237 } 3238 return metadata.isMobileNumberPortableRegion(); 3239 } 3240 } 3241