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     String regionCode = getRegionCodeForCountryCode(countryCallingCode);
   1210     if (regionCallingFrom.equals(regionCode)) {
   1211       PhoneNumberType numberType = getNumberType(numberNoExt);
   1212       boolean isFixedLineOrMobile =
   1213           (numberType == PhoneNumberType.FIXED_LINE) || (numberType == PhoneNumberType.MOBILE) ||
   1214           (numberType == PhoneNumberType.FIXED_LINE_OR_MOBILE);
   1215       // Carrier codes may be needed in some countries. We handle this here.
   1216       if (regionCode.equals("CO") && numberType == PhoneNumberType.FIXED_LINE) {
   1217         formattedNumber =
   1218             formatNationalNumberWithCarrierCode(numberNoExt, COLOMBIA_MOBILE_TO_FIXED_LINE_PREFIX);
   1219       } else if (regionCode.equals("BR") && isFixedLineOrMobile) {
   1220         formattedNumber = numberNoExt.hasPreferredDomesticCarrierCode()
   1221             ? formattedNumber = formatNationalNumberWithPreferredCarrierCode(numberNoExt, "")
   1222             // Brazilian fixed line and mobile numbers need to be dialed with a carrier code when
   1223             // called within Brazil. Without that, most of the carriers won't connect the call.
   1224             // Because of that, we return an empty string here.
   1225             : "";
   1226       } else {
   1227         // For NANPA countries, non-geographical countries, and Mexican fixed line and mobile
   1228         // numbers, we output international format for numbers that can be dialed internationally
   1229         // as that always works.
   1230         if ((countryCallingCode == NANPA_COUNTRY_CODE ||
   1231             regionCode.equals(REGION_CODE_FOR_NON_GEO_ENTITY) ||
   1232             // MX fixed line and mobile numbers should always be formatted in international format,
   1233             // even when dialed within MX. For national format to work, a carrier code needs to be
   1234             // used, and the correct carrier code depends on if the caller and callee are from the
   1235             // same local area. It is trickier to get that to work correctly than using
   1236             // international format, which is tested to work fine on all carriers.
   1237             (regionCode.equals("MX") && isFixedLineOrMobile)) &&
   1238             canBeInternationallyDialled(numberNoExt)) {
   1239           formattedNumber = format(numberNoExt, PhoneNumberFormat.INTERNATIONAL);
   1240         } else {
   1241           formattedNumber = format(numberNoExt, PhoneNumberFormat.NATIONAL);
   1242         }
   1243       }
   1244     } else if (canBeInternationallyDialled(numberNoExt)) {
   1245       return withFormatting ? format(numberNoExt, PhoneNumberFormat.INTERNATIONAL)
   1246                             : format(numberNoExt, PhoneNumberFormat.E164);
   1247     }
   1248     return withFormatting ? formattedNumber
   1249                           : normalizeHelper(formattedNumber, DIALLABLE_CHAR_MAPPINGS,
   1250                                             true /* remove non matches */);
   1251   }
   1252 
   1253   /**
   1254    * Formats a phone number for out-of-country dialing purposes. If no regionCallingFrom is
   1255    * supplied, we format the number in its INTERNATIONAL format. If the country calling code is the
   1256    * same as that of the region where the number is from, then NATIONAL formatting will be applied.
   1257    *
   1258    * <p>If the number itself has a country calling code of zero or an otherwise invalid country
   1259    * calling code, then we return the number with no formatting applied.
   1260    *
   1261    * <p>Note this function takes care of the case for calling inside of NANPA and between Russia and
   1262    * Kazakhstan (who share the same country calling code). In those cases, no international prefix
   1263    * is used. For regions which have multiple international prefixes, the number in its
   1264    * INTERNATIONAL format will be returned instead.
   1265    *
   1266    * @param number               the phone number to be formatted
   1267    * @param regionCallingFrom    the region where the call is being placed
   1268    * @return  the formatted phone number
   1269    */
   1270   public String formatOutOfCountryCallingNumber(PhoneNumber number,
   1271                                                 String regionCallingFrom) {
   1272     if (!isValidRegionCode(regionCallingFrom)) {
   1273       LOGGER.log(Level.WARNING,
   1274                  "Trying to format number from invalid region "
   1275                  + regionCallingFrom
   1276                  + ". International formatting applied.");
   1277       return format(number, PhoneNumberFormat.INTERNATIONAL);
   1278     }
   1279     int countryCallingCode = number.getCountryCode();
   1280     String nationalSignificantNumber = getNationalSignificantNumber(number);
   1281     if (!hasValidCountryCallingCode(countryCallingCode)) {
   1282       return nationalSignificantNumber;
   1283     }
   1284     if (countryCallingCode == NANPA_COUNTRY_CODE) {
   1285       if (isNANPACountry(regionCallingFrom)) {
   1286         // For NANPA regions, return the national format for these regions but prefix it with the
   1287         // country calling code.
   1288         return countryCallingCode + " " + format(number, PhoneNumberFormat.NATIONAL);
   1289       }
   1290     } else if (countryCallingCode == getCountryCodeForValidRegion(regionCallingFrom)) {
   1291       // If regions share a country calling code, the country calling code need not be dialled.
   1292       // This also applies when dialling within a region, so this if clause covers both these cases.
   1293       // Technically this is the case for dialling from La Reunion to other overseas departments of
   1294       // France (French Guiana, Martinique, Guadeloupe), but not vice versa - so we don't cover this
   1295       // edge case for now and for those cases return the version including country calling code.
   1296       // Details here: http://www.petitfute.com/voyage/225-info-pratiques-reunion
   1297       return format(number, PhoneNumberFormat.NATIONAL);
   1298     }
   1299     // Metadata cannot be null because we checked 'isValidRegionCode()' above.
   1300     PhoneMetadata metadataForRegionCallingFrom = getMetadataForRegion(regionCallingFrom);
   1301     String internationalPrefix = metadataForRegionCallingFrom.getInternationalPrefix();
   1302 
   1303     // For regions that have multiple international prefixes, the international format of the
   1304     // number is returned, unless there is a preferred international prefix.
   1305     String internationalPrefixForFormatting = "";
   1306     if (UNIQUE_INTERNATIONAL_PREFIX.matcher(internationalPrefix).matches()) {
   1307       internationalPrefixForFormatting = internationalPrefix;
   1308     } else if (metadataForRegionCallingFrom.hasPreferredInternationalPrefix()) {
   1309       internationalPrefixForFormatting =
   1310           metadataForRegionCallingFrom.getPreferredInternationalPrefix();
   1311     }
   1312 
   1313     String regionCode = getRegionCodeForCountryCode(countryCallingCode);
   1314     // Metadata cannot be null because the country calling code is valid.
   1315     PhoneMetadata metadataForRegion =
   1316         getMetadataForRegionOrCallingCode(countryCallingCode, regionCode);
   1317     String formattedNationalNumber =
   1318         formatNsn(nationalSignificantNumber, metadataForRegion, PhoneNumberFormat.INTERNATIONAL);
   1319     StringBuilder formattedNumber = new StringBuilder(formattedNationalNumber);
   1320     maybeAppendFormattedExtension(number, metadataForRegion, PhoneNumberFormat.INTERNATIONAL,
   1321                                   formattedNumber);
   1322     if (internationalPrefixForFormatting.length() > 0) {
   1323       formattedNumber.insert(0, " ").insert(0, countryCallingCode).insert(0, " ")
   1324           .insert(0, internationalPrefixForFormatting);
   1325     } else {
   1326       prefixNumberWithCountryCallingCode(countryCallingCode,
   1327                                          PhoneNumberFormat.INTERNATIONAL,
   1328                                          formattedNumber);
   1329     }
   1330     return formattedNumber.toString();
   1331   }
   1332 
   1333   /**
   1334    * Formats a phone number using the original phone number format that the number is parsed from.
   1335    * The original format is embedded in the country_code_source field of the PhoneNumber object
   1336    * passed in. If such information is missing, the number will be formatted into the NATIONAL
   1337    * format by default. When the number contains a leading zero and this is unexpected for this
   1338    * country, or we don't have a formatting pattern for the number, the method returns the raw input
   1339    * when it is available.
   1340    *
   1341    * Note this method guarantees no digit will be inserted, removed or modified as a result of
   1342    * formatting.
   1343    *
   1344    * @param number  the phone number that needs to be formatted in its original number format
   1345    * @param regionCallingFrom  the region whose IDD needs to be prefixed if the original number
   1346    *     has one
   1347    * @return  the formatted phone number in its original number format
   1348    */
   1349   public String formatInOriginalFormat(PhoneNumber number, String regionCallingFrom) {
   1350     if (number.hasRawInput() &&
   1351         (hasUnexpectedItalianLeadingZero(number) || !hasFormattingPatternForNumber(number))) {
   1352       // We check if we have the formatting pattern because without that, we might format the number
   1353       // as a group without national prefix.
   1354       return number.getRawInput();
   1355     }
   1356     if (!number.hasCountryCodeSource()) {
   1357       return format(number, PhoneNumberFormat.NATIONAL);
   1358     }
   1359     String formattedNumber;
   1360     switch (number.getCountryCodeSource()) {
   1361       case FROM_NUMBER_WITH_PLUS_SIGN:
   1362         formattedNumber = format(number, PhoneNumberFormat.INTERNATIONAL);
   1363         break;
   1364       case FROM_NUMBER_WITH_IDD:
   1365         formattedNumber = formatOutOfCountryCallingNumber(number, regionCallingFrom);
   1366         break;
   1367       case FROM_NUMBER_WITHOUT_PLUS_SIGN:
   1368         formattedNumber = format(number, PhoneNumberFormat.INTERNATIONAL).substring(1);
   1369         break;
   1370       case FROM_DEFAULT_COUNTRY:
   1371         // Fall-through to default case.
   1372       default:
   1373         String regionCode = getRegionCodeForCountryCode(number.getCountryCode());
   1374         // We strip non-digits from the NDD here, and from the raw input later, so that we can
   1375         // compare them easily.
   1376         String nationalPrefix = getNddPrefixForRegion(regionCode, true /* strip non-digits */);
   1377         String nationalFormat = format(number, PhoneNumberFormat.NATIONAL);
   1378         if (nationalPrefix == null || nationalPrefix.length() == 0) {
   1379           // If the region doesn't have a national prefix at all, we can safely return the national
   1380           // format without worrying about a national prefix being added.
   1381           formattedNumber = nationalFormat;
   1382           break;
   1383         }
   1384         // Otherwise, we check if the original number was entered with a national prefix.
   1385         if (rawInputContainsNationalPrefix(
   1386             number.getRawInput(), nationalPrefix, regionCode)) {
   1387           // If so, we can safely return the national format.
   1388           formattedNumber = nationalFormat;
   1389           break;
   1390         }
   1391         // Metadata cannot be null here because getNddPrefixForRegion() (above) returns null if
   1392         // there is no metadata for the region.
   1393         PhoneMetadata metadata = getMetadataForRegion(regionCode);
   1394         String nationalNumber = getNationalSignificantNumber(number);
   1395         NumberFormat formatRule =
   1396             chooseFormattingPatternForNumber(metadata.numberFormats(), nationalNumber);
   1397         // The format rule could still be null here if the national number was 0 and there was no
   1398         // raw input (this should not be possible for numbers generated by the phonenumber library
   1399         // as they would also not have a country calling code and we would have exited earlier).
   1400         if (formatRule == null) {
   1401           formattedNumber = nationalFormat;
   1402           break;
   1403         }
   1404         // When the format we apply to this number doesn't contain national prefix, we can just
   1405         // return the national format.
   1406         // TODO: Refactor the code below with the code in isNationalPrefixPresentIfRequired.
   1407         String candidateNationalPrefixRule = formatRule.getNationalPrefixFormattingRule();
   1408         // We assume that the first-group symbol will never be _before_ the national prefix.
   1409         int indexOfFirstGroup = candidateNationalPrefixRule.indexOf("$1");
   1410         if (indexOfFirstGroup <= 0) {
   1411           formattedNumber = nationalFormat;
   1412           break;
   1413         }
   1414         candidateNationalPrefixRule =
   1415             candidateNationalPrefixRule.substring(0, indexOfFirstGroup);
   1416         candidateNationalPrefixRule = normalizeDigitsOnly(candidateNationalPrefixRule);
   1417         if (candidateNationalPrefixRule.length() == 0) {
   1418           // National prefix not used when formatting this number.
   1419           formattedNumber = nationalFormat;
   1420           break;
   1421         }
   1422         // Otherwise, we need to remove the national prefix from our output.
   1423         NumberFormat numFormatCopy = new NumberFormat();
   1424         numFormatCopy.mergeFrom(formatRule);
   1425         numFormatCopy.clearNationalPrefixFormattingRule();
   1426         List<NumberFormat> numberFormats = new ArrayList<NumberFormat>(1);
   1427         numberFormats.add(numFormatCopy);
   1428         formattedNumber = formatByPattern(number, PhoneNumberFormat.NATIONAL, numberFormats);
   1429         break;
   1430     }
   1431     String rawInput = number.getRawInput();
   1432     // If no digit is inserted/removed/modified as a result of our formatting, we return the
   1433     // formatted phone number; otherwise we return the raw input the user entered.
   1434     if (formattedNumber != null && rawInput.length() > 0) {
   1435       String normalizedFormattedNumber =
   1436           normalizeHelper(formattedNumber, DIALLABLE_CHAR_MAPPINGS, true /* remove non matches */);
   1437       String normalizedRawInput =
   1438           normalizeHelper(rawInput, DIALLABLE_CHAR_MAPPINGS, true /* remove non matches */);
   1439       if (!normalizedFormattedNumber.equals(normalizedRawInput)) {
   1440         formattedNumber = rawInput;
   1441       }
   1442     }
   1443     return formattedNumber;
   1444   }
   1445 
   1446   // Check if rawInput, which is assumed to be in the national format, has a national prefix. The
   1447   // national prefix is assumed to be in digits-only form.
   1448   private boolean rawInputContainsNationalPrefix(String rawInput, String nationalPrefix,
   1449       String regionCode) {
   1450     String normalizedNationalNumber = normalizeDigitsOnly(rawInput);
   1451     if (normalizedNationalNumber.startsWith(nationalPrefix)) {
   1452       try {
   1453         // Some Japanese numbers (e.g. 00777123) might be mistaken to contain the national prefix
   1454         // when written without it (e.g. 0777123) if we just do prefix matching. To tackle that, we
   1455         // check the validity of the number if the assumed national prefix is removed (777123 won't
   1456         // be valid in Japan).
   1457         return isValidNumber(
   1458             parse(normalizedNationalNumber.substring(nationalPrefix.length()), regionCode));
   1459       } catch (NumberParseException e) {
   1460         return false;
   1461       }
   1462     }
   1463     return false;
   1464   }
   1465 
   1466   /**
   1467    * Returns true if a number is from a region whose national significant number couldn't contain a
   1468    * leading zero, but has the italian_leading_zero field set to true.
   1469    */
   1470   private boolean hasUnexpectedItalianLeadingZero(PhoneNumber number) {
   1471     return number.isItalianLeadingZero() && !isLeadingZeroPossible(number.getCountryCode());
   1472   }
   1473 
   1474   private boolean hasFormattingPatternForNumber(PhoneNumber number) {
   1475     int countryCallingCode = number.getCountryCode();
   1476     String phoneNumberRegion = getRegionCodeForCountryCode(countryCallingCode);
   1477     PhoneMetadata metadata =
   1478         getMetadataForRegionOrCallingCode(countryCallingCode, phoneNumberRegion);
   1479     if (metadata == null) {
   1480       return false;
   1481     }
   1482     String nationalNumber = getNationalSignificantNumber(number);
   1483     NumberFormat formatRule =
   1484         chooseFormattingPatternForNumber(metadata.numberFormats(), nationalNumber);
   1485     return formatRule != null;
   1486   }
   1487 
   1488   /**
   1489    * Formats a phone number for out-of-country dialing purposes.
   1490    *
   1491    * Note that in this version, if the number was entered originally using alpha characters and
   1492    * this version of the number is stored in raw_input, this representation of the number will be
   1493    * used rather than the digit representation. Grouping information, as specified by characters
   1494    * such as "-" and " ", will be retained.
   1495    *
   1496    * <p><b>Caveats:</b></p>
   1497    * <ul>
   1498    *  <li> This will not produce good results if the country calling code is both present in the raw
   1499    *       input _and_ is the start of the national number. This is not a problem in the regions
   1500    *       which typically use alpha numbers.
   1501    *  <li> This will also not produce good results if the raw input has any grouping information
   1502    *       within the first three digits of the national number, and if the function needs to strip
   1503    *       preceding digits/words in the raw input before these digits. Normally people group the
   1504    *       first three digits together so this is not a huge problem - and will be fixed if it
   1505    *       proves to be so.
   1506    * </ul>
   1507    *
   1508    * @param number  the phone number that needs to be formatted
   1509    * @param regionCallingFrom  the region where the call is being placed
   1510    * @return  the formatted phone number
   1511    */
   1512   public String formatOutOfCountryKeepingAlphaChars(PhoneNumber number,
   1513                                                     String regionCallingFrom) {
   1514     String rawInput = number.getRawInput();
   1515     // If there is no raw input, then we can't keep alpha characters because there aren't any.
   1516     // In this case, we return formatOutOfCountryCallingNumber.
   1517     if (rawInput.length() == 0) {
   1518       return formatOutOfCountryCallingNumber(number, regionCallingFrom);
   1519     }
   1520     int countryCode = number.getCountryCode();
   1521     if (!hasValidCountryCallingCode(countryCode)) {
   1522       return rawInput;
   1523     }
   1524     // Strip any prefix such as country calling code, IDD, that was present. We do this by comparing
   1525     // the number in raw_input with the parsed number.
   1526     // To do this, first we normalize punctuation. We retain number grouping symbols such as " "
   1527     // only.
   1528     rawInput = normalizeHelper(rawInput, ALL_PLUS_NUMBER_GROUPING_SYMBOLS, true);
   1529     // Now we trim everything before the first three digits in the parsed number. We choose three
   1530     // because all valid alpha numbers have 3 digits at the start - if it does not, then we don't
   1531     // trim anything at all. Similarly, if the national number was less than three digits, we don't
   1532     // trim anything at all.
   1533     String nationalNumber = getNationalSignificantNumber(number);
   1534     if (nationalNumber.length() > 3) {
   1535       int firstNationalNumberDigit = rawInput.indexOf(nationalNumber.substring(0, 3));
   1536       if (firstNationalNumberDigit != -1) {
   1537         rawInput = rawInput.substring(firstNationalNumberDigit);
   1538       }
   1539     }
   1540     PhoneMetadata metadataForRegionCallingFrom = getMetadataForRegion(regionCallingFrom);
   1541     if (countryCode == NANPA_COUNTRY_CODE) {
   1542       if (isNANPACountry(regionCallingFrom)) {
   1543         return countryCode + " " + rawInput;
   1544       }
   1545     } else if (metadataForRegionCallingFrom != null &&
   1546                countryCode == getCountryCodeForValidRegion(regionCallingFrom)) {
   1547       NumberFormat formattingPattern =
   1548           chooseFormattingPatternForNumber(metadataForRegionCallingFrom.numberFormats(),
   1549                                            nationalNumber);
   1550       if (formattingPattern == null) {
   1551         // If no pattern above is matched, we format the original input.
   1552         return rawInput;
   1553       }
   1554       NumberFormat newFormat = new NumberFormat();
   1555       newFormat.mergeFrom(formattingPattern);
   1556       // The first group is the first group of digits that the user wrote together.
   1557       newFormat.setPattern("(\\d+)(.*)");
   1558       // Here we just concatenate them back together after the national prefix has been fixed.
   1559       newFormat.setFormat("$1$2");
   1560       // Now we format using this pattern instead of the default pattern, but with the national
   1561       // prefix prefixed if necessary.
   1562       // This will not work in the cases where the pattern (and not the leading digits) decide
   1563       // whether a national prefix needs to be used, since we have overridden the pattern to match
   1564       // anything, but that is not the case in the metadata to date.
   1565       return formatNsnUsingPattern(rawInput, newFormat, PhoneNumberFormat.NATIONAL);
   1566     }
   1567     String internationalPrefixForFormatting = "";
   1568     // If an unsupported region-calling-from is entered, or a country with multiple international
   1569     // prefixes, the international format of the number is returned, unless there is a preferred
   1570     // international prefix.
   1571     if (metadataForRegionCallingFrom != null) {
   1572       String internationalPrefix = metadataForRegionCallingFrom.getInternationalPrefix();
   1573       internationalPrefixForFormatting =
   1574           UNIQUE_INTERNATIONAL_PREFIX.matcher(internationalPrefix).matches()
   1575           ? internationalPrefix
   1576           : metadataForRegionCallingFrom.getPreferredInternationalPrefix();
   1577     }
   1578     StringBuilder formattedNumber = new StringBuilder(rawInput);
   1579     String regionCode = getRegionCodeForCountryCode(countryCode);
   1580     // Metadata cannot be null because the country calling code is valid.
   1581     PhoneMetadata metadataForRegion = getMetadataForRegionOrCallingCode(countryCode, regionCode);
   1582     maybeAppendFormattedExtension(number, metadataForRegion,
   1583                                   PhoneNumberFormat.INTERNATIONAL, formattedNumber);
   1584     if (internationalPrefixForFormatting.length() > 0) {
   1585       formattedNumber.insert(0, " ").insert(0, countryCode).insert(0, " ")
   1586           .insert(0, internationalPrefixForFormatting);
   1587     } else {
   1588       // Invalid region entered as country-calling-from (so no metadata was found for it) or the
   1589       // region chosen has multiple international dialling prefixes.
   1590       LOGGER.log(Level.WARNING,
   1591                  "Trying to format number from invalid region "
   1592                  + regionCallingFrom
   1593                  + ". International formatting applied.");
   1594       prefixNumberWithCountryCallingCode(countryCode,
   1595                                          PhoneNumberFormat.INTERNATIONAL,
   1596                                          formattedNumber);
   1597     }
   1598     return formattedNumber.toString();
   1599   }
   1600 
   1601   /**
   1602    * Gets the national significant number of the a phone number. Note a national significant number
   1603    * doesn't contain a national prefix or any formatting.
   1604    *
   1605    * @param number  the phone number for which the national significant number is needed
   1606    * @return  the national significant number of the PhoneNumber object passed in
   1607    */
   1608   public String getNationalSignificantNumber(PhoneNumber number) {
   1609     // If a leading zero has been set, we prefix this now. Note this is not a national prefix.
   1610     StringBuilder nationalNumber = new StringBuilder(number.isItalianLeadingZero() ? "0" : "");
   1611     nationalNumber.append(number.getNationalNumber());
   1612     return nationalNumber.toString();
   1613   }
   1614 
   1615   /**
   1616    * A helper function that is used by format and formatByPattern.
   1617    */
   1618   private void prefixNumberWithCountryCallingCode(int countryCallingCode,
   1619                                                   PhoneNumberFormat numberFormat,
   1620                                                   StringBuilder formattedNumber) {
   1621     switch (numberFormat) {
   1622       case E164:
   1623         formattedNumber.insert(0, countryCallingCode).insert(0, PLUS_SIGN);
   1624         return;
   1625       case INTERNATIONAL:
   1626         formattedNumber.insert(0, " ").insert(0, countryCallingCode).insert(0, PLUS_SIGN);
   1627         return;
   1628       case RFC3966:
   1629         formattedNumber.insert(0, "-").insert(0, countryCallingCode).insert(0, PLUS_SIGN)
   1630             .insert(0, RFC3966_PREFIX);
   1631         return;
   1632       case NATIONAL:
   1633       default:
   1634         return;
   1635     }
   1636   }
   1637 
   1638   // Simple wrapper of formatNsn for the common case of no carrier code.
   1639   private String formatNsn(String number, PhoneMetadata metadata, PhoneNumberFormat numberFormat) {
   1640     return formatNsn(number, metadata, numberFormat, null);
   1641   }
   1642 
   1643   // Note in some regions, the national number can be written in two completely different ways
   1644   // depending on whether it forms part of the NATIONAL format or INTERNATIONAL format. The
   1645   // numberFormat parameter here is used to specify which format to use for those cases. If a
   1646   // carrierCode is specified, this will be inserted into the formatted string to replace $CC.
   1647   private String formatNsn(String number,
   1648                            PhoneMetadata metadata,
   1649                            PhoneNumberFormat numberFormat,
   1650                            String carrierCode) {
   1651     List<NumberFormat> intlNumberFormats = metadata.intlNumberFormats();
   1652     // When the intlNumberFormats exists, we use that to format national number for the
   1653     // INTERNATIONAL format instead of using the numberDesc.numberFormats.
   1654     List<NumberFormat> availableFormats =
   1655         (intlNumberFormats.size() == 0 || numberFormat == PhoneNumberFormat.NATIONAL)
   1656         ? metadata.numberFormats()
   1657         : metadata.intlNumberFormats();
   1658     NumberFormat formattingPattern = chooseFormattingPatternForNumber(availableFormats, number);
   1659     return (formattingPattern == null)
   1660         ? number
   1661         : formatNsnUsingPattern(number, formattingPattern, numberFormat, carrierCode);
   1662   }
   1663 
   1664   NumberFormat chooseFormattingPatternForNumber(List<NumberFormat> availableFormats,
   1665                                                 String nationalNumber) {
   1666     for (NumberFormat numFormat : availableFormats) {
   1667       int size = numFormat.leadingDigitsPatternSize();
   1668       if (size == 0 || regexCache.getPatternForRegex(
   1669               // We always use the last leading_digits_pattern, as it is the most detailed.
   1670               numFormat.getLeadingDigitsPattern(size - 1)).matcher(nationalNumber).lookingAt()) {
   1671         Matcher m = regexCache.getPatternForRegex(numFormat.getPattern()).matcher(nationalNumber);
   1672         if (m.matches()) {
   1673           return numFormat;
   1674         }
   1675       }
   1676     }
   1677     return null;
   1678   }
   1679 
   1680   // Simple wrapper of formatNsnUsingPattern for the common case of no carrier code.
   1681   String formatNsnUsingPattern(String nationalNumber,
   1682                                NumberFormat formattingPattern,
   1683                                PhoneNumberFormat numberFormat) {
   1684     return formatNsnUsingPattern(nationalNumber, formattingPattern, numberFormat, null);
   1685   }
   1686 
   1687   // Note that carrierCode is optional - if null or an empty string, no carrier code replacement
   1688   // will take place.
   1689   private String formatNsnUsingPattern(String nationalNumber,
   1690                                        NumberFormat formattingPattern,
   1691                                        PhoneNumberFormat numberFormat,
   1692                                        String carrierCode) {
   1693     String numberFormatRule = formattingPattern.getFormat();
   1694     Matcher m =
   1695         regexCache.getPatternForRegex(formattingPattern.getPattern()).matcher(nationalNumber);
   1696     String formattedNationalNumber = "";
   1697     if (numberFormat == PhoneNumberFormat.NATIONAL &&
   1698         carrierCode != null && carrierCode.length() > 0 &&
   1699         formattingPattern.getDomesticCarrierCodeFormattingRule().length() > 0) {
   1700       // Replace the $CC in the formatting rule with the desired carrier code.
   1701       String carrierCodeFormattingRule = formattingPattern.getDomesticCarrierCodeFormattingRule();
   1702       carrierCodeFormattingRule =
   1703           CC_PATTERN.matcher(carrierCodeFormattingRule).replaceFirst(carrierCode);
   1704       // Now replace the $FG in the formatting rule with the first group and the carrier code
   1705       // combined in the appropriate way.
   1706       numberFormatRule = FIRST_GROUP_PATTERN.matcher(numberFormatRule)
   1707           .replaceFirst(carrierCodeFormattingRule);
   1708       formattedNationalNumber = m.replaceAll(numberFormatRule);
   1709     } else {
   1710       // Use the national prefix formatting rule instead.
   1711       String nationalPrefixFormattingRule = formattingPattern.getNationalPrefixFormattingRule();
   1712       if (numberFormat == PhoneNumberFormat.NATIONAL &&
   1713           nationalPrefixFormattingRule != null &&
   1714           nationalPrefixFormattingRule.length() > 0) {
   1715         Matcher firstGroupMatcher = FIRST_GROUP_PATTERN.matcher(numberFormatRule);
   1716         formattedNationalNumber =
   1717             m.replaceAll(firstGroupMatcher.replaceFirst(nationalPrefixFormattingRule));
   1718       } else {
   1719         formattedNationalNumber = m.replaceAll(numberFormatRule);
   1720       }
   1721     }
   1722     if (numberFormat == PhoneNumberFormat.RFC3966) {
   1723       // Strip any leading punctuation.
   1724       Matcher matcher = SEPARATOR_PATTERN.matcher(formattedNationalNumber);
   1725       if (matcher.lookingAt()) {
   1726         formattedNationalNumber = matcher.replaceFirst("");
   1727       }
   1728       // Replace the rest with a dash between each number group.
   1729       formattedNationalNumber = matcher.reset(formattedNationalNumber).replaceAll("-");
   1730     }
   1731     return formattedNationalNumber;
   1732   }
   1733 
   1734   /**
   1735    * Gets a valid number for the specified region.
   1736    *
   1737    * @param regionCode  the region for which an example number is needed
   1738    * @return  a valid fixed-line number for the specified region. Returns null when the metadata
   1739    *    does not contain such information, or the region 001 is passed in. For 001 (representing
   1740    *    non-geographical numbers), call {@link #getExampleNumberForNonGeoEntity} instead.
   1741    */
   1742   public PhoneNumber getExampleNumber(String regionCode) {
   1743     return getExampleNumberForType(regionCode, PhoneNumberType.FIXED_LINE);
   1744   }
   1745 
   1746   /**
   1747    * Gets a valid number for the specified region and number type.
   1748    *
   1749    * @param regionCode  the region for which an example number is needed
   1750    * @param type  the type of number that is needed
   1751    * @return  a valid number for the specified region and type. Returns null when the metadata
   1752    *     does not contain such information or if an invalid region or region 001 was entered.
   1753    *     For 001 (representing non-geographical numbers), call
   1754    *     {@link #getExampleNumberForNonGeoEntity} instead.
   1755    */
   1756   public PhoneNumber getExampleNumberForType(String regionCode, PhoneNumberType type) {
   1757     // Check the region code is valid.
   1758     if (!isValidRegionCode(regionCode)) {
   1759       LOGGER.log(Level.WARNING, "Invalid or unknown region code provided: " + regionCode);
   1760       return null;
   1761     }
   1762     PhoneNumberDesc desc = getNumberDescByType(getMetadataForRegion(regionCode), type);
   1763     try {
   1764       if (desc.hasExampleNumber()) {
   1765         return parse(desc.getExampleNumber(), regionCode);
   1766       }
   1767     } catch (NumberParseException e) {
   1768       LOGGER.log(Level.SEVERE, e.toString());
   1769     }
   1770     return null;
   1771   }
   1772 
   1773   /**
   1774    * Gets a valid number for the specified country calling code for a non-geographical entity.
   1775    *
   1776    * @param countryCallingCode  the country calling code for a non-geographical entity
   1777    * @return  a valid number for the non-geographical entity. Returns null when the metadata
   1778    *    does not contain such information, or the country calling code passed in does not belong
   1779    *    to a non-geographical entity.
   1780    */
   1781   public PhoneNumber getExampleNumberForNonGeoEntity(int countryCallingCode) {
   1782     PhoneMetadata metadata = getMetadataForNonGeographicalRegion(countryCallingCode);
   1783     if (metadata != null) {
   1784       PhoneNumberDesc desc = metadata.getGeneralDesc();
   1785       try {
   1786         if (desc.hasExampleNumber()) {
   1787           return parse("+" + countryCallingCode + desc.getExampleNumber(), "ZZ");
   1788         }
   1789       } catch (NumberParseException e) {
   1790         LOGGER.log(Level.SEVERE, e.toString());
   1791       }
   1792     } else {
   1793       LOGGER.log(Level.WARNING,
   1794                  "Invalid or unknown country calling code provided: " + countryCallingCode);
   1795     }
   1796     return null;
   1797   }
   1798 
   1799   /**
   1800    * Appends the formatted extension of a phone number to formattedNumber, if the phone number had
   1801    * an extension specified.
   1802    */
   1803   private void maybeAppendFormattedExtension(PhoneNumber number, PhoneMetadata metadata,
   1804                                              PhoneNumberFormat numberFormat,
   1805                                              StringBuilder formattedNumber) {
   1806     if (number.hasExtension() && number.getExtension().length() > 0) {
   1807       if (numberFormat == PhoneNumberFormat.RFC3966) {
   1808         formattedNumber.append(RFC3966_EXTN_PREFIX).append(number.getExtension());
   1809       } else {
   1810         if (metadata.hasPreferredExtnPrefix()) {
   1811           formattedNumber.append(metadata.getPreferredExtnPrefix()).append(number.getExtension());
   1812         } else {
   1813           formattedNumber.append(DEFAULT_EXTN_PREFIX).append(number.getExtension());
   1814         }
   1815       }
   1816     }
   1817   }
   1818 
   1819   PhoneNumberDesc getNumberDescByType(PhoneMetadata metadata, PhoneNumberType type) {
   1820     switch (type) {
   1821       case PREMIUM_RATE:
   1822         return metadata.getPremiumRate();
   1823       case TOLL_FREE:
   1824         return metadata.getTollFree();
   1825       case MOBILE:
   1826         return metadata.getMobile();
   1827       case FIXED_LINE:
   1828       case FIXED_LINE_OR_MOBILE:
   1829         return metadata.getFixedLine();
   1830       case SHARED_COST:
   1831         return metadata.getSharedCost();
   1832       case VOIP:
   1833         return metadata.getVoip();
   1834       case PERSONAL_NUMBER:
   1835         return metadata.getPersonalNumber();
   1836       case PAGER:
   1837         return metadata.getPager();
   1838       case UAN:
   1839         return metadata.getUan();
   1840       case VOICEMAIL:
   1841         return metadata.getVoicemail();
   1842       default:
   1843         return metadata.getGeneralDesc();
   1844     }
   1845   }
   1846 
   1847   /**
   1848    * Gets the type of a phone number.
   1849    *
   1850    * @param number  the phone number that we want to know the type
   1851    * @return  the type of the phone number
   1852    */
   1853   public PhoneNumberType getNumberType(PhoneNumber number) {
   1854     String regionCode = getRegionCodeForNumber(number);
   1855     PhoneMetadata metadata = getMetadataForRegionOrCallingCode(number.getCountryCode(), regionCode);
   1856     if (metadata == null) {
   1857       return PhoneNumberType.UNKNOWN;
   1858     }
   1859     String nationalSignificantNumber = getNationalSignificantNumber(number);
   1860     return getNumberTypeHelper(nationalSignificantNumber, metadata);
   1861   }
   1862 
   1863   private PhoneNumberType getNumberTypeHelper(String nationalNumber, PhoneMetadata metadata) {
   1864     PhoneNumberDesc generalNumberDesc = metadata.getGeneralDesc();
   1865     if (!generalNumberDesc.hasNationalNumberPattern() ||
   1866         !isNumberMatchingDesc(nationalNumber, generalNumberDesc)) {
   1867       return PhoneNumberType.UNKNOWN;
   1868     }
   1869 
   1870     if (isNumberMatchingDesc(nationalNumber, metadata.getPremiumRate())) {
   1871       return PhoneNumberType.PREMIUM_RATE;
   1872     }
   1873     if (isNumberMatchingDesc(nationalNumber, metadata.getTollFree())) {
   1874       return PhoneNumberType.TOLL_FREE;
   1875     }
   1876     if (isNumberMatchingDesc(nationalNumber, metadata.getSharedCost())) {
   1877       return PhoneNumberType.SHARED_COST;
   1878     }
   1879     if (isNumberMatchingDesc(nationalNumber, metadata.getVoip())) {
   1880       return PhoneNumberType.VOIP;
   1881     }
   1882     if (isNumberMatchingDesc(nationalNumber, metadata.getPersonalNumber())) {
   1883       return PhoneNumberType.PERSONAL_NUMBER;
   1884     }
   1885     if (isNumberMatchingDesc(nationalNumber, metadata.getPager())) {
   1886       return PhoneNumberType.PAGER;
   1887     }
   1888     if (isNumberMatchingDesc(nationalNumber, metadata.getUan())) {
   1889       return PhoneNumberType.UAN;
   1890     }
   1891     if (isNumberMatchingDesc(nationalNumber, metadata.getVoicemail())) {
   1892       return PhoneNumberType.VOICEMAIL;
   1893     }
   1894 
   1895     boolean isFixedLine = isNumberMatchingDesc(nationalNumber, metadata.getFixedLine());
   1896     if (isFixedLine) {
   1897       if (metadata.isSameMobileAndFixedLinePattern()) {
   1898         return PhoneNumberType.FIXED_LINE_OR_MOBILE;
   1899       } else if (isNumberMatchingDesc(nationalNumber, metadata.getMobile())) {
   1900         return PhoneNumberType.FIXED_LINE_OR_MOBILE;
   1901       }
   1902       return PhoneNumberType.FIXED_LINE;
   1903     }
   1904     // Otherwise, test to see if the number is mobile. Only do this if certain that the patterns for
   1905     // mobile and fixed line aren't the same.
   1906     if (!metadata.isSameMobileAndFixedLinePattern() &&
   1907         isNumberMatchingDesc(nationalNumber, metadata.getMobile())) {
   1908       return PhoneNumberType.MOBILE;
   1909     }
   1910     return PhoneNumberType.UNKNOWN;
   1911   }
   1912 
   1913   /**
   1914    * Returns the metadata for the given region code or {@code null} if the region code is invalid
   1915    * or unknown.
   1916    */
   1917   PhoneMetadata getMetadataForRegion(String regionCode) {
   1918     if (!isValidRegionCode(regionCode)) {
   1919       return null;
   1920     }
   1921     synchronized (regionToMetadataMap) {
   1922       if (!regionToMetadataMap.containsKey(regionCode)) {
   1923         // The regionCode here will be valid and won't be '001', so we don't need to worry about
   1924         // what to pass in for the country calling code.
   1925         loadMetadataFromFile(currentFilePrefix, regionCode, 0);
   1926       }
   1927     }
   1928     return regionToMetadataMap.get(regionCode);
   1929   }
   1930 
   1931   PhoneMetadata getMetadataForNonGeographicalRegion(int countryCallingCode) {
   1932     synchronized (countryCodeToNonGeographicalMetadataMap) {
   1933       if (!countryCallingCodeToRegionCodeMap.containsKey(countryCallingCode)) {
   1934         return null;
   1935       }
   1936       if (!countryCodeToNonGeographicalMetadataMap.containsKey(countryCallingCode)) {
   1937         loadMetadataFromFile(currentFilePrefix, REGION_CODE_FOR_NON_GEO_ENTITY, countryCallingCode);
   1938       }
   1939     }
   1940     return countryCodeToNonGeographicalMetadataMap.get(countryCallingCode);
   1941   }
   1942 
   1943   private boolean isNumberMatchingDesc(String nationalNumber, PhoneNumberDesc numberDesc) {
   1944     Matcher possibleNumberPatternMatcher =
   1945         regexCache.getPatternForRegex(numberDesc.getPossibleNumberPattern())
   1946             .matcher(nationalNumber);
   1947     Matcher nationalNumberPatternMatcher =
   1948         regexCache.getPatternForRegex(numberDesc.getNationalNumberPattern())
   1949             .matcher(nationalNumber);
   1950     return possibleNumberPatternMatcher.matches() && nationalNumberPatternMatcher.matches();
   1951   }
   1952 
   1953   /**
   1954    * Tests whether a phone number matches a valid pattern. Note this doesn't verify the number
   1955    * is actually in use, which is impossible to tell by just looking at a number itself.
   1956    *
   1957    * @param number       the phone number that we want to validate
   1958    * @return  a boolean that indicates whether the number is of a valid pattern
   1959    */
   1960   public boolean isValidNumber(PhoneNumber number) {
   1961     String regionCode = getRegionCodeForNumber(number);
   1962     return isValidNumberForRegion(number, regionCode);
   1963   }
   1964 
   1965   /**
   1966    * Tests whether a phone number is valid for a certain region. Note this doesn't verify the number
   1967    * is actually in use, which is impossible to tell by just looking at a number itself. If the
   1968    * country calling code is not the same as the country calling code for the region, this
   1969    * immediately exits with false. After this, the specific number pattern rules for the region are
   1970    * examined. This is useful for determining for example whether a particular number is valid for
   1971    * Canada, rather than just a valid NANPA number.
   1972    * Warning: In most cases, you want to use {@link #isValidNumber} instead. For example, this
   1973    * method will mark numbers from British Crown dependencies such as the Isle of Man as invalid for
   1974    * the region "GB" (United Kingdom), since it has its own region code, "IM", which may be
   1975    * undesirable.
   1976    *
   1977    * @param number       the phone number that we want to validate
   1978    * @param regionCode   the region that we want to validate the phone number for
   1979    * @return  a boolean that indicates whether the number is of a valid pattern
   1980    */
   1981   public boolean isValidNumberForRegion(PhoneNumber number, String regionCode) {
   1982     int countryCode = number.getCountryCode();
   1983     PhoneMetadata metadata = getMetadataForRegionOrCallingCode(countryCode, regionCode);
   1984     if ((metadata == null) ||
   1985         (!REGION_CODE_FOR_NON_GEO_ENTITY.equals(regionCode) &&
   1986          countryCode != getCountryCodeForValidRegion(regionCode))) {
   1987       // Either the region code was invalid, or the country calling code for this number does not
   1988       // match that of the region code.
   1989       return false;
   1990     }
   1991     PhoneNumberDesc generalNumDesc = metadata.getGeneralDesc();
   1992     String nationalSignificantNumber = getNationalSignificantNumber(number);
   1993 
   1994     // For regions where we don't have metadata for PhoneNumberDesc, we treat any number passed in
   1995     // as a valid number if its national significant number is between the minimum and maximum
   1996     // lengths defined by ITU for a national significant number.
   1997     if (!generalNumDesc.hasNationalNumberPattern()) {
   1998       int numberLength = nationalSignificantNumber.length();
   1999       return numberLength > MIN_LENGTH_FOR_NSN && numberLength <= MAX_LENGTH_FOR_NSN;
   2000     }
   2001     return getNumberTypeHelper(nationalSignificantNumber, metadata) != PhoneNumberType.UNKNOWN;
   2002   }
   2003 
   2004   /**
   2005    * Returns the region where a phone number is from. This could be used for geocoding at the region
   2006    * level.
   2007    *
   2008    * @param number  the phone number whose origin we want to know
   2009    * @return  the region where the phone number is from, or null if no region matches this calling
   2010    *     code
   2011    */
   2012   public String getRegionCodeForNumber(PhoneNumber number) {
   2013     int countryCode = number.getCountryCode();
   2014     List<String> regions = countryCallingCodeToRegionCodeMap.get(countryCode);
   2015     if (regions == null) {
   2016       String numberString = getNationalSignificantNumber(number);
   2017       LOGGER.log(Level.WARNING,
   2018                  "Missing/invalid country_code (" + countryCode + ") for number " + numberString);
   2019       return null;
   2020     }
   2021     if (regions.size() == 1) {
   2022       return regions.get(0);
   2023     } else {
   2024       return getRegionCodeForNumberFromRegionList(number, regions);
   2025     }
   2026   }
   2027 
   2028   private String getRegionCodeForNumberFromRegionList(PhoneNumber number,
   2029                                                       List<String> regionCodes) {
   2030     String nationalNumber = getNationalSignificantNumber(number);
   2031     for (String regionCode : regionCodes) {
   2032       // If leadingDigits is present, use this. Otherwise, do full validation.
   2033       // Metadata cannot be null because the region codes come from the country calling code map.
   2034       PhoneMetadata metadata = getMetadataForRegion(regionCode);
   2035       if (metadata.hasLeadingDigits()) {
   2036         if (regexCache.getPatternForRegex(metadata.getLeadingDigits())
   2037                 .matcher(nationalNumber).lookingAt()) {
   2038           return regionCode;
   2039         }
   2040       } else if (getNumberTypeHelper(nationalNumber, metadata) != PhoneNumberType.UNKNOWN) {
   2041         return regionCode;
   2042       }
   2043     }
   2044     return null;
   2045   }
   2046 
   2047   /**
   2048    * Returns the region code that matches the specific country calling code. In the case of no
   2049    * region code being found, ZZ will be returned. In the case of multiple regions, the one
   2050    * designated in the metadata as the "main" region for this calling code will be returned.
   2051    */
   2052   public String getRegionCodeForCountryCode(int countryCallingCode) {
   2053     List<String> regionCodes = countryCallingCodeToRegionCodeMap.get(countryCallingCode);
   2054     return regionCodes == null ? UNKNOWN_REGION : regionCodes.get(0);
   2055   }
   2056 
   2057   /**
   2058    * Returns a list with the region codes that match the specific country calling code. For
   2059    * non-geographical country calling codes, the region code 001 is returned. Also, in the case
   2060    * of no region code being found, an empty list is returned.
   2061    */
   2062   public List<String> getRegionCodesForCountryCode(int countryCallingCode) {
   2063     List<String> regionCodes = countryCallingCodeToRegionCodeMap.get(countryCallingCode);
   2064     return Collections.unmodifiableList(regionCodes == null ? new ArrayList<String>(0)
   2065                                                             : regionCodes);
   2066   }
   2067 
   2068   /**
   2069    * Returns the country calling code for a specific region. For example, this would be 1 for the
   2070    * United States, and 64 for New Zealand.
   2071    *
   2072    * @param regionCode  the region that we want to get the country calling code for
   2073    * @return  the country calling code for the region denoted by regionCode
   2074    */
   2075   public int getCountryCodeForRegion(String regionCode) {
   2076     if (!isValidRegionCode(regionCode)) {
   2077       LOGGER.log(Level.WARNING,
   2078                  "Invalid or missing region code ("
   2079                   + ((regionCode == null) ? "null" : regionCode)
   2080                   + ") provided.");
   2081       return 0;
   2082     }
   2083     return getCountryCodeForValidRegion(regionCode);
   2084   }
   2085 
   2086   /**
   2087    * Returns the country calling code for a specific region. For example, this would be 1 for the
   2088    * United States, and 64 for New Zealand. Assumes the region is already valid.
   2089    *
   2090    * @param regionCode  the region that we want to get the country calling code for
   2091    * @return  the country calling code for the region denoted by regionCode
   2092    * @throws IllegalArgumentException if the region is invalid
   2093    */
   2094   private int getCountryCodeForValidRegion(String regionCode) {
   2095     PhoneMetadata metadata = getMetadataForRegion(regionCode);
   2096     if (metadata == null) {
   2097       throw new IllegalArgumentException("Invalid region code: " + regionCode);
   2098     }
   2099     return metadata.getCountryCode();
   2100   }
   2101 
   2102   /**
   2103    * Returns the national dialling prefix for a specific region. For example, this would be 1 for
   2104    * the United States, and 0 for New Zealand. Set stripNonDigits to true to strip symbols like "~"
   2105    * (which indicates a wait for a dialling tone) from the prefix returned. If no national prefix is
   2106    * present, we return null.
   2107    *
   2108    * <p>Warning: Do not use this method for do-your-own formatting - for some regions, the
   2109    * national dialling prefix is used only for certain types of numbers. Use the library's
   2110    * formatting functions to prefix the national prefix when required.
   2111    *
   2112    * @param regionCode  the region that we want to get the dialling prefix for
   2113    * @param stripNonDigits  true to strip non-digits from the national dialling prefix
   2114    * @return  the dialling prefix for the region denoted by regionCode
   2115    */
   2116   public String getNddPrefixForRegion(String regionCode, boolean stripNonDigits) {
   2117     PhoneMetadata metadata = getMetadataForRegion(regionCode);
   2118     if (metadata == null) {
   2119       LOGGER.log(Level.WARNING,
   2120                  "Invalid or missing region code ("
   2121                   + ((regionCode == null) ? "null" : regionCode)
   2122                   + ") provided.");
   2123       return null;
   2124     }
   2125     String nationalPrefix = metadata.getNationalPrefix();
   2126     // If no national prefix was found, we return null.
   2127     if (nationalPrefix.length() == 0) {
   2128       return null;
   2129     }
   2130     if (stripNonDigits) {
   2131       // Note: if any other non-numeric symbols are ever used in national prefixes, these would have
   2132       // to be removed here as well.
   2133       nationalPrefix = nationalPrefix.replace("~", "");
   2134     }
   2135     return nationalPrefix;
   2136   }
   2137 
   2138   /**
   2139    * Checks if this is a region under the North American Numbering Plan Administration (NANPA).
   2140    *
   2141    * @return  true if regionCode is one of the regions under NANPA
   2142    */
   2143   public boolean isNANPACountry(String regionCode) {
   2144     return nanpaRegions.contains(regionCode);
   2145   }
   2146 
   2147   /**
   2148    * Checks whether the country calling code is from a region whose national significant number
   2149    * could contain a leading zero. An example of such a region is Italy. Returns false if no
   2150    * metadata for the country is found.
   2151    */
   2152   boolean isLeadingZeroPossible(int countryCallingCode) {
   2153     PhoneMetadata mainMetadataForCallingCode =
   2154         getMetadataForRegionOrCallingCode(countryCallingCode,
   2155                                           getRegionCodeForCountryCode(countryCallingCode));
   2156     if (mainMetadataForCallingCode == null) {
   2157       return false;
   2158     }
   2159     return mainMetadataForCallingCode.isLeadingZeroPossible();
   2160   }
   2161 
   2162   /**
   2163    * Checks if the number is a valid vanity (alpha) number such as 800 MICROSOFT. A valid vanity
   2164    * number will start with at least 3 digits and will have three or more alpha characters. This
   2165    * does not do region-specific checks - to work out if this number is actually valid for a region,
   2166    * it should be parsed and methods such as {@link #isPossibleNumberWithReason} and
   2167    * {@link #isValidNumber} should be used.
   2168    *
   2169    * @param number  the number that needs to be checked
   2170    * @return  true if the number is a valid vanity number
   2171    */
   2172   public boolean isAlphaNumber(String number) {
   2173     if (!isViablePhoneNumber(number)) {
   2174       // Number is too short, or doesn't match the basic phone number pattern.
   2175       return false;
   2176     }
   2177     StringBuilder strippedNumber = new StringBuilder(number);
   2178     maybeStripExtension(strippedNumber);
   2179     return VALID_ALPHA_PHONE_PATTERN.matcher(strippedNumber).matches();
   2180   }
   2181 
   2182   /**
   2183    * Convenience wrapper around {@link #isPossibleNumberWithReason}. Instead of returning the reason
   2184    * for failure, this method returns a boolean value.
   2185    * @param number  the number that needs to be checked
   2186    * @return  true if the number is possible
   2187    */
   2188   public boolean isPossibleNumber(PhoneNumber number) {
   2189     return isPossibleNumberWithReason(number) == ValidationResult.IS_POSSIBLE;
   2190   }
   2191 
   2192   /**
   2193    * Helper method to check a number against a particular pattern and determine whether it matches,
   2194    * or is too short or too long. Currently, if a number pattern suggests that numbers of length 7
   2195    * and 10 are possible, and a number in between these possible lengths is entered, such as of
   2196    * length 8, this will return TOO_LONG.
   2197    */
   2198   private ValidationResult testNumberLengthAgainstPattern(Pattern numberPattern, String number) {
   2199     Matcher numberMatcher = numberPattern.matcher(number);
   2200     if (numberMatcher.matches()) {
   2201       return ValidationResult.IS_POSSIBLE;
   2202     }
   2203     if (numberMatcher.lookingAt()) {
   2204       return ValidationResult.TOO_LONG;
   2205     } else {
   2206       return ValidationResult.TOO_SHORT;
   2207     }
   2208   }
   2209 
   2210   /**
   2211    * Check whether a phone number is a possible number. It provides a more lenient check than
   2212    * {@link #isValidNumber} in the following sense:
   2213    *<ol>
   2214    * <li> It only checks the length of phone numbers. In particular, it doesn't check starting
   2215    *      digits of the number.
   2216    * <li> It doesn't attempt to figure out the type of the number, but uses general rules which
   2217    *      applies to all types of phone numbers in a region. Therefore, it is much faster than
   2218    *      isValidNumber.
   2219    * <li> For fixed line numbers, many regions have the concept of area code, which together with
   2220    *      subscriber number constitute the national significant number. It is sometimes okay to dial
   2221    *      the subscriber number only when dialing in the same area. This function will return
   2222    *      true if the subscriber-number-only version is passed in. On the other hand, because
   2223    *      isValidNumber validates using information on both starting digits (for fixed line
   2224    *      numbers, that would most likely be area codes) and length (obviously includes the
   2225    *      length of area codes for fixed line numbers), it will return false for the
   2226    *      subscriber-number-only version.
   2227    * </ol>
   2228    * @param number  the number that needs to be checked
   2229    * @return  a ValidationResult object which indicates whether the number is possible
   2230    */
   2231   public ValidationResult isPossibleNumberWithReason(PhoneNumber number) {
   2232     String nationalNumber = getNationalSignificantNumber(number);
   2233     int countryCode = number.getCountryCode();
   2234     // Note: For Russian Fed and NANPA numbers, we just use the rules from the default region (US or
   2235     // Russia) since the getRegionCodeForNumber will not work if the number is possible but not
   2236     // valid. This would need to be revisited if the possible number pattern ever differed between
   2237     // various regions within those plans.
   2238     if (!hasValidCountryCallingCode(countryCode)) {
   2239       return ValidationResult.INVALID_COUNTRY_CODE;
   2240     }
   2241     String regionCode = getRegionCodeForCountryCode(countryCode);
   2242     // Metadata cannot be null because the country calling code is valid.
   2243     PhoneMetadata metadata = getMetadataForRegionOrCallingCode(countryCode, regionCode);
   2244     PhoneNumberDesc generalNumDesc = metadata.getGeneralDesc();
   2245     // Handling case of numbers with no metadata.
   2246     if (!generalNumDesc.hasNationalNumberPattern()) {
   2247       LOGGER.log(Level.FINER, "Checking if number is possible with incomplete metadata.");
   2248       int numberLength = nationalNumber.length();
   2249       if (numberLength < MIN_LENGTH_FOR_NSN) {
   2250         return ValidationResult.TOO_SHORT;
   2251       } else if (numberLength > MAX_LENGTH_FOR_NSN) {
   2252         return ValidationResult.TOO_LONG;
   2253       } else {
   2254         return ValidationResult.IS_POSSIBLE;
   2255       }
   2256     }
   2257     Pattern possibleNumberPattern =
   2258         regexCache.getPatternForRegex(generalNumDesc.getPossibleNumberPattern());
   2259     return testNumberLengthAgainstPattern(possibleNumberPattern, nationalNumber);
   2260   }
   2261 
   2262   /**
   2263    * Check whether a phone number is a possible number given a number in the form of a string, and
   2264    * the region where the number could be dialed from. It provides a more lenient check than
   2265    * {@link #isValidNumber}. See {@link #isPossibleNumber(PhoneNumber)} for details.
   2266    *
   2267    * <p>This method first parses the number, then invokes {@link #isPossibleNumber(PhoneNumber)}
   2268    * with the resultant PhoneNumber object.
   2269    *
   2270    * @param number  the number that needs to be checked, in the form of a string
   2271    * @param regionDialingFrom  the region that we are expecting the number to be dialed from.
   2272    *     Note this is different from the region where the number belongs.  For example, the number
   2273    *     +1 650 253 0000 is a number that belongs to US. When written in this form, it can be
   2274    *     dialed from any region. When it is written as 00 1 650 253 0000, it can be dialed from any
   2275    *     region which uses an international dialling prefix of 00. When it is written as
   2276    *     650 253 0000, it can only be dialed from within the US, and when written as 253 0000, it
   2277    *     can only be dialed from within a smaller area in the US (Mountain View, CA, to be more
   2278    *     specific).
   2279    * @return  true if the number is possible
   2280    */
   2281   public boolean isPossibleNumber(String number, String regionDialingFrom) {
   2282     try {
   2283       return isPossibleNumber(parse(number, regionDialingFrom));
   2284     } catch (NumberParseException e) {
   2285       return false;
   2286     }
   2287   }
   2288 
   2289   /**
   2290    * Attempts to extract a valid number from a phone number that is too long to be valid, and resets
   2291    * the PhoneNumber object passed in to that valid version. If no valid number could be extracted,
   2292    * the PhoneNumber object passed in will not be modified.
   2293    * @param number a PhoneNumber object which contains a number that is too long to be valid.
   2294    * @return  true if a valid phone number can be successfully extracted.
   2295    */
   2296   public boolean truncateTooLongNumber(PhoneNumber number) {
   2297     if (isValidNumber(number)) {
   2298       return true;
   2299     }
   2300     PhoneNumber numberCopy = new PhoneNumber();
   2301     numberCopy.mergeFrom(number);
   2302     long nationalNumber = number.getNationalNumber();
   2303     do {
   2304       nationalNumber /= 10;
   2305       numberCopy.setNationalNumber(nationalNumber);
   2306       if (isPossibleNumberWithReason(numberCopy) == ValidationResult.TOO_SHORT ||
   2307           nationalNumber == 0) {
   2308         return false;
   2309       }
   2310     } while (!isValidNumber(numberCopy));
   2311     number.setNationalNumber(nationalNumber);
   2312     return true;
   2313   }
   2314 
   2315   /**
   2316    * Gets an {@link com.android.i18n.phonenumbers.AsYouTypeFormatter} for the specific region.
   2317    *
   2318    * @param regionCode  the region where the phone number is being entered
   2319    * @return  an {@link com.android.i18n.phonenumbers.AsYouTypeFormatter} object, which can be used
   2320    *     to format phone numbers in the specific region "as you type"
   2321    */
   2322   public AsYouTypeFormatter getAsYouTypeFormatter(String regionCode) {
   2323     return new AsYouTypeFormatter(regionCode);
   2324   }
   2325 
   2326   // Extracts country calling code from fullNumber, returns it and places the remaining number in
   2327   // nationalNumber. It assumes that the leading plus sign or IDD has already been removed. Returns
   2328   // 0 if fullNumber doesn't start with a valid country calling code, and leaves nationalNumber
   2329   // unmodified.
   2330   int extractCountryCode(StringBuilder fullNumber, StringBuilder nationalNumber) {
   2331     if ((fullNumber.length() == 0) || (fullNumber.charAt(0) == '0')) {
   2332       // Country codes do not begin with a '0'.
   2333       return 0;
   2334     }
   2335     int potentialCountryCode;
   2336     int numberLength = fullNumber.length();
   2337     for (int i = 1; i <= MAX_LENGTH_COUNTRY_CODE && i <= numberLength; i++) {
   2338       potentialCountryCode = Integer.parseInt(fullNumber.substring(0, i));
   2339       if (countryCallingCodeToRegionCodeMap.containsKey(potentialCountryCode)) {
   2340         nationalNumber.append(fullNumber.substring(i));
   2341         return potentialCountryCode;
   2342       }
   2343     }
   2344     return 0;
   2345   }
   2346 
   2347   /**
   2348    * Tries to extract a country calling code from a number. This method will return zero if no
   2349    * country calling code is considered to be present. Country calling codes are extracted in the
   2350    * following ways:
   2351    * <ul>
   2352    *  <li> by stripping the international dialing prefix of the region the person is dialing from,
   2353    *       if this is present in the number, and looking at the next digits
   2354    *  <li> by stripping the '+' sign if present and then looking at the next digits
   2355    *  <li> by comparing the start of the number and the country calling code of the default region.
   2356    *       If the number is not considered possible for the numbering plan of the default region
   2357    *       initially, but starts with the country calling code of this region, validation will be
   2358    *       reattempted after stripping this country calling code. If this number is considered a
   2359    *       possible number, then the first digits will be considered the country calling code and
   2360    *       removed as such.
   2361    * </ul>
   2362    * It will throw a NumberParseException if the number starts with a '+' but the country calling
   2363    * code supplied after this does not match that of any known region.
   2364    *
   2365    * @param number  non-normalized telephone number that we wish to extract a country calling
   2366    *     code from - may begin with '+'
   2367    * @param defaultRegionMetadata  metadata about the region this number may be from
   2368    * @param nationalNumber  a string buffer to store the national significant number in, in the case
   2369    *     that a country calling code was extracted. The number is appended to any existing contents.
   2370    *     If no country calling code was extracted, this will be left unchanged.
   2371    * @param keepRawInput  true if the country_code_source and preferred_carrier_code fields of
   2372    *     phoneNumber should be populated.
   2373    * @param phoneNumber  the PhoneNumber object where the country_code and country_code_source need
   2374    *     to be populated. Note the country_code is always populated, whereas country_code_source is
   2375    *     only populated when keepCountryCodeSource is true.
   2376    * @return  the country calling code extracted or 0 if none could be extracted
   2377    */
   2378   // @VisibleForTesting
   2379   int maybeExtractCountryCode(String number, PhoneMetadata defaultRegionMetadata,
   2380                               StringBuilder nationalNumber, boolean keepRawInput,
   2381                               PhoneNumber phoneNumber)
   2382       throws NumberParseException {
   2383     if (number.length() == 0) {
   2384       return 0;
   2385     }
   2386     StringBuilder fullNumber = new StringBuilder(number);
   2387     // Set the default prefix to be something that will never match.
   2388     String possibleCountryIddPrefix = "NonMatch";
   2389     if (defaultRegionMetadata != null) {
   2390       possibleCountryIddPrefix = defaultRegionMetadata.getInternationalPrefix();
   2391     }
   2392 
   2393     CountryCodeSource countryCodeSource =
   2394         maybeStripInternationalPrefixAndNormalize(fullNumber, possibleCountryIddPrefix);
   2395     if (keepRawInput) {
   2396       phoneNumber.setCountryCodeSource(countryCodeSource);
   2397     }
   2398     if (countryCodeSource != CountryCodeSource.FROM_DEFAULT_COUNTRY) {
   2399       if (fullNumber.length() <= MIN_LENGTH_FOR_NSN) {
   2400         throw new NumberParseException(NumberParseException.ErrorType.TOO_SHORT_AFTER_IDD,
   2401                                        "Phone number had an IDD, but after this was not "
   2402                                        + "long enough to be a viable phone number.");
   2403       }
   2404       int potentialCountryCode = extractCountryCode(fullNumber, nationalNumber);
   2405       if (potentialCountryCode != 0) {
   2406         phoneNumber.setCountryCode(potentialCountryCode);
   2407         return potentialCountryCode;
   2408       }
   2409 
   2410       // If this fails, they must be using a strange country calling code that we don't recognize,
   2411       // or that doesn't exist.
   2412       throw new NumberParseException(NumberParseException.ErrorType.INVALID_COUNTRY_CODE,
   2413                                      "Country calling code supplied was not recognised.");
   2414     } else if (defaultRegionMetadata != null) {
   2415       // Check to see if the number starts with the country calling code for the default region. If
   2416       // so, we remove the country calling code, and do some checks on the validity of the number
   2417       // before and after.
   2418       int defaultCountryCode = defaultRegionMetadata.getCountryCode();
   2419       String defaultCountryCodeString = String.valueOf(defaultCountryCode);
   2420       String normalizedNumber = fullNumber.toString();
   2421       if (normalizedNumber.startsWith(defaultCountryCodeString)) {
   2422         StringBuilder potentialNationalNumber =
   2423             new StringBuilder(normalizedNumber.substring(defaultCountryCodeString.length()));
   2424         PhoneNumberDesc generalDesc = defaultRegionMetadata.getGeneralDesc();
   2425         Pattern validNumberPattern =
   2426             regexCache.getPatternForRegex(generalDesc.getNationalNumberPattern());
   2427         maybeStripNationalPrefixAndCarrierCode(
   2428             potentialNationalNumber, defaultRegionMetadata, null /* Don't need the carrier code */);
   2429         Pattern possibleNumberPattern =
   2430             regexCache.getPatternForRegex(generalDesc.getPossibleNumberPattern());
   2431         // If the number was not valid before but is valid now, or if it was too long before, we
   2432         // consider the number with the country calling code stripped to be a better result and
   2433         // keep that instead.
   2434         if ((!validNumberPattern.matcher(fullNumber).matches() &&
   2435              validNumberPattern.matcher(potentialNationalNumber).matches()) ||
   2436              testNumberLengthAgainstPattern(possibleNumberPattern, fullNumber.toString())
   2437                   == ValidationResult.TOO_LONG) {
   2438           nationalNumber.append(potentialNationalNumber);
   2439           if (keepRawInput) {
   2440             phoneNumber.setCountryCodeSource(CountryCodeSource.FROM_NUMBER_WITHOUT_PLUS_SIGN);
   2441           }
   2442           phoneNumber.setCountryCode(defaultCountryCode);
   2443           return defaultCountryCode;
   2444         }
   2445       }
   2446     }
   2447     // No country calling code present.
   2448     phoneNumber.setCountryCode(0);
   2449     return 0;
   2450   }
   2451 
   2452   /**
   2453    * Strips the IDD from the start of the number if present. Helper function used by
   2454    * maybeStripInternationalPrefixAndNormalize.
   2455    */
   2456   private boolean parsePrefixAsIdd(Pattern iddPattern, StringBuilder number) {
   2457     Matcher m = iddPattern.matcher(number);
   2458     if (m.lookingAt()) {
   2459       int matchEnd = m.end();
   2460       // Only strip this if the first digit after the match is not a 0, since country calling codes
   2461       // cannot begin with 0.
   2462       Matcher digitMatcher = CAPTURING_DIGIT_PATTERN.matcher(number.substring(matchEnd));
   2463       if (digitMatcher.find()) {
   2464         String normalizedGroup = normalizeDigitsOnly(digitMatcher.group(1));
   2465         if (normalizedGroup.equals("0")) {
   2466           return false;
   2467         }
   2468       }
   2469       number.delete(0, matchEnd);
   2470       return true;
   2471     }
   2472     return false;
   2473   }
   2474 
   2475   /**
   2476    * Strips any international prefix (such as +, 00, 011) present in the number provided, normalizes
   2477    * the resulting number, and indicates if an international prefix was present.
   2478    *
   2479    * @param number  the non-normalized telephone number that we wish to strip any international
   2480    *     dialing prefix from.
   2481    * @param possibleIddPrefix  the international direct dialing prefix from the region we
   2482    *     think this number may be dialed in
   2483    * @return  the corresponding CountryCodeSource if an international dialing prefix could be
   2484    *     removed from the number, otherwise CountryCodeSource.FROM_DEFAULT_COUNTRY if the number did
   2485    *     not seem to be in international format.
   2486    */
   2487   // @VisibleForTesting
   2488   CountryCodeSource maybeStripInternationalPrefixAndNormalize(
   2489       StringBuilder number,
   2490       String possibleIddPrefix) {
   2491     if (number.length() == 0) {
   2492       return CountryCodeSource.FROM_DEFAULT_COUNTRY;
   2493     }
   2494     // Check to see if the number begins with one or more plus signs.
   2495     Matcher m = PLUS_CHARS_PATTERN.matcher(number);
   2496     if (m.lookingAt()) {
   2497       number.delete(0, m.end());
   2498       // Can now normalize the rest of the number since we've consumed the "+" sign at the start.
   2499       normalize(number);
   2500       return CountryCodeSource.FROM_NUMBER_WITH_PLUS_SIGN;
   2501     }
   2502     // Attempt to parse the first digits as an international prefix.
   2503     Pattern iddPattern = regexCache.getPatternForRegex(possibleIddPrefix);
   2504     normalize(number);
   2505     return parsePrefixAsIdd(iddPattern, number)
   2506            ? CountryCodeSource.FROM_NUMBER_WITH_IDD
   2507            : CountryCodeSource.FROM_DEFAULT_COUNTRY;
   2508   }
   2509 
   2510   /**
   2511    * Strips any national prefix (such as 0, 1) present in the number provided.
   2512    *
   2513    * @param number  the normalized telephone number that we wish to strip any national
   2514    *     dialing prefix from
   2515    * @param metadata  the metadata for the region that we think this number is from
   2516    * @param carrierCode  a place to insert the carrier code if one is extracted
   2517    * @return true if a national prefix or carrier code (or both) could be extracted.
   2518    */
   2519   // @VisibleForTesting
   2520   boolean maybeStripNationalPrefixAndCarrierCode(
   2521       StringBuilder number, PhoneMetadata metadata, StringBuilder carrierCode) {
   2522     int numberLength = number.length();
   2523     String possibleNationalPrefix = metadata.getNationalPrefixForParsing();
   2524     if (numberLength == 0 || possibleNationalPrefix.length() == 0) {
   2525       // Early return for numbers of zero length.
   2526       return false;
   2527     }
   2528     // Attempt to parse the first digits as a national prefix.
   2529     Matcher prefixMatcher = regexCache.getPatternForRegex(possibleNationalPrefix).matcher(number);
   2530     if (prefixMatcher.lookingAt()) {
   2531       Pattern nationalNumberRule =
   2532           regexCache.getPatternForRegex(metadata.getGeneralDesc().getNationalNumberPattern());
   2533       // Check if the original number is viable.
   2534       boolean isViableOriginalNumber = nationalNumberRule.matcher(number).matches();
   2535       // prefixMatcher.group(numOfGroups) == null implies nothing was captured by the capturing
   2536       // groups in possibleNationalPrefix; therefore, no transformation is necessary, and we just
   2537       // remove the national prefix.
   2538       int numOfGroups = prefixMatcher.groupCount();
   2539       String transformRule = metadata.getNationalPrefixTransformRule();
   2540       if (transformRule == null || transformRule.length() == 0 ||
   2541           prefixMatcher.group(numOfGroups) == null) {
   2542         // If the original number was viable, and the resultant number is not, we return.
   2543         if (isViableOriginalNumber &&
   2544             !nationalNumberRule.matcher(number.substring(prefixMatcher.end())).matches()) {
   2545           return false;
   2546         }
   2547         if (carrierCode != null && numOfGroups > 0 && prefixMatcher.group(numOfGroups) != null) {
   2548           carrierCode.append(prefixMatcher.group(1));
   2549         }
   2550         number.delete(0, prefixMatcher.end());
   2551         return true;
   2552       } else {
   2553         // Check that the resultant number is still viable. If not, return. Check this by copying
   2554         // the string buffer and making the transformation on the copy first.
   2555         StringBuilder transformedNumber = new StringBuilder(number);
   2556         transformedNumber.replace(0, numberLength, prefixMatcher.replaceFirst(transformRule));
   2557         if (isViableOriginalNumber &&
   2558             !nationalNumberRule.matcher(transformedNumber.toString()).matches()) {
   2559           return false;
   2560         }
   2561         if (carrierCode != null && numOfGroups > 1) {
   2562           carrierCode.append(prefixMatcher.group(1));
   2563         }
   2564         number.replace(0, number.length(), transformedNumber.toString());
   2565         return true;
   2566       }
   2567     }
   2568     return false;
   2569   }
   2570 
   2571   /**
   2572    * Strips any extension (as in, the part of the number dialled after the call is connected,
   2573    * usually indicated with extn, ext, x or similar) from the end of the number, and returns it.
   2574    *
   2575    * @param number  the non-normalized telephone number that we wish to strip the extension from
   2576    * @return        the phone extension
   2577    */
   2578   // @VisibleForTesting
   2579   String maybeStripExtension(StringBuilder number) {
   2580     Matcher m = EXTN_PATTERN.matcher(number);
   2581     // If we find a potential extension, and the number preceding this is a viable number, we assume
   2582     // it is an extension.
   2583     if (m.find() && isViablePhoneNumber(number.substring(0, m.start()))) {
   2584       // The numbers are captured into groups in the regular expression.
   2585       for (int i = 1, length = m.groupCount(); i <= length; i++) {
   2586         if (m.group(i) != null) {
   2587           // We go through the capturing groups until we find one that captured some digits. If none
   2588           // did, then we will return the empty string.
   2589           String extension = m.group(i);
   2590           number.delete(m.start(), number.length());
   2591           return extension;
   2592         }
   2593       }
   2594     }
   2595     return "";
   2596   }
   2597 
   2598   /**
   2599    * Checks to see that the region code used is valid, or if it is not valid, that the number to
   2600    * parse starts with a + symbol so that we can attempt to infer the region from the number.
   2601    * Returns false if it cannot use the region provided and the region cannot be inferred.
   2602    */
   2603   private boolean checkRegionForParsing(String numberToParse, String defaultRegion) {
   2604     if (!isValidRegionCode(defaultRegion)) {
   2605       // If the number is null or empty, we can't infer the region.
   2606       if (numberToParse == null || numberToParse.length() == 0 ||
   2607           !PLUS_CHARS_PATTERN.matcher(numberToParse).lookingAt()) {
   2608         return false;
   2609       }
   2610     }
   2611     return true;
   2612   }
   2613 
   2614   /**
   2615    * Parses a string and returns it in proto buffer format. This method will throw a
   2616    * {@link com.android.i18n.phonenumbers.NumberParseException} if the number is not considered to be
   2617    * a possible number. Note that validation of whether the number is actually a valid number for a
   2618    * particular region is not performed. This can be done separately with {@link #isValidNumber}.
   2619    *
   2620    * @param numberToParse     number that we are attempting to parse. This can contain formatting
   2621    *                          such as +, ( and -, as well as a phone number extension. It can also
   2622    *                          be provided in RFC3966 format.
   2623    * @param defaultRegion     region that we are expecting the number to be from. This is only used
   2624    *                          if the number being parsed is not written in international format.
   2625    *                          The country_code for the number in this case would be stored as that
   2626    *                          of the default region supplied. If the number is guaranteed to
   2627    *                          start with a '+' followed by the country calling code, then
   2628    *                          "ZZ" or null can be supplied.
   2629    * @return                  a phone number proto buffer filled with the parsed number
   2630    * @throws NumberParseException  if the string is not considered to be a viable phone number or if
   2631    *                               no default region was supplied and the number is not in
   2632    *                               international format (does not start with +)
   2633    */
   2634   public PhoneNumber parse(String numberToParse, String defaultRegion)
   2635       throws NumberParseException {
   2636     PhoneNumber phoneNumber = new PhoneNumber();
   2637     parse(numberToParse, defaultRegion, phoneNumber);
   2638     return phoneNumber;
   2639   }
   2640 
   2641   /**
   2642    * Same as {@link #parse(String, String)}, but accepts mutable PhoneNumber as a parameter to
   2643    * decrease object creation when invoked many times.
   2644    */
   2645   public void parse(String numberToParse, String defaultRegion, PhoneNumber phoneNumber)
   2646       throws NumberParseException {
   2647     parseHelper(numberToParse, defaultRegion, false, true, phoneNumber);
   2648   }
   2649 
   2650   /**
   2651    * Parses a string and returns it in proto buffer format. This method differs from {@link #parse}
   2652    * in that it always populates the raw_input field of the protocol buffer with numberToParse as
   2653    * well as the country_code_source field.
   2654    *
   2655    * @param numberToParse     number that we are attempting to parse. This can contain formatting
   2656    *                          such as +, ( and -, as well as a phone number extension.
   2657    * @param defaultRegion     region that we are expecting the number to be from. This is only used
   2658    *                          if the number being parsed is not written in international format.
   2659    *                          The country calling code for the number in this case would be stored
   2660    *                          as that of the default region supplied.
   2661    * @return                  a phone number proto buffer filled with the parsed number
   2662    * @throws NumberParseException  if the string is not considered to be a viable phone number or if
   2663    *                               no default region was supplied
   2664    */
   2665   public PhoneNumber parseAndKeepRawInput(String numberToParse, String defaultRegion)
   2666       throws NumberParseException {
   2667     PhoneNumber phoneNumber = new PhoneNumber();
   2668     parseAndKeepRawInput(numberToParse, defaultRegion, phoneNumber);
   2669     return phoneNumber;
   2670   }
   2671 
   2672   /**
   2673    * Same as{@link #parseAndKeepRawInput(String, String)}, but accepts a mutable PhoneNumber as
   2674    * a parameter to decrease object creation when invoked many times.
   2675    */
   2676   public void parseAndKeepRawInput(String numberToParse, String defaultRegion,
   2677                                    PhoneNumber phoneNumber)
   2678       throws NumberParseException {
   2679     parseHelper(numberToParse, defaultRegion, true, true, phoneNumber);
   2680   }
   2681 
   2682   /**
   2683    * Returns an iterable over all {@link PhoneNumberMatch PhoneNumberMatches} in {@code text}. This
   2684    * is a shortcut for {@link #findNumbers(CharSequence, String, Leniency, long)
   2685    * getMatcher(text, defaultRegion, Leniency.VALID, Long.MAX_VALUE)}.
   2686    *
   2687    * @param text              the text to search for phone numbers, null for no text
   2688    * @param defaultRegion     region that we are expecting the number to be from. This is only used
   2689    *                          if the number being parsed is not written in international format. The
   2690    *                          country_code for the number in this case would be stored as that of
   2691    *                          the default region supplied. May be null if only international
   2692    *                          numbers are expected.
   2693    */
   2694   public Iterable<PhoneNumberMatch> findNumbers(CharSequence text, String defaultRegion) {
   2695     return findNumbers(text, defaultRegion, Leniency.VALID, Long.MAX_VALUE);
   2696   }
   2697 
   2698   /**
   2699    * Returns an iterable over all {@link PhoneNumberMatch PhoneNumberMatches} in {@code text}.
   2700    *
   2701    * @param text              the text to search for phone numbers, null for no text
   2702    * @param defaultRegion     region that we are expecting the number to be from. This is only used
   2703    *                          if the number being parsed is not written in international format. The
   2704    *                          country_code for the number in this case would be stored as that of
   2705    *                          the default region supplied. May be null if only international
   2706    *                          numbers are expected.
   2707    * @param leniency          the leniency to use when evaluating candidate phone numbers
   2708    * @param maxTries          the maximum number of invalid numbers to try before giving up on the
   2709    *                          text. This is to cover degenerate cases where the text has a lot of
   2710    *                          false positives in it. Must be {@code >= 0}.
   2711    */
   2712   public Iterable<PhoneNumberMatch> findNumbers(
   2713       final CharSequence text, final String defaultRegion, final Leniency leniency,
   2714       final long maxTries) {
   2715 
   2716     return new Iterable<PhoneNumberMatch>() {
   2717       public Iterator<PhoneNumberMatch> iterator() {
   2718         return new PhoneNumberMatcher(
   2719             PhoneNumberUtil.this, text, defaultRegion, leniency, maxTries);
   2720       }
   2721     };
   2722   }
   2723 
   2724   /**
   2725    * Parses a string and fills up the phoneNumber. This method is the same as the public
   2726    * parse() method, with the exception that it allows the default region to be null, for use by
   2727    * isNumberMatch(). checkRegion should be set to false if it is permitted for the default region
   2728    * to be null or unknown ("ZZ").
   2729    */
   2730   private void parseHelper(String numberToParse, String defaultRegion, boolean keepRawInput,
   2731                            boolean checkRegion, PhoneNumber phoneNumber)
   2732       throws NumberParseException {
   2733     if (numberToParse == null) {
   2734       throw new NumberParseException(NumberParseException.ErrorType.NOT_A_NUMBER,
   2735                                      "The phone number supplied was null.");
   2736     } else if (numberToParse.length() > MAX_INPUT_STRING_LENGTH) {
   2737       throw new NumberParseException(NumberParseException.ErrorType.TOO_LONG,
   2738                                      "The string supplied was too long to parse.");
   2739     }
   2740 
   2741     StringBuilder nationalNumber = new StringBuilder();
   2742     buildNationalNumberForParsing(numberToParse, nationalNumber);
   2743 
   2744     if (!isViablePhoneNumber(nationalNumber.toString())) {
   2745       throw new NumberParseException(NumberParseException.ErrorType.NOT_A_NUMBER,
   2746                                      "The string supplied did not seem to be a phone number.");
   2747     }
   2748 
   2749     // Check the region supplied is valid, or that the extracted number starts with some sort of +
   2750     // sign so the number's region can be determined.
   2751     if (checkRegion && !checkRegionForParsing(nationalNumber.toString(), defaultRegion)) {
   2752       throw new NumberParseException(NumberParseException.ErrorType.INVALID_COUNTRY_CODE,
   2753                                      "Missing or invalid default region.");
   2754     }
   2755 
   2756     if (keepRawInput) {
   2757       phoneNumber.setRawInput(numberToParse);
   2758     }
   2759     // Attempt to parse extension first, since it doesn't require region-specific data and we want
   2760     // to have the non-normalised number here.
   2761     String extension = maybeStripExtension(nationalNumber);
   2762     if (extension.length() > 0) {
   2763       phoneNumber.setExtension(extension);
   2764     }
   2765 
   2766     PhoneMetadata regionMetadata = getMetadataForRegion(defaultRegion);
   2767     // Check to see if the number is given in international format so we know whether this number is
   2768     // from the default region or not.
   2769     StringBuilder normalizedNationalNumber = new StringBuilder();
   2770     int countryCode = 0;
   2771     try {
   2772       // TODO: This method should really just take in the string buffer that has already
   2773       // been created, and just remove the prefix, rather than taking in a string and then
   2774       // outputting a string buffer.
   2775       countryCode = maybeExtractCountryCode(nationalNumber.toString(), regionMetadata,
   2776                                             normalizedNationalNumber, keepRawInput, phoneNumber);
   2777     } catch (NumberParseException e) {
   2778       Matcher matcher = PLUS_CHARS_PATTERN.matcher(nationalNumber.toString());
   2779       if (e.getErrorType() == NumberParseException.ErrorType.INVALID_COUNTRY_CODE &&
   2780           matcher.lookingAt()) {
   2781         // Strip the plus-char, and try again.
   2782         countryCode = maybeExtractCountryCode(nationalNumber.substring(matcher.end()),
   2783                                               regionMetadata, normalizedNationalNumber,
   2784                                               keepRawInput, phoneNumber);
   2785         if (countryCode == 0) {
   2786           throw new NumberParseException(NumberParseException.ErrorType.INVALID_COUNTRY_CODE,
   2787                                          "Could not interpret numbers after plus-sign.");
   2788         }
   2789       } else {
   2790         throw new NumberParseException(e.getErrorType(), e.getMessage());
   2791       }
   2792     }
   2793     if (countryCode != 0) {
   2794       String phoneNumberRegion = getRegionCodeForCountryCode(countryCode);
   2795       if (!phoneNumberRegion.equals(defaultRegion)) {
   2796         // Metadata cannot be null because the country calling code is valid.
   2797         regionMetadata = getMetadataForRegionOrCallingCode(countryCode, phoneNumberRegion);
   2798       }
   2799     } else {
   2800       // If no extracted country calling code, use the region supplied instead. The national number
   2801       // is just the normalized version of the number we were given to parse.
   2802       normalize(nationalNumber);
   2803       normalizedNationalNumber.append(nationalNumber);
   2804       if (defaultRegion != null) {
   2805         countryCode = regionMetadata.getCountryCode();
   2806         phoneNumber.setCountryCode(countryCode);
   2807       } else if (keepRawInput) {
   2808         phoneNumber.clearCountryCodeSource();
   2809       }
   2810     }
   2811     if (normalizedNationalNumber.length() < MIN_LENGTH_FOR_NSN) {
   2812       throw new NumberParseException(NumberParseException.ErrorType.TOO_SHORT_NSN,
   2813                                      "The string supplied is too short to be a phone number.");
   2814     }
   2815     if (regionMetadata != null) {
   2816       StringBuilder carrierCode = new StringBuilder();
   2817       maybeStripNationalPrefixAndCarrierCode(normalizedNationalNumber, regionMetadata, carrierCode);
   2818       if (keepRawInput) {
   2819         phoneNumber.setPreferredDomesticCarrierCode(carrierCode.toString());
   2820       }
   2821     }
   2822     int lengthOfNationalNumber = normalizedNationalNumber.length();
   2823     if (lengthOfNationalNumber < MIN_LENGTH_FOR_NSN) {
   2824       throw new NumberParseException(NumberParseException.ErrorType.TOO_SHORT_NSN,
   2825                                      "The string supplied is too short to be a phone number.");
   2826     }
   2827     if (lengthOfNationalNumber > MAX_LENGTH_FOR_NSN) {
   2828       throw new NumberParseException(NumberParseException.ErrorType.TOO_LONG,
   2829                                      "The string supplied is too long to be a phone number.");
   2830     }
   2831     if (normalizedNationalNumber.charAt(0) == '0') {
   2832       phoneNumber.setItalianLeadingZero(true);
   2833     }
   2834     phoneNumber.setNationalNumber(Long.parseLong(normalizedNationalNumber.toString()));
   2835   }
   2836 
   2837   /**
   2838    * Converts numberToParse to a form that we can parse and write it to nationalNumber if it is
   2839    * written in RFC3966; otherwise extract a possible number out of it and write to nationalNumber.
   2840    */
   2841   private void buildNationalNumberForParsing(String numberToParse, StringBuilder nationalNumber) {
   2842     int indexOfPhoneContext = numberToParse.indexOf(RFC3966_PHONE_CONTEXT);
   2843     if (indexOfPhoneContext > 0) {
   2844       int phoneContextStart = indexOfPhoneContext + RFC3966_PHONE_CONTEXT.length();
   2845       // If the phone context contains a phone number prefix, we need to capture it, whereas domains
   2846       // will be ignored.
   2847       if (numberToParse.charAt(phoneContextStart) == PLUS_SIGN) {
   2848         // Additional parameters might follow the phone context. If so, we will remove them here
   2849         // because the parameters after phone context are not important for parsing the
   2850         // phone number.
   2851         int phoneContextEnd = numberToParse.indexOf(';', phoneContextStart);
   2852         if (phoneContextEnd > 0) {
   2853           nationalNumber.append(numberToParse.substring(phoneContextStart, phoneContextEnd));
   2854         } else {
   2855           nationalNumber.append(numberToParse.substring(phoneContextStart));
   2856         }
   2857       }
   2858 
   2859       // Now append everything between the "tel:" prefix and the phone-context. This should include
   2860       // the national number, an optional extension or isdn-subaddress component.
   2861       nationalNumber.append(numberToParse.substring(
   2862           numberToParse.indexOf(RFC3966_PREFIX) + RFC3966_PREFIX.length(), indexOfPhoneContext));
   2863     } else {
   2864       // Extract a possible number from the string passed in (this strips leading characters that
   2865       // could not be the start of a phone number.)
   2866       nationalNumber.append(extractPossibleNumber(numberToParse));
   2867     }
   2868 
   2869     // Delete the isdn-subaddress and everything after it if it is present. Note extension won't
   2870     // appear at the same time with isdn-subaddress according to paragraph 5.3 of the RFC3966 spec,
   2871     int indexOfIsdn = nationalNumber.indexOf(RFC3966_ISDN_SUBADDRESS);
   2872     if (indexOfIsdn > 0) {
   2873       nationalNumber.delete(indexOfIsdn, nationalNumber.length());
   2874     }
   2875     // If both phone context and isdn-subaddress are absent but other parameters are present, the
   2876     // parameters are left in nationalNumber. This is because we are concerned about deleting
   2877     // content from a potential number string when there is no strong evidence that the number is
   2878     // actually written in RFC3966.
   2879   }
   2880 
   2881   /**
   2882    * Takes two phone numbers and compares them for equality.
   2883    *
   2884    * <p>Returns EXACT_MATCH if the country_code, NSN, presence of a leading zero for Italian numbers
   2885    * and any extension present are the same.
   2886    * Returns NSN_MATCH if either or both has no region specified, and the NSNs and extensions are
   2887    * the same.
   2888    * Returns SHORT_NSN_MATCH if either or both has no region specified, or the region specified is
   2889    * the same, and one NSN could be a shorter version of the other number. This includes the case
   2890    * where one has an extension specified, and the other does not.
   2891    * Returns NO_MATCH otherwise.
   2892    * For example, the numbers +1 345 657 1234 and 657 1234 are a SHORT_NSN_MATCH.
   2893    * The numbers +1 345 657 1234 and 345 657 are a NO_MATCH.
   2894    *
   2895    * @param firstNumberIn  first number to compare
   2896    * @param secondNumberIn  second number to compare
   2897    *
   2898    * @return  NO_MATCH, SHORT_NSN_MATCH, NSN_MATCH or EXACT_MATCH depending on the level of equality
   2899    *     of the two numbers, described in the method definition.
   2900    */
   2901   public MatchType isNumberMatch(PhoneNumber firstNumberIn, PhoneNumber secondNumberIn) {
   2902     // Make copies of the phone number so that the numbers passed in are not edited.
   2903     PhoneNumber firstNumber = new PhoneNumber();
   2904     firstNumber.mergeFrom(firstNumberIn);
   2905     PhoneNumber secondNumber = new PhoneNumber();
   2906     secondNumber.mergeFrom(secondNumberIn);
   2907     // First clear raw_input, country_code_source and preferred_domestic_carrier_code fields and any
   2908     // empty-string extensions so that we can use the proto-buffer equality method.
   2909     firstNumber.clearRawInput();
   2910     firstNumber.clearCountryCodeSource();
   2911     firstNumber.clearPreferredDomesticCarrierCode();
   2912     secondNumber.clearRawInput();
   2913     secondNumber.clearCountryCodeSource();
   2914     secondNumber.clearPreferredDomesticCarrierCode();
   2915     if (firstNumber.hasExtension() &&
   2916         firstNumber.getExtension().length() == 0) {
   2917         firstNumber.clearExtension();
   2918     }
   2919     if (secondNumber.hasExtension() &&
   2920         secondNumber.getExtension().length() == 0) {
   2921         secondNumber.clearExtension();
   2922     }
   2923     // Early exit if both had extensions and these are different.
   2924     if (firstNumber.hasExtension() && secondNumber.hasExtension() &&
   2925         !firstNumber.getExtension().equals(secondNumber.getExtension())) {
   2926       return MatchType.NO_MATCH;
   2927     }
   2928     int firstNumberCountryCode = firstNumber.getCountryCode();
   2929     int secondNumberCountryCode = secondNumber.getCountryCode();
   2930     // Both had country_code specified.
   2931     if (firstNumberCountryCode != 0 && secondNumberCountryCode != 0) {
   2932       if (firstNumber.exactlySameAs(secondNumber)) {
   2933         return MatchType.EXACT_MATCH;
   2934       } else if (firstNumberCountryCode == secondNumberCountryCode &&
   2935                  isNationalNumberSuffixOfTheOther(firstNumber, secondNumber)) {
   2936         // A SHORT_NSN_MATCH occurs if there is a difference because of the presence or absence of
   2937         // an 'Italian leading zero', the presence or absence of an extension, or one NSN being a
   2938         // shorter variant of the other.
   2939         return MatchType.SHORT_NSN_MATCH;
   2940       }
   2941       // This is not a match.
   2942       return MatchType.NO_MATCH;
   2943     }
   2944     // Checks cases where one or both country_code fields were not specified. To make equality
   2945     // checks easier, we first set the country_code fields to be equal.
   2946     firstNumber.setCountryCode(secondNumberCountryCode);
   2947     // If all else was the same, then this is an NSN_MATCH.
   2948     if (firstNumber.exactlySameAs(secondNumber)) {
   2949       return MatchType.NSN_MATCH;
   2950     }
   2951     if (isNationalNumberSuffixOfTheOther(firstNumber, secondNumber)) {
   2952       return MatchType.SHORT_NSN_MATCH;
   2953     }
   2954     return MatchType.NO_MATCH;
   2955   }
   2956 
   2957   // Returns true when one national number is the suffix of the other or both are the same.
   2958   private boolean isNationalNumberSuffixOfTheOther(PhoneNumber firstNumber,
   2959                                                    PhoneNumber secondNumber) {
   2960     String firstNumberNationalNumber = String.valueOf(firstNumber.getNationalNumber());
   2961     String secondNumberNationalNumber = String.valueOf(secondNumber.getNationalNumber());
   2962     // Note that endsWith returns true if the numbers are equal.
   2963     return firstNumberNationalNumber.endsWith(secondNumberNationalNumber) ||
   2964            secondNumberNationalNumber.endsWith(firstNumberNationalNumber);
   2965   }
   2966 
   2967   /**
   2968    * Takes two phone numbers as strings and compares them for equality. This is a convenience
   2969    * wrapper for {@link #isNumberMatch(PhoneNumber, PhoneNumber)}. No default region is known.
   2970    *
   2971    * @param firstNumber  first number to compare. Can contain formatting, and can have country
   2972    *     calling code specified with + at the start.
   2973    * @param secondNumber  second number to compare. Can contain formatting, and can have country
   2974    *     calling code specified with + at the start.
   2975    * @return  NOT_A_NUMBER, NO_MATCH, SHORT_NSN_MATCH, NSN_MATCH, EXACT_MATCH. See
   2976    *     {@link #isNumberMatch(PhoneNumber, PhoneNumber)} for more details.
   2977    */
   2978   public MatchType isNumberMatch(String firstNumber, String secondNumber) {
   2979     try {
   2980       PhoneNumber firstNumberAsProto = parse(firstNumber, UNKNOWN_REGION);
   2981       return isNumberMatch(firstNumberAsProto, secondNumber);
   2982     } catch (NumberParseException e) {
   2983       if (e.getErrorType() == NumberParseException.ErrorType.INVALID_COUNTRY_CODE) {
   2984         try {
   2985           PhoneNumber secondNumberAsProto = parse(secondNumber, UNKNOWN_REGION);
   2986           return isNumberMatch(secondNumberAsProto, firstNumber);
   2987         } catch (NumberParseException e2) {
   2988           if (e2.getErrorType() == NumberParseException.ErrorType.INVALID_COUNTRY_CODE) {
   2989             try {
   2990               PhoneNumber firstNumberProto = new PhoneNumber();
   2991               PhoneNumber secondNumberProto = new PhoneNumber();
   2992               parseHelper(firstNumber, null, false, false, firstNumberProto);
   2993               parseHelper(secondNumber, null, false, false, secondNumberProto);
   2994               return isNumberMatch(firstNumberProto, secondNumberProto);
   2995             } catch (NumberParseException e3) {
   2996               // Fall through and return MatchType.NOT_A_NUMBER.
   2997             }
   2998           }
   2999         }
   3000       }
   3001     }
   3002     // One or more of the phone numbers we are trying to match is not a viable phone number.
   3003     return MatchType.NOT_A_NUMBER;
   3004   }
   3005 
   3006   /**
   3007    * Takes two phone numbers and compares them for equality. This is a convenience wrapper for
   3008    * {@link #isNumberMatch(PhoneNumber, PhoneNumber)}. No default region is known.
   3009    *
   3010    * @param firstNumber  first number to compare in proto buffer format.
   3011    * @param secondNumber  second number to compare. Can contain formatting, and can have country
   3012    *     calling code specified with + at the start.
   3013    * @return  NOT_A_NUMBER, NO_MATCH, SHORT_NSN_MATCH, NSN_MATCH, EXACT_MATCH. See
   3014    *     {@link #isNumberMatch(PhoneNumber, PhoneNumber)} for more details.
   3015    */
   3016   public MatchType isNumberMatch(PhoneNumber firstNumber, String secondNumber) {
   3017     // First see if the second number has an implicit country calling code, by attempting to parse
   3018     // it.
   3019     try {
   3020       PhoneNumber secondNumberAsProto = parse(secondNumber, UNKNOWN_REGION);
   3021       return isNumberMatch(firstNumber, secondNumberAsProto);
   3022     } catch (NumberParseException e) {
   3023       if (e.getErrorType() == NumberParseException.ErrorType.INVALID_COUNTRY_CODE) {
   3024         // The second number has no country calling code. EXACT_MATCH is no longer possible.
   3025         // We parse it as if the region was the same as that for the first number, and if
   3026         // EXACT_MATCH is returned, we replace this with NSN_MATCH.
   3027         String firstNumberRegion = getRegionCodeForCountryCode(firstNumber.getCountryCode());
   3028         try {
   3029           if (!firstNumberRegion.equals(UNKNOWN_REGION)) {
   3030             PhoneNumber secondNumberWithFirstNumberRegion = parse(secondNumber, firstNumberRegion);
   3031             MatchType match = isNumberMatch(firstNumber, secondNumberWithFirstNumberRegion);
   3032             if (match == MatchType.EXACT_MATCH) {
   3033               return MatchType.NSN_MATCH;
   3034             }
   3035             return match;
   3036           } else {
   3037             // If the first number didn't have a valid country calling code, then we parse the
   3038             // second number without one as well.
   3039             PhoneNumber secondNumberProto = new PhoneNumber();
   3040             parseHelper(secondNumber, null, false, false, secondNumberProto);
   3041             return isNumberMatch(firstNumber, secondNumberProto);
   3042           }
   3043         } catch (NumberParseException e2) {
   3044           // Fall-through to return NOT_A_NUMBER.
   3045         }
   3046       }
   3047     }
   3048     // One or more of the phone numbers we are trying to match is not a viable phone number.
   3049     return MatchType.NOT_A_NUMBER;
   3050   }
   3051 
   3052   /**
   3053    * Returns true if the number can be dialled from outside the region, or unknown. If the number
   3054    * can only be dialled from within the region, returns false. Does not check the number is a valid
   3055    * number.
   3056    * TODO: Make this method public when we have enough metadata to make it worthwhile.
   3057    *
   3058    * @param number  the phone-number for which we want to know whether it is diallable from
   3059    *     outside the region
   3060    */
   3061   // @VisibleForTesting
   3062   boolean canBeInternationallyDialled(PhoneNumber number) {
   3063     PhoneMetadata metadata = getMetadataForRegion(getRegionCodeForNumber(number));
   3064     if (metadata == null) {
   3065       // Note numbers belonging to non-geographical entities (e.g. +800 numbers) are always
   3066       // internationally diallable, and will be caught here.
   3067       return true;
   3068     }
   3069     String nationalSignificantNumber = getNationalSignificantNumber(number);
   3070     return !isNumberMatchingDesc(nationalSignificantNumber, metadata.getNoInternationalDialling());
   3071   }
   3072 }
   3073