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