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