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