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