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