11524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia/*
2ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia * Copyright (C) 2009 The Libphonenumber Authors
31524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia *
41524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia * Licensed under the Apache License, Version 2.0 (the "License");
51524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia * you may not use this file except in compliance with the License.
61524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia * You may obtain a copy of the License at
71524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia *
81524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia * http://www.apache.org/licenses/LICENSE-2.0
91524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia *
101524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia * Unless required by applicable law or agreed to in writing, software
111524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia * distributed under the License is distributed on an "AS IS" BASIS,
121524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
131524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia * See the License for the specific language governing permissions and
141524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia * limitations under the License.
151524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia */
161524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
17a77faddfc3b3e4cca8f585c82d669054aec221f4Narayan Kamathpackage com.google.i18n.phonenumbers;
181524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
1993399cc7a32833de9cb538ef7940eed61a23edcaNeil Fullerimport com.google.i18n.phonenumbers.Phonemetadata.NumberFormat;
2093399cc7a32833de9cb538ef7940eed61a23edcaNeil Fullerimport com.google.i18n.phonenumbers.Phonemetadata.PhoneMetadata;
2193399cc7a32833de9cb538ef7940eed61a23edcaNeil Fullerimport com.google.i18n.phonenumbers.Phonemetadata.PhoneNumberDesc;
22a77faddfc3b3e4cca8f585c82d669054aec221f4Narayan Kamathimport com.google.i18n.phonenumbers.Phonenumber.PhoneNumber;
23a77faddfc3b3e4cca8f585c82d669054aec221f4Narayan Kamathimport com.google.i18n.phonenumbers.Phonenumber.PhoneNumber.CountryCodeSource;
241524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
2552699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jiaimport java.io.InputStream;
264b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jiaimport java.util.ArrayList;
271524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jiaimport java.util.Arrays;
281524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jiaimport java.util.Collections;
291524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jiaimport java.util.HashMap;
301524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jiaimport java.util.HashSet;
3152699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jiaimport java.util.Iterator;
321524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jiaimport java.util.List;
331524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jiaimport java.util.Map;
341524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jiaimport java.util.Set;
351524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jiaimport java.util.logging.Level;
361524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jiaimport java.util.logging.Logger;
371524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jiaimport java.util.regex.Matcher;
381524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jiaimport java.util.regex.Pattern;
391524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
401524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia/**
411524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia * Utility for international phone numbers. Functionality includes formatting, parsing and
421524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia * validation.
431524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia *
44372bff8dd464574d36737d47e495cad14346653cShaopeng Jia * <p>If you use this library, and want to be notified about important changes, please sign up to
45372bff8dd464574d36737d47e495cad14346653cShaopeng Jia * our <a href="http://groups.google.com/group/libphonenumber-discuss/about">mailing list</a>.
46372bff8dd464574d36737d47e495cad14346653cShaopeng Jia *
47d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia * NOTE: A lot of methods in this class require Region Code strings. These must be provided using
48d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia * ISO 3166-1 two-letter country-code format. These should be in upper-case. The list of the codes
49bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia * can be found here:
50bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia * http://www.iso.org/iso/country_codes/iso_3166_code_lists/country_names_and_code_elements.htm
51d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia *
521524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia * @author Shaopeng Jia
531524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia */
541524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jiapublic class PhoneNumberUtil {
559ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia  // @VisibleForTesting
569ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia  static final MetadataLoader DEFAULT_METADATA_LOADER = new MetadataLoader() {
57b0d1cb1662daab3451e5fa59b8f073e9992b628bAndy Staudacher    @Override
589ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia    public InputStream loadMetadata(String metadataFileName) {
599ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia      return PhoneNumberUtil.class.getResourceAsStream(metadataFileName);
609ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia    }
619ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia  };
629ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia
63bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia  private static final Logger logger = Logger.getLogger(PhoneNumberUtil.class.getName());
64bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia
6574aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia  /** Flags to use when compiling regular expressions for phone numbers. */
6674aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia  static final int REGEX_FLAGS = Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE;
677900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia  // The minimum and maximum length of the national significant number.
68bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia  private static final int MIN_LENGTH_FOR_NSN = 2;
69ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia  // The ITU says the maximum length should be 15, but we have found longer numbers in Germany.
70b03a14984ad9b0d8b88337ca714cb831233b99c3Shaopeng Jia  static final int MAX_LENGTH_FOR_NSN = 17;
71372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  // The maximum length of the country calling code.
7274aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia  static final int MAX_LENGTH_COUNTRY_CODE = 3;
73b0e21c22b1ca6b9aeb1426924cdf42a221c3d416Shaopeng Jia  // We don't allow input strings for parsing to be longer than 250 chars. This prevents malicious
74b0e21c22b1ca6b9aeb1426924cdf42a221c3d416Shaopeng Jia  // input from overflowing the regular-expression engine.
75b0e21c22b1ca6b9aeb1426924cdf42a221c3d416Shaopeng Jia  private static final int MAX_INPUT_STRING_LENGTH = 250;
769ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia
7774aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia  // Region-code for the unknown region.
7874aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia  private static final String UNKNOWN_REGION = "ZZ";
79be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia
801524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  private static final int NANPA_COUNTRY_CODE = 1;
811524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
82ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia  // The prefix that needs to be inserted in front of a Colombian landline number when dialed from
83ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia  // a mobile phone in Colombia.
84ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia  private static final String COLOMBIA_MOBILE_TO_FIXED_LINE_PREFIX = "3";
85ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia
86f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia  // Map of country calling codes that use a mobile token before the area code. One example of when
87f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia  // this is relevant is when determining the length of the national destination code, which should
88f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia  // be the length of the area code plus the length of the mobile token.
89f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia  private static final Map<Integer, String> MOBILE_TOKEN_MAPPINGS;
90f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia
911524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  // The PLUS_SIGN signifies the international prefix.
921524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  static final char PLUS_SIGN = '+';
931524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
94cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia  private static final char STAR_SIGN = '*';
95cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia
96372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  private static final String RFC3966_EXTN_PREFIX = ";ext=";
97b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia  private static final String RFC3966_PREFIX = "tel:";
98bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia  private static final String RFC3966_PHONE_CONTEXT = ";phone-context=";
99bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia  private static final String RFC3966_ISDN_SUBADDRESS = ";isub=";
100372bff8dd464574d36737d47e495cad14346653cShaopeng Jia
10196a7214cdabf08f53f5b1a560304601c9f65e0b9Shaopeng Jia  // A map that contains characters that are essential when dialling. That means any of the
102203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia  // characters in this map must not be removed from a number when dialling, otherwise the call
103203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia  // will not reach the intended destination.
10496a7214cdabf08f53f5b1a560304601c9f65e0b9Shaopeng Jia  private static final Map<Character, Character> DIALLABLE_CHAR_MAPPINGS;
10596a7214cdabf08f53f5b1a560304601c9f65e0b9Shaopeng Jia
1061524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  // Only upper-case variants of alpha characters are stored.
107be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia  private static final Map<Character, Character> ALPHA_MAPPINGS;
1081524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
1091524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  // For performance reasons, amalgamate both into one map.
110d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia  private static final Map<Character, Character> ALPHA_PHONE_MAPPINGS;
111be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia
112372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  // Separate map of all symbols that we wish to retain when formatting alpha numbers. This
113372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  // includes digits, ASCII letters and number grouping symbols such as "-" and " ".
114372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  private static final Map<Character, Character> ALL_PLUS_NUMBER_GROUPING_SYMBOLS;
115372bff8dd464574d36737d47e495cad14346653cShaopeng Jia
116be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia  static {
117f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia    HashMap<Integer, String> mobileTokenMap = new HashMap<Integer, String>();
118f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia    mobileTokenMap.put(52, "1");
119f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia    mobileTokenMap.put(54, "9");
120f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia    MOBILE_TOKEN_MAPPINGS = Collections.unmodifiableMap(mobileTokenMap);
121f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia
122d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia    // Simple ASCII digits map used to populate ALPHA_PHONE_MAPPINGS and
123372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    // ALL_PLUS_NUMBER_GROUPING_SYMBOLS.
124372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    HashMap<Character, Character> asciiDigitMappings = new HashMap<Character, Character>();
125372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    asciiDigitMappings.put('0', '0');
126372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    asciiDigitMappings.put('1', '1');
127372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    asciiDigitMappings.put('2', '2');
128372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    asciiDigitMappings.put('3', '3');
129372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    asciiDigitMappings.put('4', '4');
130372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    asciiDigitMappings.put('5', '5');
131372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    asciiDigitMappings.put('6', '6');
132372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    asciiDigitMappings.put('7', '7');
133372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    asciiDigitMappings.put('8', '8');
134372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    asciiDigitMappings.put('9', '9');
135372bff8dd464574d36737d47e495cad14346653cShaopeng Jia
136be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    HashMap<Character, Character> alphaMap = new HashMap<Character, Character>(40);
137be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    alphaMap.put('A', '2');
138be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    alphaMap.put('B', '2');
139be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    alphaMap.put('C', '2');
140be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    alphaMap.put('D', '3');
141be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    alphaMap.put('E', '3');
142be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    alphaMap.put('F', '3');
143be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    alphaMap.put('G', '4');
144be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    alphaMap.put('H', '4');
145be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    alphaMap.put('I', '4');
146be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    alphaMap.put('J', '5');
147be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    alphaMap.put('K', '5');
148be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    alphaMap.put('L', '5');
149be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    alphaMap.put('M', '6');
150be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    alphaMap.put('N', '6');
151be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    alphaMap.put('O', '6');
152be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    alphaMap.put('P', '7');
153be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    alphaMap.put('Q', '7');
154be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    alphaMap.put('R', '7');
155be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    alphaMap.put('S', '7');
156be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    alphaMap.put('T', '8');
157be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    alphaMap.put('U', '8');
158be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    alphaMap.put('V', '8');
159be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    alphaMap.put('W', '9');
160be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    alphaMap.put('X', '9');
161be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    alphaMap.put('Y', '9');
162be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    alphaMap.put('Z', '9');
163be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    ALPHA_MAPPINGS = Collections.unmodifiableMap(alphaMap);
164be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia
165be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    HashMap<Character, Character> combinedMap = new HashMap<Character, Character>(100);
166d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia    combinedMap.putAll(ALPHA_MAPPINGS);
167d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia    combinedMap.putAll(asciiDigitMappings);
168d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia    ALPHA_PHONE_MAPPINGS = Collections.unmodifiableMap(combinedMap);
1691524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
17096a7214cdabf08f53f5b1a560304601c9f65e0b9Shaopeng Jia    HashMap<Character, Character> diallableCharMap = new HashMap<Character, Character>();
17196a7214cdabf08f53f5b1a560304601c9f65e0b9Shaopeng Jia    diallableCharMap.putAll(asciiDigitMappings);
172bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia    diallableCharMap.put(PLUS_SIGN, PLUS_SIGN);
17396a7214cdabf08f53f5b1a560304601c9f65e0b9Shaopeng Jia    diallableCharMap.put('*', '*');
17496a7214cdabf08f53f5b1a560304601c9f65e0b9Shaopeng Jia    DIALLABLE_CHAR_MAPPINGS = Collections.unmodifiableMap(diallableCharMap);
17596a7214cdabf08f53f5b1a560304601c9f65e0b9Shaopeng Jia
176372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    HashMap<Character, Character> allPlusNumberGroupings = new HashMap<Character, Character>();
177372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    // Put (lower letter -> upper letter) and (upper letter -> upper letter) mappings.
178372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    for (char c : ALPHA_MAPPINGS.keySet()) {
179372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      allPlusNumberGroupings.put(Character.toLowerCase(c), c);
180372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      allPlusNumberGroupings.put(c, c);
181372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    }
182372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    allPlusNumberGroupings.putAll(asciiDigitMappings);
183372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    // Put grouping symbols.
184372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    allPlusNumberGroupings.put('-', '-');
185372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    allPlusNumberGroupings.put('\uFF0D', '-');
186372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    allPlusNumberGroupings.put('\u2010', '-');
187372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    allPlusNumberGroupings.put('\u2011', '-');
188372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    allPlusNumberGroupings.put('\u2012', '-');
189372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    allPlusNumberGroupings.put('\u2013', '-');
190372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    allPlusNumberGroupings.put('\u2014', '-');
191372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    allPlusNumberGroupings.put('\u2015', '-');
192372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    allPlusNumberGroupings.put('\u2212', '-');
193372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    allPlusNumberGroupings.put('/', '/');
194372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    allPlusNumberGroupings.put('\uFF0F', '/');
195372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    allPlusNumberGroupings.put(' ', ' ');
196372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    allPlusNumberGroupings.put('\u3000', ' ');
197372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    allPlusNumberGroupings.put('\u2060', ' ');
198372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    allPlusNumberGroupings.put('.', '.');
199372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    allPlusNumberGroupings.put('\uFF0E', '.');
200372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    ALL_PLUS_NUMBER_GROUPING_SYMBOLS = Collections.unmodifiableMap(allPlusNumberGroupings);
201372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  }
202372bff8dd464574d36737d47e495cad14346653cShaopeng Jia
203372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  // Pattern that makes it easy to distinguish whether a region has a unique international dialing
204372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  // prefix or not. If a region has a unique international prefix (e.g. 011 in USA), it will be
2051524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  // represented as a string that contains a sequence of ASCII digits. If there are multiple
206372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  // available international prefixes in a region, they will be represented as a regex string that
2071524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  // always contains character(s) other than ASCII digits.
2081524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  // Note this regex also includes tilde, which signals waiting for the tone.
2091524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  private static final Pattern UNIQUE_INTERNATIONAL_PREFIX =
2107900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia      Pattern.compile("[\\d]+(?:[~\u2053\u223C\uFF5E][\\d]+)?");
2111524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
2121524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  // Regular expression of acceptable punctuation found in phone numbers. This excludes punctuation
2131524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  // found as a leading character only.
2141524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  // This consists of dash characters, white space characters, full stops, slashes,
2151524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  // square brackets, parentheses and tildes. It also includes the letter 'x' as that is found as a
216d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia  // placeholder for carrier information in some phone numbers. Full-width variants are also
217d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia  // present.
21874aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia  static final String VALID_PUNCTUATION = "-x\u2010-\u2015\u2212\u30FC\uFF0D-\uFF0F " +
219bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia      "\u00A0\u00AD\u200B\u2060\u3000()\uFF08\uFF09\uFF3B\uFF3D.\\[\\]/~\u2053\u223C\uFF5E";
2201524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
221d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia  private static final String DIGITS = "\\p{Nd}";
2221524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  // We accept alpha characters in phone numbers, ASCII only, upper and lower case.
2231524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  private static final String VALID_ALPHA =
22474aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia      Arrays.toString(ALPHA_MAPPINGS.keySet().toArray()).replaceAll("[, \\[\\]]", "") +
22574aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia      Arrays.toString(ALPHA_MAPPINGS.keySet().toArray()).toLowerCase().replaceAll("[, \\[\\]]", "");
22674aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia  static final String PLUS_CHARS = "+\uFF0B";
22716b56da4e787a614d16bedcd02b5086d40efbbdbShaopeng Jia  static final Pattern PLUS_CHARS_PATTERN = Pattern.compile("[" + PLUS_CHARS + "]+");
228372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  private static final Pattern SEPARATOR_PATTERN = Pattern.compile("[" + VALID_PUNCTUATION + "]+");
229d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia  private static final Pattern CAPTURING_DIGIT_PATTERN = Pattern.compile("(" + DIGITS + ")");
2301524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
2311524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  // Regular expression of acceptable characters that may start a phone number for the purposes of
2321524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  // parsing. This allows us to strip away meaningless prefixes to phone numbers that may be
2331524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  // mistakenly given to us. This consists of digits, the plus symbol and arabic-indic digits. This
2341524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  // does not contain alpha characters, although they may be used later in the number. It also does
2351524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  // not include other punctuation, as this will be stripped later during parsing and is of no
2361524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  // information value when parsing a number.
237d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia  private static final String VALID_START_CHAR = "[" + PLUS_CHARS + DIGITS + "]";
23816b56da4e787a614d16bedcd02b5086d40efbbdbShaopeng Jia  private static final Pattern VALID_START_CHAR_PATTERN = Pattern.compile(VALID_START_CHAR);
2391524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
2401524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  // Regular expression of characters typically used to start a second phone number for the purposes
2411524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  // of parsing. This allows us to strip off parts of the number that are actually the start of
2421524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  // another number, such as for: (530) 583-6985 x302/x2303 -> the second extension here makes this
2431524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  // actually two phone numbers, (530) 583-6985 x302 and (530) 583-6985 x2303. We remove the second
2441524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  // extension so that the first number is parsed correctly.
2451524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  private static final String SECOND_NUMBER_START = "[\\\\/] *x";
24674aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia  static final Pattern SECOND_NUMBER_START_PATTERN = Pattern.compile(SECOND_NUMBER_START);
2471524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
2487900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia  // Regular expression of trailing characters that we want to remove. We remove all characters that
2497900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia  // are not alpha or numerical characters. The hash character is retained here, as it may signify
2507900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia  // the previous block was an extension.
2517900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia  private static final String UNWANTED_END_CHARS = "[[\\P{N}&&\\P{L}]&&[^#]]+$";
252372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  static final Pattern UNWANTED_END_CHAR_PATTERN = Pattern.compile(UNWANTED_END_CHARS);
2537900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia
2547900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia  // We use this pattern to check if the phone number has at least three letters in it - if so, then
2557900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia  // we treat it as a number where some phone-number digits are represented by letters.
2567900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia  private static final Pattern VALID_ALPHA_PHONE_PATTERN = Pattern.compile("(?:.*?[A-Za-z]){3}.*");
2577900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia
2581524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  // Regular expression of viable phone numbers. This is location independent. Checks we have at
2591524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  // least three leading digits, and only valid punctuation, alpha characters and
2607900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia  // digits in the phone number. Does not include extension data.
2611524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  // The symbol 'x' is allowed here as valid punctuation since it is often used as a placeholder for
262256a5f71a05ffd182a0fda2cfed6f93345cc889fLara Rennie  // carrier codes, for example in Brazilian phone numbers. We also allow multiple "+" characters at
263256a5f71a05ffd182a0fda2cfed6f93345cc889fLara Rennie  // the start.
2641524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  // Corresponds to the following:
2654b867acb917b73e699a596df94445c634c916519Shaopeng Jia  // [digits]{minLengthNsn}|
266cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia  // plus_sign*(([punctuation]|[star])*[digits]){3,}([punctuation]|[star]|[digits]|[alpha])*
2674b867acb917b73e699a596df94445c634c916519Shaopeng Jia  //
2684b867acb917b73e699a596df94445c634c916519Shaopeng Jia  // The first reg-ex is to allow short numbers (two digits long) to be parsed if they are entered
2694b867acb917b73e699a596df94445c634c916519Shaopeng Jia  // as "15" etc, but only if there is no punctuation in them. The second expression restricts the
2704b867acb917b73e699a596df94445c634c916519Shaopeng Jia  // number of digits to three or more, but then allows them to be in international form, and to
2714b867acb917b73e699a596df94445c634c916519Shaopeng Jia  // have alpha-characters and punctuation.
2724b867acb917b73e699a596df94445c634c916519Shaopeng Jia  //
27374aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia  // Note VALID_PUNCTUATION starts with a -, so must be the first in the range.
2741524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  private static final String VALID_PHONE_NUMBER =
2754b867acb917b73e699a596df94445c634c916519Shaopeng Jia      DIGITS + "{" + MIN_LENGTH_FOR_NSN + "}" + "|" +
276b0e21c22b1ca6b9aeb1426924cdf42a221c3d416Shaopeng Jia      "[" + PLUS_CHARS + "]*+(?:[" + VALID_PUNCTUATION + STAR_SIGN + "]*" + DIGITS + "){3,}[" +
277cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia      VALID_PUNCTUATION + STAR_SIGN + VALID_ALPHA + DIGITS + "]*";
2781524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
2791524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  // Default extension prefix to use when formatting. This will be put in front of any extension
2801524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  // component of the number, after the main national number is formatted. For example, if you wish
2811524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  // the default extension formatting to be " extn: 3456", then you should specify " extn: " here
282372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  // as the default extension prefix. This can be overridden by region-specific preferences.
2831524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  private static final String DEFAULT_EXTN_PREFIX = " ext. ";
2841524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
285f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia  // Pattern to capture digits used in an extension. Places a maximum length of "7" for an
286f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia  // extension.
287f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia  private static final String CAPTURING_EXTN_DIGITS = "(" + DIGITS + "{1,7})";
2881524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  // Regexp of all possible ways to write extensions, for use when parsing. This will be run as a
289372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  // case-insensitive regexp match. Wide character versions are also provided after each ASCII
290f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia  // version.
291f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia  private static final String EXTN_PATTERNS_FOR_PARSING;
292f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia  static final String EXTN_PATTERNS_FOR_MATCHING;
293f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia  static {
294f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia    // One-character symbols that can be used to indicate an extension.
295f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia    String singleExtnSymbolsForMatching = "x\uFF58#\uFF03~\uFF5E";
296f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia    // For parsing, we are slightly more lenient in our interpretation than for matching. Here we
297f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia    // allow a "comma" as a possible extension indicator. When matching, this is hardly ever used to
298f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia    // indicate this.
299f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia    String singleExtnSymbolsForParsing = "," + singleExtnSymbolsForMatching;
300f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia
301f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia    EXTN_PATTERNS_FOR_PARSING = createExtnPattern(singleExtnSymbolsForParsing);
302f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia    EXTN_PATTERNS_FOR_MATCHING = createExtnPattern(singleExtnSymbolsForMatching);
303f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia  }
304f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia
305f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia  /**
306f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia   * Helper initialiser method to create the regular-expression pattern to match extensions,
307f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia   * allowing the one-char extension symbols provided by {@code singleExtnSymbols}.
308f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia   */
309f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia  private static String createExtnPattern(String singleExtnSymbols) {
310f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia    // There are three regular expressions here. The first covers RFC 3966 format, where the
311f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia    // extension is added using ";ext=". The second more generic one starts with optional white
312f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia    // space and ends with an optional full stop (.), followed by zero or more spaces/tabs and then
313f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia    // the numbers themselves. The other one covers the special case of American numbers where the
314f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia    // extension is written with a hash at the end, such as "- 503#".
315f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia    // Note that the only capturing groups should be around the digits that you want to capture as
316f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia    // part of the extension, or else parsing will fail!
317f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia    // Canonical-equivalence doesn't seem to be an option with Android java, so we allow two options
318f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia    // for representing the accented o - the character itself, and one in the unicode decomposed
319f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia    // form with the combining acute accent.
320f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia    return (RFC3966_EXTN_PREFIX + CAPTURING_EXTN_DIGITS + "|" + "[ \u00A0\\t,]*" +
321528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia            "(?:e?xt(?:ensi(?:o\u0301?|\u00F3))?n?|\uFF45?\uFF58\uFF54\uFF4E?|" +
322f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia            "[" + singleExtnSymbols + "]|int|anexo|\uFF49\uFF4E\uFF54)" +
323f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia            "[:\\.\uFF0E]?[ \u00A0\\t,-]*" + CAPTURING_EXTN_DIGITS + "#?|" +
324f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia            "[- ]+(" + DIGITS + "{1,5})#");
325f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia  }
3261524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
327372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  // Regexp of all known extension prefixes used by different regions followed by 1 or more valid
3281524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  // digits, for use when parsing.
3291524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  private static final Pattern EXTN_PATTERN =
330f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia      Pattern.compile("(?:" + EXTN_PATTERNS_FOR_PARSING + ")$", REGEX_FLAGS);
3311524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
3321524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  // We append optionally the extension pattern to the end here, as a valid phone number may
3331524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  // have an extension prefix appended, followed by 1 or more digits.
3341524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  private static final Pattern VALID_PHONE_NUMBER_PATTERN =
335f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia      Pattern.compile(VALID_PHONE_NUMBER + "(?:" + EXTN_PATTERNS_FOR_PARSING + ")?", REGEX_FLAGS);
3361524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
337b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia  static final Pattern NON_DIGITS_PATTERN = Pattern.compile("(\\D+)");
338372bff8dd464574d36737d47e495cad14346653cShaopeng Jia
339372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  // The FIRST_GROUP_PATTERN was originally set to $1 but there are some countries for which the
340372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  // first group is not used in the national pattern (e.g. Argentina) so the $1 group does not match
341372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  // correctly.  Therefore, we use \d, so that the first group actually used in the pattern will be
342372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  // matched.
343372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  private static final Pattern FIRST_GROUP_PATTERN = Pattern.compile("(\\$\\d)");
344be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia  private static final Pattern NP_PATTERN = Pattern.compile("\\$NP");
345be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia  private static final Pattern FG_PATTERN = Pattern.compile("\\$FG");
3464b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia  private static final Pattern CC_PATTERN = Pattern.compile("\\$CC");
347be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia
348203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia  // A pattern that is used to determine if the national prefix formatting rule has the first group
349203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia  // only, i.e., does not start with the national prefix. Note that the pattern explicitly allows
350203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia  // for unbalanced parentheses.
351203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia  private static final Pattern FIRST_GROUP_ONLY_PREFIX_PATTERN = Pattern.compile("\\(?\\$1\\)?");
352203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia
3531524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  private static PhoneNumberUtil instance = null;
3541524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
355528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia  public static final String REGION_CODE_FOR_NON_GEO_ENTITY = "001";
356528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia
3571524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
3581524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * INTERNATIONAL and NATIONAL formats are consistent with the definition in ITU-T Recommendation
359d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   * E123. For example, the number of the Google Switzerland office will be written as
3601524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * "+41 44 668 1800" in INTERNATIONAL format, and as "044 668 1800" in NATIONAL format.
361b0e21c22b1ca6b9aeb1426924cdf42a221c3d416Shaopeng Jia   * E164 format is as per INTERNATIONAL format but with no formatting applied, e.g.
362b0e21c22b1ca6b9aeb1426924cdf42a221c3d416Shaopeng Jia   * "+41446681800". RFC3966 is as per INTERNATIONAL format, but with all spaces and other
363b0e21c22b1ca6b9aeb1426924cdf42a221c3d416Shaopeng Jia   * separating symbols replaced with a hyphen, and with any phone number extension appended with
364b0e21c22b1ca6b9aeb1426924cdf42a221c3d416Shaopeng Jia   * ";ext=". It also will have a prefix of "tel:" added, e.g. "tel:+41-44-668-1800".
3651524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *
3661524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * Note: If you are considering storing the number in a neutral format, you are highly advised to
367372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * use the PhoneNumber class.
3681524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
3691524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  public enum PhoneNumberFormat {
3701524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    E164,
3711524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    INTERNATIONAL,
372372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    NATIONAL,
373372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    RFC3966
3741524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
3751524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
3761524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
3771524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * Type of phone numbers.
3781524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
3791524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  public enum PhoneNumberType {
3801524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    FIXED_LINE,
3811524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    MOBILE,
382372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    // In some regions (e.g. the USA), it is impossible to distinguish between fixed-line and
3831524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    // mobile numbers by looking at the phone number itself.
3841524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    FIXED_LINE_OR_MOBILE,
3851524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    // Freephone lines
3861524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    TOLL_FREE,
3871524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    PREMIUM_RATE,
3881524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    // The cost of this call is shared between the caller and the recipient, and is hence typically
3891524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    // less than PREMIUM_RATE calls. See // http://en.wikipedia.org/wiki/Shared_Cost_Service for
3901524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    // more information.
3911524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    SHARED_COST,
3921524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    // Voice over IP numbers. This includes TSoIP (Telephony Service over IP).
3931524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    VOIP,
3941524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    // A personal number is associated with a particular person, and may be routed to either a
3951524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    // MOBILE or FIXED_LINE number. Some more information can be found here:
3961524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    // http://en.wikipedia.org/wiki/Personal_Numbers
3971524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    PERSONAL_NUMBER,
398b2697412130f6d087dde01fb1a978f7e5840a5faShaopeng Jia    PAGER,
39974aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia    // Used for "Universal Access Numbers" or "Company Numbers". They may be further routed to
40074aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia    // specific offices, but allow one number to be used for a company.
40174aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia    UAN,
402528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    // Used for "Voice Mail Access Numbers".
403528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    VOICEMAIL,
4041524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    // A phone number is of type UNKNOWN when it does not fit any of the known patterns for a
405372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    // specific region.
4061524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    UNKNOWN
4071524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
4081524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
4091524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
4101524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * Types of phone number matches. See detailed description beside the isNumberMatch() method.
4111524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
4121524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  public enum MatchType {
41374aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia    NOT_A_NUMBER,
4141524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    NO_MATCH,
4151524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    SHORT_NSN_MATCH,
4161524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    NSN_MATCH,
4171524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    EXACT_MATCH,
4181524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
4191524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
4201524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
4211524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * Possible outcomes when testing if a PhoneNumber is possible.
4221524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
4231524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  public enum ValidationResult {
4241524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    IS_POSSIBLE,
4251524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    INVALID_COUNTRY_CODE,
4261524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    TOO_SHORT,
4271524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    TOO_LONG,
4281524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
4291524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
4301524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
43152699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia   * Leniency when {@linkplain PhoneNumberUtil#findNumbers finding} potential phone numbers in text
432f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia   * segments. The levels here are ordered in increasing strictness.
43352699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia   */
43452699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia  public enum Leniency {
43552699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia    /**
43696a7214cdabf08f53f5b1a560304601c9f65e0b9Shaopeng Jia     * Phone numbers accepted are {@linkplain PhoneNumberUtil#isPossibleNumber(PhoneNumber)
43796a7214cdabf08f53f5b1a560304601c9f65e0b9Shaopeng Jia     * possible}, but not necessarily {@linkplain PhoneNumberUtil#isValidNumber(PhoneNumber) valid}.
43852699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia     */
43952699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia    POSSIBLE {
44052699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia      @Override
441f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia      boolean verify(PhoneNumber number, String candidate, PhoneNumberUtil util) {
44252699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia        return util.isPossibleNumber(number);
44352699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia      }
44452699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia    },
44552699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia    /**
44696a7214cdabf08f53f5b1a560304601c9f65e0b9Shaopeng Jia     * Phone numbers accepted are {@linkplain PhoneNumberUtil#isPossibleNumber(PhoneNumber)
44796a7214cdabf08f53f5b1a560304601c9f65e0b9Shaopeng Jia     * possible} and {@linkplain PhoneNumberUtil#isValidNumber(PhoneNumber) valid}. Numbers written
448a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia     * in national format must have their national-prefix present if it is usually written for a
449a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia     * number of this type.
45052699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia     */
45152699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia    VALID {
45252699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia      @Override
453f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia      boolean verify(PhoneNumber number, String candidate, PhoneNumberUtil util) {
454a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia        if (!util.isValidNumber(number) ||
455b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia            !PhoneNumberMatcher.containsOnlyValidXChars(number, candidate, util)) {
456f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia          return false;
457f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia        }
458b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia        return PhoneNumberMatcher.isNationalPrefixPresentIfRequired(number, util);
459f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia      }
460f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia    },
461f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia    /**
462f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia     * Phone numbers accepted are {@linkplain PhoneNumberUtil#isValidNumber(PhoneNumber) valid} and
463f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia     * are grouped in a possible way for this locale. For example, a US number written as
464f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia     * "65 02 53 00 00" and "650253 0000" are not accepted at this leniency level, whereas
465f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia     * "650 253 0000", "650 2530000" or "6502530000" are.
466bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia     * Numbers with more than one '/' symbol in the national significant number are also dropped at
467bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia     * this level.
468f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia     * <p>
469f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia     * Warning: This level might result in lower coverage especially for regions outside of country
470f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia     * code "+1". If you are not sure about which level to use, email the discussion group
471f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia     * libphonenumber-discuss@googlegroups.com.
472f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia     */
473f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia    STRICT_GROUPING {
474f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia      @Override
475f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia      boolean verify(PhoneNumber number, String candidate, PhoneNumberUtil util) {
476f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia        if (!util.isValidNumber(number) ||
477b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia            !PhoneNumberMatcher.containsOnlyValidXChars(number, candidate, util) ||
478bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia            PhoneNumberMatcher.containsMoreThanOneSlashInNationalNumber(number, candidate) ||
479b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia            !PhoneNumberMatcher.isNationalPrefixPresentIfRequired(number, util)) {
480f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia          return false;
481f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia        }
482b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia        return PhoneNumberMatcher.checkNumberGroupingIsValid(
483b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia            number, candidate, util, new PhoneNumberMatcher.NumberGroupingChecker() {
484b0d1cb1662daab3451e5fa59b8f073e9992b628bAndy Staudacher              @Override
485b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia              public boolean checkGroups(PhoneNumberUtil util, PhoneNumber number,
486b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia                                         StringBuilder normalizedCandidate,
487b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia                                         String[] expectedNumberGroups) {
488b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia                return PhoneNumberMatcher.allNumberGroupsRemainGrouped(
489b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia                    util, number, normalizedCandidate, expectedNumberGroups);
490b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia              }
491b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia            });
492f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia      }
493f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia    },
494f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia    /**
495f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia     * Phone numbers accepted are {@linkplain PhoneNumberUtil#isValidNumber(PhoneNumber) valid} and
496f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia     * are grouped in the same way that we would have formatted it, or as a single block. For
497f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia     * example, a US number written as "650 2530000" is not accepted at this leniency level, whereas
498f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia     * "650 253 0000" or "6502530000" are.
499f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia     * Numbers with more than one '/' symbol are also dropped at this level.
500f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia     * <p>
501f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia     * Warning: This level might result in lower coverage especially for regions outside of country
502f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia     * code "+1". If you are not sure about which level to use, email the discussion group
503f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia     * libphonenumber-discuss@googlegroups.com.
504f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia     */
505f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia    EXACT_GROUPING {
506f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia      @Override
507f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia      boolean verify(PhoneNumber number, String candidate, PhoneNumberUtil util) {
508f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia        if (!util.isValidNumber(number) ||
509b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia            !PhoneNumberMatcher.containsOnlyValidXChars(number, candidate, util) ||
510bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia            PhoneNumberMatcher.containsMoreThanOneSlashInNationalNumber(number, candidate) ||
511b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia            !PhoneNumberMatcher.isNationalPrefixPresentIfRequired(number, util)) {
512f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia          return false;
513f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia        }
514b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia        return PhoneNumberMatcher.checkNumberGroupingIsValid(
515b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia            number, candidate, util, new PhoneNumberMatcher.NumberGroupingChecker() {
516b0d1cb1662daab3451e5fa59b8f073e9992b628bAndy Staudacher              @Override
517b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia              public boolean checkGroups(PhoneNumberUtil util, PhoneNumber number,
518b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia                                         StringBuilder normalizedCandidate,
519b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia                                         String[] expectedNumberGroups) {
520b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia                return PhoneNumberMatcher.allNumberGroupsAreExactlyPresent(
521b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia                    util, number, normalizedCandidate, expectedNumberGroups);
522b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia              }
523b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia            });
52452699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia      }
52552699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia    };
52652699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia
52752699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia    /** Returns true if {@code number} is a verified number according to this leniency. */
528f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia    abstract boolean verify(PhoneNumber number, String candidate, PhoneNumberUtil util);
52952699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia  }
53052699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia
531279df210d5a4215ee2273bd23d29de5dc29e8370Neil Fuller  // A source of metadata for different regions.
532279df210d5a4215ee2273bd23d29de5dc29e8370Neil Fuller  private final MetadataSource metadataSource;
533279df210d5a4215ee2273bd23d29de5dc29e8370Neil Fuller
5343396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia  // A mapping from a country calling code to the region codes which denote the region represented
5353396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia  // by that country calling code. In the case of multiple regions sharing a calling code, such as
5363396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia  // the NANPA regions, the one indicated with "isMainCountryForCode" in the metadata should be
5373396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia  // first.
5383396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia  private final Map<Integer, List<String>> countryCallingCodeToRegionCodeMap;
5393396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia
5403396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia  // The set of regions that share country calling code 1.
5417a81979b0076f18b31b47b7df2beac29735f3a37Cecilia Roes  // There are roughly 26 regions.
5427a81979b0076f18b31b47b7df2beac29735f3a37Cecilia Roes  // We set the initial capacity of the HashSet to 35 to offer a load factor of roughly 0.75.
5433396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia  private final Set<String> nanpaRegions = new HashSet<String>(35);
5443396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia
5453396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia  // A cache for frequently used region-specific regular expressions.
5463396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia  // The initial capacity is set to 100 as this seems to be an optimal value for Android, based on
5473396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia  // performance measurements.
5483396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia  private final RegexCache regexCache = new RegexCache(100);
5493396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia
5503396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia  // The set of regions the library supports.
5513396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia  // There are roughly 240 of them and we set the initial capacity of the HashSet to 320 to offer a
5523396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia  // load factor of roughly 0.75.
5533396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia  private final Set<String> supportedRegions = new HashSet<String>(320);
5543396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia
5553396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia  // The set of county calling codes that map to the non-geo entity region ("001"). This set
5563396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia  // currently contains < 12 elements so the default capacity of 16 (load factor=0.75) is fine.
5573396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia  private final Set<Integer> countryCodesForNonGeographicalRegion = new HashSet<Integer>();
5583396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia
55952699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia  /**
5607a81979b0076f18b31b47b7df2beac29735f3a37Cecilia Roes   * This class implements a singleton, the constructor is only visible to facilitate testing.
5611524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
5629ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia  // @VisibleForTesting
563279df210d5a4215ee2273bd23d29de5dc29e8370Neil Fuller  PhoneNumberUtil(MetadataSource metadataSource,
5643396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia      Map<Integer, List<String>> countryCallingCodeToRegionCodeMap) {
565279df210d5a4215ee2273bd23d29de5dc29e8370Neil Fuller    this.metadataSource = metadataSource;
5663396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia    this.countryCallingCodeToRegionCodeMap = countryCallingCodeToRegionCodeMap;
567203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    for (Map.Entry<Integer, List<String>> entry : countryCallingCodeToRegionCodeMap.entrySet()) {
568203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia      List<String> regionCodes = entry.getValue();
569203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia      // We can assume that if the county calling code maps to the non-geo entity region code then
570203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia      // that's the only region code it maps to.
571203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia      if (regionCodes.size() == 1 && REGION_CODE_FOR_NON_GEO_ENTITY.equals(regionCodes.get(0))) {
572203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia        // This is the subset of all country codes that map to the non-geo entity region code.
573203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia        countryCodesForNonGeographicalRegion.add(entry.getKey());
574203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia      } else {
575203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia        // The supported regions set does not include the "001" non-geo entity region code.
576203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia        supportedRegions.addAll(regionCodes);
577203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia      }
578203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    }
579203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    // If the non-geo entity still got added to the set of supported regions it must be because
580203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    // there are entries that list the non-geo entity alongside normal regions (which is wrong).
581203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    // If we discover this, remove the non-geo entity from the set of supported regions and log.
582203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    if (supportedRegions.remove(REGION_CODE_FOR_NON_GEO_ENTITY)) {
583bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia      logger.log(Level.WARNING, "invalid metadata " +
584203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia          "(country calling code was mapped to the non-geo entity as well as specific region(s))");
585fa42140081949568565af7dc8c22f0600ad90a8aShaopeng Jia    }
586372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    nanpaRegions.addAll(countryCallingCodeToRegionCodeMap.get(NANPA_COUNTRY_CODE));
587fa42140081949568565af7dc8c22f0600ad90a8aShaopeng Jia  }
588fa42140081949568565af7dc8c22f0600ad90a8aShaopeng Jia
5891524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
5901524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * Attempts to extract a possible number from the string passed in. This currently strips all
591372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * leading characters that cannot be used to start a phone number. Characters that can be used to
592372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * start a phone number are defined in the VALID_START_CHAR_PATTERN. If none of these characters
593372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * are found in the number passed in, an empty string is returned. This function also attempts to
594372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * strip off any alternative extensions or endings if two or more are present, such as in the case
595372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * of: (530) 583-6985 x302/x2303. The second extension here makes this actually two phone numbers,
596372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * (530) 583-6985 x302 and (530) 583-6985 x2303. We remove the second extension so that the first
597372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * number is parsed correctly.
5981524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *
5991524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @param number  the string that might contain a phone number
6001524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @return        the number, stripped of any non-phone-number prefix (such as "Tel:") or an empty
6011524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *                string if no character used to start phone numbers (such as + or any digit) is
6021524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *                found in the number
6031524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
6041524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  static String extractPossibleNumber(String number) {
6051524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    Matcher m = VALID_START_CHAR_PATTERN.matcher(number);
6061524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    if (m.find()) {
6071524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      number = number.substring(m.start());
6084b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia      // Remove trailing non-alpha non-numerical characters.
6094b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia      Matcher trailingCharsMatcher = UNWANTED_END_CHAR_PATTERN.matcher(number);
6104b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia      if (trailingCharsMatcher.find()) {
6114b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia        number = number.substring(0, trailingCharsMatcher.start());
612bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia        logger.log(Level.FINER, "Stripped trailing characters: " + number);
6134b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia      }
6141524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      // Check for extra numbers at the end.
6151524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      Matcher secondNumber = SECOND_NUMBER_START_PATTERN.matcher(number);
6161524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      if (secondNumber.find()) {
6171524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia        number = number.substring(0, secondNumber.start());
6181524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      }
6191524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      return number;
6201524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    } else {
6211524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      return "";
6221524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
6231524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
6241524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
6251524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
6261524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * Checks to see if the string of characters could possibly be a phone number at all. At the
627bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia   * moment, checks to see that the string begins with at least 2 digits, ignoring any punctuation
6281524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * commonly found in phone numbers.
6291524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * This method does not require the number to be normalized in advance - but does assume that
6301524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * leading non-number symbols have been removed, such as by the method extractPossibleNumber.
6311524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *
6321524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @param number  string to be checked for viability as a phone number
6331524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @return        true if the number could be a phone number of some sort, otherwise false
6341524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
635ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia  // @VisibleForTesting
6361524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  static boolean isViablePhoneNumber(String number) {
6371524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    if (number.length() < MIN_LENGTH_FOR_NSN) {
6381524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      return false;
6391524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
6401524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    Matcher m = VALID_PHONE_NUMBER_PATTERN.matcher(number);
6411524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    return m.matches();
6421524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
6431524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
6441524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
6451524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * Normalizes a string of characters representing a phone number. This performs the following
6461524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * conversions:
647d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   *   Punctuation is stripped.
648d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   *   For ALPHA/VANITY numbers:
6491524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *   Letters are converted to their numeric representation on a telephone keypad. The keypad
6501524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *       used here is the one defined in ITU Recommendation E.161. This is only done if there are
651d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   *       3 or more letters in the number, to lessen the risk that such letters are typos.
652d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   *   For other numbers:
653d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   *   Wide-ascii digits are converted to normal ASCII (European) digits.
6541524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *   Arabic-Indic numerals are converted to European numerals.
655d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   *   Spurious alpha characters are stripped.
6561524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *
6571524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @param number  a string of characters representing a phone number
6581524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @return        the normalized string version of the phone number
6591524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
6601524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  static String normalize(String number) {
6617900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia    Matcher m = VALID_ALPHA_PHONE_PATTERN.matcher(number);
6627900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia    if (m.matches()) {
663d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia      return normalizeHelper(number, ALPHA_PHONE_MAPPINGS, true);
6641524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    } else {
665d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia      return normalizeDigitsOnly(number);
6661524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
6671524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
6681524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
6691524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
6701524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * Normalizes a string of characters representing a phone number. This is a wrapper for
671372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * normalize(String number) but does in-place normalization of the StringBuilder provided.
6721524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *
673372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * @param number  a StringBuilder of characters representing a phone number that will be
674372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *     normalized in place
6751524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
676372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  static void normalize(StringBuilder number) {
6771524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    String normalizedNumber = normalize(number.toString());
6781524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    number.replace(0, number.length(), normalizedNumber);
6791524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
6801524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
6811524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
6821524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * Normalizes a string of characters representing a phone number. This converts wide-ascii and
6837900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia   * arabic-indic numerals to European numerals, and strips punctuation and alpha characters.
6841524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *
6851524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @param number  a string of characters representing a phone number
6861524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @return        the normalized string version of the phone number
6871524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
6881524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  public static String normalizeDigitsOnly(String number) {
689f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia    return normalizeDigits(number, false /* strip non-digits */).toString();
690f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia  }
691f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia
692b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia  static StringBuilder normalizeDigits(String number, boolean keepNonDigits) {
693f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia    StringBuilder normalizedDigits = new StringBuilder(number.length());
694f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia    for (char c : number.toCharArray()) {
695f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia      int digit = Character.digit(c, 10);
696f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia      if (digit != -1) {
697f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia        normalizedDigits.append(digit);
698f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia      } else if (keepNonDigits) {
699f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia        normalizedDigits.append(c);
700d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia      }
701d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia    }
702f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia    return normalizedDigits;
7031524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
7041524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
7051524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
706bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia   * Normalizes a string of characters representing a phone number. This strips all characters which
707bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia   * are not diallable on a mobile phone keypad (including all non-ASCII digits).
708bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia   *
709bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia   * @param number  a string of characters representing a phone number
710bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia   * @return        the normalized string version of the phone number
711bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia   */
712bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia  static String normalizeDiallableCharsOnly(String number) {
713bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia    return normalizeHelper(number, DIALLABLE_CHAR_MAPPINGS, true /* remove non matches */);
714bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia  }
715bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia
716bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia  /**
7171524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * Converts all alpha characters in a number to their respective digits on a keypad, but retains
718d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   * existing formatting.
7191524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
7201524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  public static String convertAlphaCharactersInNumber(String number) {
721d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia    return normalizeHelper(number, ALPHA_PHONE_MAPPINGS, false);
7221524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
7231524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
7241524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
7257a81979b0076f18b31b47b7df2beac29735f3a37Cecilia Roes   * Gets the length of the geographical area code from the
7267a81979b0076f18b31b47b7df2beac29735f3a37Cecilia Roes   * PhoneNumber object passed in, so that clients could use it
7277a81979b0076f18b31b47b7df2beac29735f3a37Cecilia Roes   * to split a national significant number into geographical area code and subscriber number. It
7287a81979b0076f18b31b47b7df2beac29735f3a37Cecilia Roes   * works in such a way that the resultant subscriber number should be diallable, at least on some
7297a81979b0076f18b31b47b7df2beac29735f3a37Cecilia Roes   * devices. An example of how this could be used:
7305c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia   *
731279df210d5a4215ee2273bd23d29de5dc29e8370Neil Fuller   * <pre>{@code
732df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia   * PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
733b2697412130f6d087dde01fb1a978f7e5840a5faShaopeng Jia   * PhoneNumber number = phoneUtil.parse("16502530000", "US");
734372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * String nationalSignificantNumber = phoneUtil.getNationalSignificantNumber(number);
7355c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia   * String areaCode;
7365c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia   * String subscriberNumber;
7375c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia   *
7385c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia   * int areaCodeLength = phoneUtil.getLengthOfGeographicalAreaCode(number);
7395c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia   * if (areaCodeLength > 0) {
7405c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia   *   areaCode = nationalSignificantNumber.substring(0, areaCodeLength);
7415c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia   *   subscriberNumber = nationalSignificantNumber.substring(areaCodeLength);
7425c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia   * } else {
7435c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia   *   areaCode = "";
7445c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia   *   subscriberNumber = nationalSignificantNumber;
7455c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia   * }
746279df210d5a4215ee2273bd23d29de5dc29e8370Neil Fuller   * }</pre>
7475c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia   *
7485c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia   * N.B.: area code is a very ambiguous concept, so the I18N team generally recommends against
749d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   * using it for most purposes, but recommends using the more general {@code national_number}
750d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   * instead. Read the following carefully before deciding to use this method:
751d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   * <ul>
752d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   *  <li> geographical area codes change over time, and this method honors those changes;
753d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   *    therefore, it doesn't guarantee the stability of the result it produces.
754d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   *  <li> subscriber numbers may not be diallable from all devices (notably mobile devices, which
755d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   *    typically requires the full national_number to be dialled in most regions).
756528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia   *  <li> most non-geographical numbers have no area codes, including numbers from non-geographical
757528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia   *    entities
758d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   *  <li> some geographical numbers have no area codes.
759d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   * </ul>
7607a81979b0076f18b31b47b7df2beac29735f3a37Cecilia Roes   * @param number  the PhoneNumber object for which clients
7617a81979b0076f18b31b47b7df2beac29735f3a37Cecilia Roes   *     want to know the length of the area code.
7627a81979b0076f18b31b47b7df2beac29735f3a37Cecilia Roes   * @return  the length of area code of the PhoneNumber object
7637a81979b0076f18b31b47b7df2beac29735f3a37Cecilia Roes   *     passed in.
7645c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia   */
7655c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia  public int getLengthOfGeographicalAreaCode(PhoneNumber number) {
766203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    PhoneMetadata metadata = getMetadataForRegion(getRegionCodeForNumber(number));
767203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    if (metadata == null) {
7685c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia      return 0;
7695c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia    }
770b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia    // If a country doesn't use a national prefix, and this number doesn't have an Italian leading
771b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia    // zero, we assume it is a closed dialling plan with no area codes.
77293399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller    if (!metadata.hasNationalPrefix() && !number.isItalianLeadingZero()) {
7735c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia      return 0;
7745c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia    }
7755c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia
776203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    if (!isNumberGeographical(number)) {
7775c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia      return 0;
7785c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia    }
7795c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia
78074aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia    return getLengthOfNationalDestinationCode(number);
78174aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia  }
78274aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia
78374aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia  /**
7847a81979b0076f18b31b47b7df2beac29735f3a37Cecilia Roes   * Gets the length of the national destination code (NDC) from the
7857a81979b0076f18b31b47b7df2beac29735f3a37Cecilia Roes   * PhoneNumber object passed in, so that clients could use it
7867a81979b0076f18b31b47b7df2beac29735f3a37Cecilia Roes   * to split a national significant number into NDC and subscriber number. The NDC of a phone
7877a81979b0076f18b31b47b7df2beac29735f3a37Cecilia Roes   * number is normally the first group of digit(s) right after the country calling code when the
7887a81979b0076f18b31b47b7df2beac29735f3a37Cecilia Roes   * number is formatted in the international format, if there is a subscriber number part that
7897a81979b0076f18b31b47b7df2beac29735f3a37Cecilia Roes   * follows. An example of how this could be used:
79074aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia   *
791279df210d5a4215ee2273bd23d29de5dc29e8370Neil Fuller   * <pre>{@code
79274aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia   * PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
79374aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia   * PhoneNumber number = phoneUtil.parse("18002530000", "US");
794372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * String nationalSignificantNumber = phoneUtil.getNationalSignificantNumber(number);
79574aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia   * String nationalDestinationCode;
79674aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia   * String subscriberNumber;
79774aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia   *
79874aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia   * int nationalDestinationCodeLength = phoneUtil.getLengthOfNationalDestinationCode(number);
79974aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia   * if (nationalDestinationCodeLength > 0) {
80074aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia   *   nationalDestinationCode = nationalSignificantNumber.substring(0,
80174aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia   *       nationalDestinationCodeLength);
80274aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia   *   subscriberNumber = nationalSignificantNumber.substring(nationalDestinationCodeLength);
80374aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia   * } else {
80474aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia   *   nationalDestinationCode = "";
80574aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia   *   subscriberNumber = nationalSignificantNumber;
80674aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia   * }
807279df210d5a4215ee2273bd23d29de5dc29e8370Neil Fuller   * }</pre>
80874aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia   *
80974aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia   * Refer to the unittests to see the difference between this function and
810d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   * {@link #getLengthOfGeographicalAreaCode}.
81174aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia   *
8127a81979b0076f18b31b47b7df2beac29735f3a37Cecilia Roes   * @param number  the PhoneNumber object for which clients
8137a81979b0076f18b31b47b7df2beac29735f3a37Cecilia Roes   *     want to know the length of the NDC.
8147a81979b0076f18b31b47b7df2beac29735f3a37Cecilia Roes   * @return  the length of NDC of the PhoneNumber object
8157a81979b0076f18b31b47b7df2beac29735f3a37Cecilia Roes   *     passed in.
81674aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia   */
81774aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia  public int getLengthOfNationalDestinationCode(PhoneNumber number) {
8185c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia    PhoneNumber copiedProto;
8195c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia    if (number.hasExtension()) {
8205c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia      // We don't want to alter the proto given to us, but we don't want to include the extension
8215c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia      // when we format it, so we copy it and clear the extension here.
82276f6569af0619d12afd19991d8ff69a9bea4c142Shaopeng Jia      copiedProto = new PhoneNumber();
82376f6569af0619d12afd19991d8ff69a9bea4c142Shaopeng Jia      copiedProto.mergeFrom(number);
82476f6569af0619d12afd19991d8ff69a9bea4c142Shaopeng Jia      copiedProto.clearExtension();
8255c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia    } else {
8265c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia      copiedProto = number;
8275c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia    }
8285c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia
8295c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia    String nationalSignificantNumber = format(copiedProto,
8305c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia                                              PhoneNumberUtil.PhoneNumberFormat.INTERNATIONAL);
831f59ccfca9dd02c4e3cf3e06b5cf184a8d0e67626Shaopeng Jia    String[] numberGroups = NON_DIGITS_PATTERN.split(nationalSignificantNumber);
8325c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia    // The pattern will start with "+COUNTRY_CODE " so the first group will always be the empty
833372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    // string (before the + symbol) and the second group will be the country calling code. The third
834372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    // group will be area code if it is not the last group.
8355c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia    if (numberGroups.length <= 3) {
8365c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia      return 0;
8375c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia    }
83874aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia
839f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia    if (getNumberType(number) == PhoneNumberType.MOBILE) {
840f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia      // For example Argentinian mobile numbers, when formatted in the international format, are in
841f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia      // the form of +54 9 NDC XXXX.... As a result, we take the length of the third group (NDC) and
842f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia      // add the length of the second group (which is the mobile token), which also forms part of
843f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia      // the national significant number. This assumes that the mobile token is always formatted
844f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia      // separately from the rest of the phone number.
845f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia      String mobileToken = getCountryMobileToken(number.getCountryCode());
846f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia      if (!mobileToken.equals("")) {
847f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia        return numberGroups[2].length() + numberGroups[3].length();
848f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia      }
84974aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia    }
8505c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia    return numberGroups[2].length();
851df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia  }
8525c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia
8535c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia  /**
854f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia   * Returns the mobile token for the provided country calling code if it has one, otherwise
855f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia   * returns an empty string. A mobile token is a number inserted before the area code when dialing
856f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia   * a mobile number from that country from abroad.
857f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia   *
858f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia   * @param countryCallingCode  the country calling code for which we want the mobile token
859f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia   * @return  the mobile token, as a string, for the given country calling code
860f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia   */
861f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia  public static String getCountryMobileToken(int countryCallingCode) {
862f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia    if (MOBILE_TOKEN_MAPPINGS.containsKey(countryCallingCode)) {
863f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia      return MOBILE_TOKEN_MAPPINGS.get(countryCallingCode);
864f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia    }
865f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia    return "";
866f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia  }
867f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia
868f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia  /**
8691524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * Normalizes a string of characters representing a phone number by replacing all characters found
8701524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * in the accompanying map with the values therein, and stripping all other characters if
8711524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * removeNonMatches is true.
8721524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *
8731524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @param number                     a string of characters representing a phone number
8741524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @param normalizationReplacements  a mapping of characters to what they should be replaced by in
8751524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *                                   the normalized version of the phone number
8761524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @param removeNonMatches           indicates whether characters that are not able to be replaced
8771524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *                                   should be stripped from the number. If this is false, they
8781524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *                                   will be left unchanged in the number.
8795c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia   * @return  the normalized string version of the phone number
8801524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
881f59ccfca9dd02c4e3cf3e06b5cf184a8d0e67626Shaopeng Jia  private static String normalizeHelper(String number,
882f59ccfca9dd02c4e3cf3e06b5cf184a8d0e67626Shaopeng Jia                                        Map<Character, Character> normalizationReplacements,
883f59ccfca9dd02c4e3cf3e06b5cf184a8d0e67626Shaopeng Jia                                        boolean removeNonMatches) {
884372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    StringBuilder normalizedNumber = new StringBuilder(number.length());
885203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    for (int i = 0; i < number.length(); i++) {
886203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia      char character = number.charAt(i);
8871524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      Character newDigit = normalizationReplacements.get(Character.toUpperCase(character));
8881524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      if (newDigit != null) {
8891524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia        normalizedNumber.append(newDigit);
8901524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      } else if (!removeNonMatches) {
8911524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia        normalizedNumber.append(character);
8921524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      }
8931524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      // If neither of the above are true, we remove this character.
8941524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
8951524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    return normalizedNumber.toString();
8961524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
8971524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
8983396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia  /**
8999ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia   * Sets or resets the PhoneNumberUtil singleton instance. If set to null, the next call to
9009ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia   * {@code getInstance()} will load (and return) the default instance.
9013396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia   */
902cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia  // @VisibleForTesting
9039ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia  static synchronized void setInstance(PhoneNumberUtil util) {
9049ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia    instance = util;
9051524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
9061524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
9071524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
908ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia   * Convenience method to get a list of what regions the library has metadata for.
9091524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
910372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  public Set<String> getSupportedRegions() {
911203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    return Collections.unmodifiableSet(supportedRegions);
9121524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
9131524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
9141524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
915cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia   * Convenience method to get a list of what global network calling codes the library has metadata
916cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia   * for.
917cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia   */
918cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia  public Set<Integer> getSupportedGlobalNetworkCallingCodes() {
919203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    return Collections.unmodifiableSet(countryCodesForNonGeographicalRegion);
920cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia  }
921cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia
922cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia  /**
923372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * Gets a {@link PhoneNumberUtil} instance to carry out international phone number formatting,
924372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * parsing, or validation. The instance is loaded with phone number metadata for a number of most
925372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * commonly used regions.
9261524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *
927372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * <p>The {@link PhoneNumberUtil} is implemented as a singleton. Therefore, calling getInstance
928372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * multiple times will only result in one instance being created.
9291524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *
9301524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @return a PhoneNumberUtil instance
9311524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
9321524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  public static synchronized PhoneNumberUtil getInstance() {
9331524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    if (instance == null) {
9349ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia      setInstance(createInstance(DEFAULT_METADATA_LOADER));
9351524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
9361524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    return instance;
9371524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
9381524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
9391524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
9409ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia   * Create a new {@link PhoneNumberUtil} instance to carry out international phone number
9419ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia   * formatting, parsing, or validation. The instance is loaded with all metadata by
942279df210d5a4215ee2273bd23d29de5dc29e8370Neil Fuller   * using the metadataSource specified.
943279df210d5a4215ee2273bd23d29de5dc29e8370Neil Fuller   *
944279df210d5a4215ee2273bd23d29de5dc29e8370Neil Fuller   * This method should only be used in the rare case in which you want to manage your own
945279df210d5a4215ee2273bd23d29de5dc29e8370Neil Fuller   * metadata loading. Calling this method multiple times is very expensive, as each time
946279df210d5a4215ee2273bd23d29de5dc29e8370Neil Fuller   * a new instance is created from scratch. When in doubt, use {@link #getInstance}.
947279df210d5a4215ee2273bd23d29de5dc29e8370Neil Fuller   *
948279df210d5a4215ee2273bd23d29de5dc29e8370Neil Fuller   * @param metadataSource Customized metadata source. This should not be null.
949279df210d5a4215ee2273bd23d29de5dc29e8370Neil Fuller   * @return a PhoneNumberUtil instance
950279df210d5a4215ee2273bd23d29de5dc29e8370Neil Fuller   */
951279df210d5a4215ee2273bd23d29de5dc29e8370Neil Fuller  public static PhoneNumberUtil createInstance(MetadataSource metadataSource) {
952279df210d5a4215ee2273bd23d29de5dc29e8370Neil Fuller    if (metadataSource == null) {
953279df210d5a4215ee2273bd23d29de5dc29e8370Neil Fuller      throw new IllegalArgumentException("metadataSource could not be null.");
954279df210d5a4215ee2273bd23d29de5dc29e8370Neil Fuller    }
955279df210d5a4215ee2273bd23d29de5dc29e8370Neil Fuller    return new PhoneNumberUtil(metadataSource,
956279df210d5a4215ee2273bd23d29de5dc29e8370Neil Fuller        CountryCodeToRegionCodeMap.getCountryCodeToRegionCodeMap());
957279df210d5a4215ee2273bd23d29de5dc29e8370Neil Fuller  }
958279df210d5a4215ee2273bd23d29de5dc29e8370Neil Fuller
959279df210d5a4215ee2273bd23d29de5dc29e8370Neil Fuller  /**
960279df210d5a4215ee2273bd23d29de5dc29e8370Neil Fuller   * Create a new {@link PhoneNumberUtil} instance to carry out international phone number
961279df210d5a4215ee2273bd23d29de5dc29e8370Neil Fuller   * formatting, parsing, or validation. The instance is loaded with all metadata by
9629ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia   * using the metadataLoader specified.
9639ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia   *
9649ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia   * This method should only be used in the rare case in which you want to manage your own
9659ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia   * metadata loading. Calling this method multiple times is very expensive, as each time
9669ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia   * a new instance is created from scratch. When in doubt, use {@link #getInstance}.
9679ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia   *
968279df210d5a4215ee2273bd23d29de5dc29e8370Neil Fuller   * @param metadataLoader Customized metadata loader. This should not be null.
9699ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia   * @return a PhoneNumberUtil instance
9709ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia   */
9719ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia  public static PhoneNumberUtil createInstance(MetadataLoader metadataLoader) {
9729ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia    if (metadataLoader == null) {
9739ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia      throw new IllegalArgumentException("metadataLoader could not be null.");
9749ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia    }
975279df210d5a4215ee2273bd23d29de5dc29e8370Neil Fuller    return createInstance(new MultiFileMetadataSourceImpl(metadataLoader));
9769ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia  }
9779ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia
9789ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia  /**
979203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia   * Helper function to check if the national prefix formatting rule has the first group only, i.e.,
980203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia   * does not start with the national prefix.
981203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia   */
982203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia  static boolean formattingRuleHasFirstGroupOnly(String nationalPrefixFormattingRule) {
9833396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia    return nationalPrefixFormattingRule.length() == 0 ||
9843396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia        FIRST_GROUP_ONLY_PREFIX_PATTERN.matcher(nationalPrefixFormattingRule).matches();
985203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia  }
986203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia
987203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia  /**
988203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia   * Tests whether a phone number has a geographical association. It checks if the number is
989203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia   * associated to a certain region in the country where it belongs to. Note that this doesn't
990203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia   * verify if the number is actually in use.
9917a81979b0076f18b31b47b7df2beac29735f3a37Cecilia Roes   *
9927a81979b0076f18b31b47b7df2beac29735f3a37Cecilia Roes   * A similar method is implemented as PhoneNumberOfflineGeocoder.canBeGeocoded, which performs a
9937a81979b0076f18b31b47b7df2beac29735f3a37Cecilia Roes   * looser check, since it only prevents cases where prefixes overlap for geocodable and
9947a81979b0076f18b31b47b7df2beac29735f3a37Cecilia Roes   * non-geocodable numbers. Also, if new phone number types were added, we should check if this
9957a81979b0076f18b31b47b7df2beac29735f3a37Cecilia Roes   * other method should be updated too.
996203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia   */
997203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia  boolean isNumberGeographical(PhoneNumber phoneNumber) {
998203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    PhoneNumberType numberType = getNumberType(phoneNumber);
999203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    // TODO: Include mobile phone numbers from countries like Indonesia, which has some
1000203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    // mobile numbers that are geographical.
1001203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    return numberType == PhoneNumberType.FIXED_LINE ||
1002203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia        numberType == PhoneNumberType.FIXED_LINE_OR_MOBILE;
1003203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia  }
1004203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia
1005203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia  /**
1006be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia   * Helper function to check region code is not unknown or null.
10071524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
1008be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia  private boolean isValidRegionCode(String regionCode) {
1009d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia    return regionCode != null && supportedRegions.contains(regionCode);
1010372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  }
1011372bff8dd464574d36737d47e495cad14346653cShaopeng Jia
1012372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  /**
1013528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia   * Helper function to check the country calling code is valid.
1014372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   */
1015528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia  private boolean hasValidCountryCallingCode(int countryCallingCode) {
1016528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    return countryCallingCodeToRegionCodeMap.containsKey(countryCallingCode);
10171524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
10181524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
10191524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
10201524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * Formats a phone number in the specified format using default rules. Note that this does not
10211524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * promise to produce a phone number that the user can dial from where they are - although we do
10221524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * format in either 'national' or 'international' format depending on what the client asks for, we
10231524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * do not currently support a more abbreviated format, such as for users in the same "area" who
10241524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * could potentially dial the number without area code. Note that if the phone number has a
1025372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * country calling code of 0 or an otherwise invalid country calling code, we cannot work out
1026372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * which formatting rules to apply so we return the national significant number with no formatting
1027372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * applied.
10281524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *
10291524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @param number         the phone number to be formatted
10301524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @param numberFormat   the format the phone number should be formatted into
10315c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia   * @return  the formatted phone number
10321524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
10331524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  public String format(PhoneNumber number, PhoneNumberFormat numberFormat) {
1034082e1e80b0bcb2911de5d26981b592f2c2b9d3f6Shaopeng Jia    if (number.getNationalNumber() == 0 && number.hasRawInput()) {
1035203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia      // Unparseable numbers that kept their raw input just use that.
1036203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia      // This is the only case where a number can be formatted as E164 without a
1037203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia      // leading '+' symbol (but the original number wasn't parseable anyway).
1038203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia      // TODO: Consider removing the 'if' above so that unparseable
1039203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia      // strings without raw input format to the empty string instead of "+00"
1040082e1e80b0bcb2911de5d26981b592f2c2b9d3f6Shaopeng Jia      String rawInput = number.getRawInput();
1041082e1e80b0bcb2911de5d26981b592f2c2b9d3f6Shaopeng Jia      if (rawInput.length() > 0) {
1042082e1e80b0bcb2911de5d26981b592f2c2b9d3f6Shaopeng Jia        return rawInput;
1043082e1e80b0bcb2911de5d26981b592f2c2b9d3f6Shaopeng Jia      }
1044082e1e80b0bcb2911de5d26981b592f2c2b9d3f6Shaopeng Jia    }
1045372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    StringBuilder formattedNumber = new StringBuilder(20);
104676f6569af0619d12afd19991d8ff69a9bea4c142Shaopeng Jia    format(number, numberFormat, formattedNumber);
1047be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    return formattedNumber.toString();
1048be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia  }
1049be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia
1050d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia  /**
105196a7214cdabf08f53f5b1a560304601c9f65e0b9Shaopeng Jia   * Same as {@link #format(PhoneNumber, PhoneNumberFormat)}, but accepts a mutable StringBuilder as
105296a7214cdabf08f53f5b1a560304601c9f65e0b9Shaopeng Jia   * a parameter to decrease object creation when invoked many times.
1053d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   */
105476f6569af0619d12afd19991d8ff69a9bea4c142Shaopeng Jia  public void format(PhoneNumber number, PhoneNumberFormat numberFormat,
1055372bff8dd464574d36737d47e495cad14346653cShaopeng Jia                     StringBuilder formattedNumber) {
1056372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    // Clear the StringBuilder first.
1057be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    formattedNumber.setLength(0);
1058d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia    int countryCallingCode = number.getCountryCode();
10595c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia    String nationalSignificantNumber = getNationalSignificantNumber(number);
10607a81979b0076f18b31b47b7df2beac29735f3a37Cecilia Roes
10611524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    if (numberFormat == PhoneNumberFormat.E164) {
1062203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia      // Early exit for E164 case (even if the country calling code is invalid) since no formatting
1063203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia      // of the national number needs to be applied. Extensions are not formatted.
1064be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia      formattedNumber.append(nationalSignificantNumber);
1065cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia      prefixNumberWithCountryCallingCode(countryCallingCode, PhoneNumberFormat.E164,
1066cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia                                         formattedNumber);
1067be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia      return;
10681524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
1069cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia    if (!hasValidCountryCallingCode(countryCallingCode)) {
1070be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia      formattedNumber.append(nationalSignificantNumber);
1071be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia      return;
10721524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
1073203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    // Note getRegionCodeForCountryCode() is used because formatting information for regions which
1074203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    // share a country calling code is contained by only one region for performance reasons. For
1075203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    // example, for NANPA regions it will be contained in the metadata for US.
1076203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    String regionCode = getRegionCodeForCountryCode(countryCallingCode);
1077203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    // Metadata cannot be null because the country calling code is valid (which means that the
1078203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    // region code cannot be ZZ and must be one of our supported region codes).
1079528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    PhoneMetadata metadata =
1080528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        getMetadataForRegionOrCallingCode(countryCallingCode, regionCode);
1081cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia    formattedNumber.append(formatNsn(nationalSignificantNumber, metadata, numberFormat));
1082cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia    maybeAppendFormattedExtension(number, metadata, numberFormat, formattedNumber);
1083cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia    prefixNumberWithCountryCallingCode(countryCallingCode, numberFormat, formattedNumber);
10841524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
10851524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
10861524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
10871524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * Formats a phone number in the specified format using client-defined formatting rules. Note that
1088372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * if the phone number has a country calling code of zero or an otherwise invalid country calling
1089372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * code, we cannot work out things like whether there should be a national prefix applied, or how
1090372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * to format extensions, so we return the national significant number with no formatting applied.
10911524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *
10921524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @param number                        the phone number to be formatted
10931524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @param numberFormat                  the format the phone number should be formatted into
10941524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @param userDefinedFormats            formatting rules specified by clients
10955c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia   * @return  the formatted phone number
10961524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
10971524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  public String formatByPattern(PhoneNumber number,
10981524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia                                PhoneNumberFormat numberFormat,
10991524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia                                List<NumberFormat> userDefinedFormats) {
1100372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    int countryCallingCode = number.getCountryCode();
11014b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia    String nationalSignificantNumber = getNationalSignificantNumber(number);
1102203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    if (!hasValidCountryCallingCode(countryCallingCode)) {
1103203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia      return nationalSignificantNumber;
1104203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    }
1105372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    // Note getRegionCodeForCountryCode() is used because formatting information for regions which
1106372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    // share a country calling code is contained by only one region for performance reasons. For
1107372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    // example, for NANPA regions it will be contained in the metadata for US.
1108372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    String regionCode = getRegionCodeForCountryCode(countryCallingCode);
1109203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    // Metadata cannot be null because the country calling code is valid
1110528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    PhoneMetadata metadata =
1111528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        getMetadataForRegionOrCallingCode(countryCallingCode, regionCode);
1112cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia
1113cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia    StringBuilder formattedNumber = new StringBuilder(20);
1114cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia
1115cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia    NumberFormat formattingPattern =
111693399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller        chooseFormattingPatternForNumber(userDefinedFormats, nationalSignificantNumber);
1117cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia    if (formattingPattern == null) {
1118cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia      // If no pattern above is matched, we format the number as a whole.
1119cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia      formattedNumber.append(nationalSignificantNumber);
1120cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia    } else {
112193399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller      NumberFormat numFormatCopy = new NumberFormat();
1122cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia      // Before we do a replacement of the national prefix pattern $NP with the national prefix, we
1123cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia      // need to copy the rule so that subsequent replacements for different numbers have the
1124cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia      // appropriate national prefix.
112593399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller      numFormatCopy.mergeFrom(formattingPattern);
112693399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller      String nationalPrefixFormattingRule = formattingPattern.getNationalPrefixFormattingRule();
11271524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      if (nationalPrefixFormattingRule.length() > 0) {
112893399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller        String nationalPrefix = metadata.getNationalPrefix();
1129f59ccfca9dd02c4e3cf3e06b5cf184a8d0e67626Shaopeng Jia        if (nationalPrefix.length() > 0) {
1130df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia          // Replace $NP with national prefix and $FG with the first group ($1).
1131df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia          nationalPrefixFormattingRule =
1132df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia              NP_PATTERN.matcher(nationalPrefixFormattingRule).replaceFirst(nationalPrefix);
1133df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia          nationalPrefixFormattingRule =
1134df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia              FG_PATTERN.matcher(nationalPrefixFormattingRule).replaceFirst("\\$1");
113593399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller          numFormatCopy.setNationalPrefixFormattingRule(nationalPrefixFormattingRule);
1136df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia        } else {
1137df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia          // We don't want to have a rule for how to format the national prefix if there isn't one.
113893399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller          numFormatCopy.clearNationalPrefixFormattingRule();
1139df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia        }
11401524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      }
1141cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia      formattedNumber.append(
1142cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia          formatNsnUsingPattern(nationalSignificantNumber, numFormatCopy, numberFormat));
11431524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
1144cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia    maybeAppendFormattedExtension(number, metadata, numberFormat, formattedNumber);
1145cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia    prefixNumberWithCountryCallingCode(countryCallingCode, numberFormat, formattedNumber);
1146be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    return formattedNumber.toString();
11471524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
11481524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
114952699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia  /**
115052699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia   * Formats a phone number in national format for dialing using the carrier as specified in the
1151372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * {@code carrierCode}. The {@code carrierCode} will always be used regardless of whether the
1152372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * phone number already has a preferred domestic carrier code stored. If {@code carrierCode}
1153372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * contains an empty string, returns the number in national format without any carrier code.
115452699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia   *
115552699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia   * @param number  the phone number to be formatted
115652699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia   * @param carrierCode  the carrier selection code to be used
115752699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia   * @return  the formatted phone number in national format for dialing using the carrier as
1158372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *          specified in the {@code carrierCode}
115952699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia   */
11604b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia  public String formatNationalNumberWithCarrierCode(PhoneNumber number, String carrierCode) {
1161372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    int countryCallingCode = number.getCountryCode();
11624b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia    String nationalSignificantNumber = getNationalSignificantNumber(number);
1163203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    if (!hasValidCountryCallingCode(countryCallingCode)) {
1164203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia      return nationalSignificantNumber;
1165203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    }
1166203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia
1167372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    // Note getRegionCodeForCountryCode() is used because formatting information for regions which
1168372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    // share a country calling code is contained by only one region for performance reasons. For
1169372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    // example, for NANPA regions it will be contained in the metadata for US.
1170372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    String regionCode = getRegionCodeForCountryCode(countryCallingCode);
1171203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    // Metadata cannot be null because the country calling code is valid.
1172203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    PhoneMetadata metadata = getMetadataForRegionOrCallingCode(countryCallingCode, regionCode);
11734b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia
1174372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    StringBuilder formattedNumber = new StringBuilder(20);
1175cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia    formattedNumber.append(formatNsn(nationalSignificantNumber, metadata,
1176cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia                                     PhoneNumberFormat.NATIONAL, carrierCode));
1177cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia    maybeAppendFormattedExtension(number, metadata, PhoneNumberFormat.NATIONAL, formattedNumber);
1178cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia    prefixNumberWithCountryCallingCode(countryCallingCode, PhoneNumberFormat.NATIONAL,
1179cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia                                       formattedNumber);
11804b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia    return formattedNumber.toString();
11814b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia  }
11824b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia
1183528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia  private PhoneMetadata getMetadataForRegionOrCallingCode(
1184528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia      int countryCallingCode, String regionCode) {
1185528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    return REGION_CODE_FOR_NON_GEO_ENTITY.equals(regionCode)
1186528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        ? getMetadataForNonGeographicalRegion(countryCallingCode)
1187528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        : getMetadataForRegion(regionCode);
1188528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia  }
1189528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia
11901524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
119152699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia   * Formats a phone number in national format for dialing using the carrier as specified in the
1192372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * preferredDomesticCarrierCode field of the PhoneNumber object passed in. If that is missing,
1193372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * use the {@code fallbackCarrierCode} passed in instead. If there is no
1194372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * {@code preferredDomesticCarrierCode}, and the {@code fallbackCarrierCode} contains an empty
1195372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * string, return the number in national format without any carrier code.
119652699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia   *
1197372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * <p>Use {@link #formatNationalNumberWithCarrierCode} instead if the carrier code passed in
1198372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * should take precedence over the number's {@code preferredDomesticCarrierCode} when formatting.
119952699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia   *
120052699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia   * @param number  the phone number to be formatted
120152699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia   * @param fallbackCarrierCode  the carrier selection code to be used, if none is found in the
1202372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *     phone number itself
120352699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia   * @return  the formatted phone number in national format for dialing using the number's
1204372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *     {@code preferredDomesticCarrierCode}, or the {@code fallbackCarrierCode} passed in if
1205372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *     none is found
120652699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia   */
120752699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia  public String formatNationalNumberWithPreferredCarrierCode(PhoneNumber number,
120852699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia                                                             String fallbackCarrierCode) {
120952699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia    return formatNationalNumberWithCarrierCode(number, number.hasPreferredDomesticCarrierCode()
121052699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia                                                       ? number.getPreferredDomesticCarrierCode()
121152699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia                                                       : fallbackCarrierCode);
121252699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia  }
121352699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia
121452699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia  /**
1215ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia   * Returns a number formatted in such a way that it can be dialed from a mobile phone in a
1216ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia   * specific region. If the number cannot be reached from the region (e.g. some countries block
1217ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia   * toll-free numbers from being called outside of the country), the method returns an empty
1218ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia   * string.
1219ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia   *
1220ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia   * @param number  the phone number to be formatted
1221ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia   * @param regionCallingFrom  the region where the call is being placed
1222ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia   * @param withFormatting  whether the number should be returned with formatting symbols, such as
1223ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia   *     spaces and dashes.
1224ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia   * @return  the formatted phone number
1225ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia   */
1226ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia  public String formatNumberForMobileDialing(PhoneNumber number, String regionCallingFrom,
1227ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia                                             boolean withFormatting) {
1228528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    int countryCallingCode = number.getCountryCode();
1229528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    if (!hasValidCountryCallingCode(countryCallingCode)) {
1230ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia      return number.hasRawInput() ? number.getRawInput() : "";
1231ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia    }
1232ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia
1233485e6d5c6e48a1fc43cc0a090e687c723dac056cShaopeng Jia    String formattedNumber = "";
1234ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia    // Clear the extension, as that part cannot normally be dialed together with the main number.
1235ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia    PhoneNumber numberNoExt = new PhoneNumber().mergeFrom(number).clearExtension();
1236528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    String regionCode = getRegionCodeForCountryCode(countryCallingCode);
1237f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia    PhoneNumberType numberType = getNumberType(numberNoExt);
1238f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia    boolean isValidNumber = (numberType != PhoneNumberType.UNKNOWN);
1239485e6d5c6e48a1fc43cc0a090e687c723dac056cShaopeng Jia    if (regionCallingFrom.equals(regionCode)) {
1240485e6d5c6e48a1fc43cc0a090e687c723dac056cShaopeng Jia      boolean isFixedLineOrMobile =
1241485e6d5c6e48a1fc43cc0a090e687c723dac056cShaopeng Jia          (numberType == PhoneNumberType.FIXED_LINE) || (numberType == PhoneNumberType.MOBILE) ||
1242485e6d5c6e48a1fc43cc0a090e687c723dac056cShaopeng Jia          (numberType == PhoneNumberType.FIXED_LINE_OR_MOBILE);
1243485e6d5c6e48a1fc43cc0a090e687c723dac056cShaopeng Jia      // Carrier codes may be needed in some countries. We handle this here.
1244485e6d5c6e48a1fc43cc0a090e687c723dac056cShaopeng Jia      if (regionCode.equals("CO") && numberType == PhoneNumberType.FIXED_LINE) {
124596a7214cdabf08f53f5b1a560304601c9f65e0b9Shaopeng Jia        formattedNumber =
124696a7214cdabf08f53f5b1a560304601c9f65e0b9Shaopeng Jia            formatNationalNumberWithCarrierCode(numberNoExt, COLOMBIA_MOBILE_TO_FIXED_LINE_PREFIX);
1247485e6d5c6e48a1fc43cc0a090e687c723dac056cShaopeng Jia      } else if (regionCode.equals("BR") && isFixedLineOrMobile) {
1248485e6d5c6e48a1fc43cc0a090e687c723dac056cShaopeng Jia        formattedNumber = numberNoExt.hasPreferredDomesticCarrierCode()
1249485e6d5c6e48a1fc43cc0a090e687c723dac056cShaopeng Jia            ? formattedNumber = formatNationalNumberWithPreferredCarrierCode(numberNoExt, "")
1250485e6d5c6e48a1fc43cc0a090e687c723dac056cShaopeng Jia            // Brazilian fixed line and mobile numbers need to be dialed with a carrier code when
1251485e6d5c6e48a1fc43cc0a090e687c723dac056cShaopeng Jia            // called within Brazil. Without that, most of the carriers won't connect the call.
1252485e6d5c6e48a1fc43cc0a090e687c723dac056cShaopeng Jia            // Because of that, we return an empty string here.
1253485e6d5c6e48a1fc43cc0a090e687c723dac056cShaopeng Jia            : "";
1254f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia      } else if (isValidNumber && regionCode.equals("HU")) {
12553396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia        // The national format for HU numbers doesn't contain the national prefix, because that is
12563396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia        // how numbers are normally written down. However, the national prefix is obligatory when
1257f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia        // dialing from a mobile phone, except for short numbers. As a result, we add it back here
1258f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia        // if it is a valid regular length phone number.
12593396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia        formattedNumber =
12603396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia            getNddPrefixForRegion(regionCode, true /* strip non-digits */) +
12613396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia            " " + format(numberNoExt, PhoneNumberFormat.NATIONAL);
1262f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia      } else if (countryCallingCode == NANPA_COUNTRY_CODE) {
1263f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia        // For NANPA countries, we output international format for numbers that can be dialed
1264f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia        // internationally, since that always works, except for numbers which might potentially be
1265f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia        // short numbers, which are always dialled in national format.
1266f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia        PhoneMetadata regionMetadata = getMetadataForRegion(regionCallingFrom);
1267f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia        if (canBeInternationallyDialled(numberNoExt) &&
1268f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia            !isShorterThanPossibleNormalNumber(regionMetadata,
1269f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia                getNationalSignificantNumber(numberNoExt))) {
1270f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia          formattedNumber = format(numberNoExt, PhoneNumberFormat.INTERNATIONAL);
1271f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia        } else {
1272f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia          formattedNumber = format(numberNoExt, PhoneNumberFormat.NATIONAL);
1273f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia        }
127496a7214cdabf08f53f5b1a560304601c9f65e0b9Shaopeng Jia      } else {
1275f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia        // For non-geographical countries, and Mexican and Chilean fixed line and mobile numbers, we
1276f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia        // output international format for numbers that can be dialed internationally as that always
1277f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia        // works.
1278f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia        if ((regionCode.equals(REGION_CODE_FOR_NON_GEO_ENTITY) ||
1279485e6d5c6e48a1fc43cc0a090e687c723dac056cShaopeng Jia            // MX fixed line and mobile numbers should always be formatted in international format,
1280485e6d5c6e48a1fc43cc0a090e687c723dac056cShaopeng Jia            // even when dialed within MX. For national format to work, a carrier code needs to be
1281485e6d5c6e48a1fc43cc0a090e687c723dac056cShaopeng Jia            // used, and the correct carrier code depends on if the caller and callee are from the
1282485e6d5c6e48a1fc43cc0a090e687c723dac056cShaopeng Jia            // same local area. It is trickier to get that to work correctly than using
1283485e6d5c6e48a1fc43cc0a090e687c723dac056cShaopeng Jia            // international format, which is tested to work fine on all carriers.
12843396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia            // CL fixed line numbers need the national prefix when dialing in the national format,
12853396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia            // but don't have it when used for display. The reverse is true for mobile numbers.
12863396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia            // As a result, we output them in the international format to make it work.
12877a81979b0076f18b31b47b7df2beac29735f3a37Cecilia Roes            ((regionCode.equals("MX") || regionCode.equals("CL")) &&
12887a81979b0076f18b31b47b7df2beac29735f3a37Cecilia Roes             isFixedLineOrMobile)) &&
1289485e6d5c6e48a1fc43cc0a090e687c723dac056cShaopeng Jia            canBeInternationallyDialled(numberNoExt)) {
1290485e6d5c6e48a1fc43cc0a090e687c723dac056cShaopeng Jia          formattedNumber = format(numberNoExt, PhoneNumberFormat.INTERNATIONAL);
1291485e6d5c6e48a1fc43cc0a090e687c723dac056cShaopeng Jia        } else {
1292485e6d5c6e48a1fc43cc0a090e687c723dac056cShaopeng Jia          formattedNumber = format(numberNoExt, PhoneNumberFormat.NATIONAL);
1293485e6d5c6e48a1fc43cc0a090e687c723dac056cShaopeng Jia        }
129496a7214cdabf08f53f5b1a560304601c9f65e0b9Shaopeng Jia      }
1295f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia    } else if (isValidNumber && canBeInternationallyDialled(numberNoExt)) {
1296f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia      // We assume that short numbers are not diallable from outside their region, so if a number
1297f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia      // is not a valid regular length phone number, we treat it as if it cannot be internationally
1298f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia      // dialled.
1299ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia      return withFormatting ? format(numberNoExt, PhoneNumberFormat.INTERNATIONAL)
1300ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia                            : format(numberNoExt, PhoneNumberFormat.E164);
1301ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia    }
130296a7214cdabf08f53f5b1a560304601c9f65e0b9Shaopeng Jia    return withFormatting ? formattedNumber
1303bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia                          : normalizeDiallableCharsOnly(formattedNumber);
1304ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia  }
1305ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia
1306ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia  /**
1307372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * Formats a phone number for out-of-country dialing purposes. If no regionCallingFrom is
1308372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * supplied, we format the number in its INTERNATIONAL format. If the country calling code is the
1309d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   * same as that of the region where the number is from, then NATIONAL formatting will be applied.
13101524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *
1311372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * <p>If the number itself has a country calling code of zero or an otherwise invalid country
1312372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * calling code, then we return the number with no formatting applied.
13131524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *
1314372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * <p>Note this function takes care of the case for calling inside of NANPA and between Russia and
1315372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * Kazakhstan (who share the same country calling code). In those cases, no international prefix
1316372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * is used. For regions which have multiple international prefixes, the number in its
1317372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * INTERNATIONAL format will be returned instead.
13181524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *
13191524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @param number               the phone number to be formatted
1320d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   * @param regionCallingFrom    the region where the call is being placed
13215c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia   * @return  the formatted phone number
13221524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
1323d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia  public String formatOutOfCountryCallingNumber(PhoneNumber number,
1324d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia                                                String regionCallingFrom) {
1325372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    if (!isValidRegionCode(regionCallingFrom)) {
1326bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia      logger.log(Level.WARNING,
1327cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia                 "Trying to format number from invalid region "
1328cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia                 + regionCallingFrom
1329cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia                 + ". International formatting applied.");
13301524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      return format(number, PhoneNumberFormat.INTERNATIONAL);
13311524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
1332372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    int countryCallingCode = number.getCountryCode();
13335c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia    String nationalSignificantNumber = getNationalSignificantNumber(number);
1334528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    if (!hasValidCountryCallingCode(countryCallingCode)) {
13351524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      return nationalSignificantNumber;
13361524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
1337372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    if (countryCallingCode == NANPA_COUNTRY_CODE) {
1338372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      if (isNANPACountry(regionCallingFrom)) {
1339372bff8dd464574d36737d47e495cad14346653cShaopeng Jia        // For NANPA regions, return the national format for these regions but prefix it with the
1340372bff8dd464574d36737d47e495cad14346653cShaopeng Jia        // country calling code.
1341372bff8dd464574d36737d47e495cad14346653cShaopeng Jia        return countryCallingCode + " " + format(number, PhoneNumberFormat.NATIONAL);
13424b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia      }
1343cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia    } else if (countryCallingCode == getCountryCodeForValidRegion(regionCallingFrom)) {
134477aadd284847681bd66af639636c2fa43e418c2bShaopeng Jia      // If regions share a country calling code, the country calling code need not be dialled.
134577aadd284847681bd66af639636c2fa43e418c2bShaopeng Jia      // This also applies when dialling within a region, so this if clause covers both these cases.
134677aadd284847681bd66af639636c2fa43e418c2bShaopeng Jia      // Technically this is the case for dialling from La Reunion to other overseas departments of
134777aadd284847681bd66af639636c2fa43e418c2bShaopeng Jia      // France (French Guiana, Martinique, Guadeloupe), but not vice versa - so we don't cover this
134877aadd284847681bd66af639636c2fa43e418c2bShaopeng Jia      // edge case for now and for those cases return the version including country calling code.
134977aadd284847681bd66af639636c2fa43e418c2bShaopeng Jia      // Details here: http://www.petitfute.com/voyage/225-info-pratiques-reunion
13501524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      return format(number, PhoneNumberFormat.NATIONAL);
13511524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
1352203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    // Metadata cannot be null because we checked 'isValidRegionCode()' above.
1353528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    PhoneMetadata metadataForRegionCallingFrom = getMetadataForRegion(regionCallingFrom);
135493399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller    String internationalPrefix = metadataForRegionCallingFrom.getInternationalPrefix();
1355be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia
1356372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    // For regions that have multiple international prefixes, the international format of the
13571524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    // number is returned, unless there is a preferred international prefix.
13581524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    String internationalPrefixForFormatting = "";
13591524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    if (UNIQUE_INTERNATIONAL_PREFIX.matcher(internationalPrefix).matches()) {
13601524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      internationalPrefixForFormatting = internationalPrefix;
136193399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller    } else if (metadataForRegionCallingFrom.hasPreferredInternationalPrefix()) {
1362528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia      internationalPrefixForFormatting =
136393399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller          metadataForRegionCallingFrom.getPreferredInternationalPrefix();
13641524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
1365be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia
1366528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    String regionCode = getRegionCodeForCountryCode(countryCallingCode);
1367203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    // Metadata cannot be null because the country calling code is valid.
1368528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    PhoneMetadata metadataForRegion =
1369528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        getMetadataForRegionOrCallingCode(countryCallingCode, regionCode);
1370528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    String formattedNationalNumber =
1371cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia        formatNsn(nationalSignificantNumber, metadataForRegion, PhoneNumberFormat.INTERNATIONAL);
1372372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    StringBuilder formattedNumber = new StringBuilder(formattedNationalNumber);
1373cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia    maybeAppendFormattedExtension(number, metadataForRegion, PhoneNumberFormat.INTERNATIONAL,
1374cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia                                  formattedNumber);
1375be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    if (internationalPrefixForFormatting.length() > 0) {
1376372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      formattedNumber.insert(0, " ").insert(0, countryCallingCode).insert(0, " ")
1377be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia          .insert(0, internationalPrefixForFormatting);
1378be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    } else {
1379cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia      prefixNumberWithCountryCallingCode(countryCallingCode,
1380cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia                                         PhoneNumberFormat.INTERNATIONAL,
1381cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia                                         formattedNumber);
1382be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    }
1383be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    return formattedNumber.toString();
13841524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
13851524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
138654923fc72f0faeb11fe58a545c0314f6051b14aaShaopeng Jia  /**
138754923fc72f0faeb11fe58a545c0314f6051b14aaShaopeng Jia   * Formats a phone number using the original phone number format that the number is parsed from.
138854923fc72f0faeb11fe58a545c0314f6051b14aaShaopeng Jia   * The original format is embedded in the country_code_source field of the PhoneNumber object
138954923fc72f0faeb11fe58a545c0314f6051b14aaShaopeng Jia   * passed in. If such information is missing, the number will be formatted into the NATIONAL
1390528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia   * format by default. When the number contains a leading zero and this is unexpected for this
1391528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia   * country, or we don't have a formatting pattern for the number, the method returns the raw input
1392528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia   * when it is available.
139354923fc72f0faeb11fe58a545c0314f6051b14aaShaopeng Jia   *
1394528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia   * Note this method guarantees no digit will be inserted, removed or modified as a result of
1395528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia   * formatting.
1396cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia   *
1397372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * @param number  the phone number that needs to be formatted in its original number format
1398372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * @param regionCallingFrom  the region whose IDD needs to be prefixed if the original number
13994b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia   *     has one
14004b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia   * @return  the formatted phone number in its original number format
140154923fc72f0faeb11fe58a545c0314f6051b14aaShaopeng Jia   */
1402372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  public String formatInOriginalFormat(PhoneNumber number, String regionCallingFrom) {
14035cd062f9cba053c771bcea181fec210279ec030bShaopeng Jia    if (number.hasRawInput() &&
1404528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        (hasUnexpectedItalianLeadingZero(number) || !hasFormattingPatternForNumber(number))) {
14055cd062f9cba053c771bcea181fec210279ec030bShaopeng Jia      // We check if we have the formatting pattern because without that, we might format the number
1406528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia      // as a group without national prefix.
14071940212be2ff2ac5bf7d91eabbdb34e10d9b8e2eShaopeng Jia      return number.getRawInput();
14081940212be2ff2ac5bf7d91eabbdb34e10d9b8e2eShaopeng Jia    }
14094b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia    if (!number.hasCountryCodeSource()) {
141054923fc72f0faeb11fe58a545c0314f6051b14aaShaopeng Jia      return format(number, PhoneNumberFormat.NATIONAL);
141154923fc72f0faeb11fe58a545c0314f6051b14aaShaopeng Jia    }
1412d470984844c388d6766c3de6ac64e93e00480fc9Flavio Lerda    String formattedNumber;
141354923fc72f0faeb11fe58a545c0314f6051b14aaShaopeng Jia    switch (number.getCountryCodeSource()) {
141454923fc72f0faeb11fe58a545c0314f6051b14aaShaopeng Jia      case FROM_NUMBER_WITH_PLUS_SIGN:
1415d470984844c388d6766c3de6ac64e93e00480fc9Flavio Lerda        formattedNumber = format(number, PhoneNumberFormat.INTERNATIONAL);
1416d470984844c388d6766c3de6ac64e93e00480fc9Flavio Lerda        break;
141754923fc72f0faeb11fe58a545c0314f6051b14aaShaopeng Jia      case FROM_NUMBER_WITH_IDD:
1418d470984844c388d6766c3de6ac64e93e00480fc9Flavio Lerda        formattedNumber = formatOutOfCountryCallingNumber(number, regionCallingFrom);
1419d470984844c388d6766c3de6ac64e93e00480fc9Flavio Lerda        break;
142054923fc72f0faeb11fe58a545c0314f6051b14aaShaopeng Jia      case FROM_NUMBER_WITHOUT_PLUS_SIGN:
1421d470984844c388d6766c3de6ac64e93e00480fc9Flavio Lerda        formattedNumber = format(number, PhoneNumberFormat.INTERNATIONAL).substring(1);
1422d470984844c388d6766c3de6ac64e93e00480fc9Flavio Lerda        break;
14234b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia      case FROM_DEFAULT_COUNTRY:
1424528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        // Fall-through to default case.
142554923fc72f0faeb11fe58a545c0314f6051b14aaShaopeng Jia      default:
1426528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        String regionCode = getRegionCodeForCountryCode(number.getCountryCode());
1427528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        // We strip non-digits from the NDD here, and from the raw input later, so that we can
1428528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        // compare them easily.
1429528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        String nationalPrefix = getNddPrefixForRegion(regionCode, true /* strip non-digits */);
1430528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        String nationalFormat = format(number, PhoneNumberFormat.NATIONAL);
1431528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        if (nationalPrefix == null || nationalPrefix.length() == 0) {
1432528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia          // If the region doesn't have a national prefix at all, we can safely return the national
1433528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia          // format without worrying about a national prefix being added.
1434528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia          formattedNumber = nationalFormat;
1435528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia          break;
1436528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        }
1437528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        // Otherwise, we check if the original number was entered with a national prefix.
1438528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        if (rawInputContainsNationalPrefix(
1439528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia            number.getRawInput(), nationalPrefix, regionCode)) {
1440528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia          // If so, we can safely return the national format.
1441528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia          formattedNumber = nationalFormat;
1442528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia          break;
1443528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        }
1444203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia        // Metadata cannot be null here because getNddPrefixForRegion() (above) returns null if
1445203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia        // there is no metadata for the region.
1446528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        PhoneMetadata metadata = getMetadataForRegion(regionCode);
1447528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        String nationalNumber = getNationalSignificantNumber(number);
1448528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        NumberFormat formatRule =
144993399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller            chooseFormattingPatternForNumber(metadata.numberFormats(), nationalNumber);
1450203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia        // The format rule could still be null here if the national number was 0 and there was no
1451203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia        // raw input (this should not be possible for numbers generated by the phonenumber library
1452203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia        // as they would also not have a country calling code and we would have exited earlier).
1453203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia        if (formatRule == null) {
1454203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia          formattedNumber = nationalFormat;
1455203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia          break;
1456203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia        }
1457528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        // When the format we apply to this number doesn't contain national prefix, we can just
1458528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        // return the national format.
14597a81979b0076f18b31b47b7df2beac29735f3a37Cecilia Roes        // TODO: Refactor the code below with the code in
14607a81979b0076f18b31b47b7df2beac29735f3a37Cecilia Roes        // isNationalPrefixPresentIfRequired.
146193399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller        String candidateNationalPrefixRule = formatRule.getNationalPrefixFormattingRule();
1462528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        // We assume that the first-group symbol will never be _before_ the national prefix.
1463528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        int indexOfFirstGroup = candidateNationalPrefixRule.indexOf("$1");
1464528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        if (indexOfFirstGroup <= 0) {
1465528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia          formattedNumber = nationalFormat;
1466528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia          break;
1467528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        }
1468528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        candidateNationalPrefixRule =
1469528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia            candidateNationalPrefixRule.substring(0, indexOfFirstGroup);
1470528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        candidateNationalPrefixRule = normalizeDigitsOnly(candidateNationalPrefixRule);
1471528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        if (candidateNationalPrefixRule.length() == 0) {
1472528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia          // National prefix not used when formatting this number.
1473528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia          formattedNumber = nationalFormat;
1474528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia          break;
1475528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        }
1476528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        // Otherwise, we need to remove the national prefix from our output.
147793399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller        NumberFormat numFormatCopy = new NumberFormat();
147893399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller        numFormatCopy.mergeFrom(formatRule);
147993399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller        numFormatCopy.clearNationalPrefixFormattingRule();
1480528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        List<NumberFormat> numberFormats = new ArrayList<NumberFormat>(1);
1481528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        numberFormats.add(numFormatCopy);
1482528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        formattedNumber = formatByPattern(number, PhoneNumberFormat.NATIONAL, numberFormats);
1483d470984844c388d6766c3de6ac64e93e00480fc9Flavio Lerda        break;
148454923fc72f0faeb11fe58a545c0314f6051b14aaShaopeng Jia    }
1485d470984844c388d6766c3de6ac64e93e00480fc9Flavio Lerda    String rawInput = number.getRawInput();
1486d470984844c388d6766c3de6ac64e93e00480fc9Flavio Lerda    // If no digit is inserted/removed/modified as a result of our formatting, we return the
1487d470984844c388d6766c3de6ac64e93e00480fc9Flavio Lerda    // formatted phone number; otherwise we return the raw input the user entered.
1488203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    if (formattedNumber != null && rawInput.length() > 0) {
1489bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia      String normalizedFormattedNumber = normalizeDiallableCharsOnly(formattedNumber);
1490bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia      String normalizedRawInput = normalizeDiallableCharsOnly(rawInput);
1491203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia      if (!normalizedFormattedNumber.equals(normalizedRawInput)) {
1492203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia        formattedNumber = rawInput;
1493203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia      }
1494203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    }
1495203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    return formattedNumber;
149654923fc72f0faeb11fe58a545c0314f6051b14aaShaopeng Jia  }
149754923fc72f0faeb11fe58a545c0314f6051b14aaShaopeng Jia
1498528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia  // Check if rawInput, which is assumed to be in the national format, has a national prefix. The
1499528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia  // national prefix is assumed to be in digits-only form.
1500528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia  private boolean rawInputContainsNationalPrefix(String rawInput, String nationalPrefix,
1501528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia      String regionCode) {
1502528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    String normalizedNationalNumber = normalizeDigitsOnly(rawInput);
1503528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    if (normalizedNationalNumber.startsWith(nationalPrefix)) {
1504528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia      try {
1505528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        // Some Japanese numbers (e.g. 00777123) might be mistaken to contain the national prefix
1506528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        // when written without it (e.g. 0777123) if we just do prefix matching. To tackle that, we
1507528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        // check the validity of the number if the assumed national prefix is removed (777123 won't
1508528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        // be valid in Japan).
1509528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        return isValidNumber(
1510528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia            parse(normalizedNationalNumber.substring(nationalPrefix.length()), regionCode));
1511528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia      } catch (NumberParseException e) {
1512528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        return false;
1513528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia      }
1514528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    }
1515528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    return false;
1516528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia  }
1517528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia
1518528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia  /**
1519528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia   * Returns true if a number is from a region whose national significant number couldn't contain a
1520528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia   * leading zero, but has the italian_leading_zero field set to true.
1521528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia   */
1522528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia  private boolean hasUnexpectedItalianLeadingZero(PhoneNumber number) {
1523528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    return number.isItalianLeadingZero() && !isLeadingZeroPossible(number.getCountryCode());
1524528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia  }
1525528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia
15265cd062f9cba053c771bcea181fec210279ec030bShaopeng Jia  private boolean hasFormattingPatternForNumber(PhoneNumber number) {
1527528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    int countryCallingCode = number.getCountryCode();
1528528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    String phoneNumberRegion = getRegionCodeForCountryCode(countryCallingCode);
1529528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    PhoneMetadata metadata =
1530528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        getMetadataForRegionOrCallingCode(countryCallingCode, phoneNumberRegion);
15315cd062f9cba053c771bcea181fec210279ec030bShaopeng Jia    if (metadata == null) {
15325cd062f9cba053c771bcea181fec210279ec030bShaopeng Jia      return false;
15335cd062f9cba053c771bcea181fec210279ec030bShaopeng Jia    }
15345cd062f9cba053c771bcea181fec210279ec030bShaopeng Jia    String nationalNumber = getNationalSignificantNumber(number);
15355cd062f9cba053c771bcea181fec210279ec030bShaopeng Jia    NumberFormat formatRule =
153693399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller        chooseFormattingPatternForNumber(metadata.numberFormats(), nationalNumber);
15375cd062f9cba053c771bcea181fec210279ec030bShaopeng Jia    return formatRule != null;
15385cd062f9cba053c771bcea181fec210279ec030bShaopeng Jia  }
15395cd062f9cba053c771bcea181fec210279ec030bShaopeng Jia
15405c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia  /**
1541372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * Formats a phone number for out-of-country dialing purposes.
1542372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *
1543372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * Note that in this version, if the number was entered originally using alpha characters and
1544372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * this version of the number is stored in raw_input, this representation of the number will be
1545372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * used rather than the digit representation. Grouping information, as specified by characters
1546372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * such as "-" and " ", will be retained.
1547372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *
1548372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * <p><b>Caveats:</b></p>
1549372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * <ul>
1550372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *  <li> This will not produce good results if the country calling code is both present in the raw
1551372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *       input _and_ is the start of the national number. This is not a problem in the regions
1552372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *       which typically use alpha numbers.
1553372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *  <li> This will also not produce good results if the raw input has any grouping information
1554372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *       within the first three digits of the national number, and if the function needs to strip
1555372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *       preceding digits/words in the raw input before these digits. Normally people group the
1556372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *       first three digits together so this is not a huge problem - and will be fixed if it
1557372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *       proves to be so.
1558372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * </ul>
1559372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *
1560372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * @param number  the phone number that needs to be formatted
1561372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * @param regionCallingFrom  the region where the call is being placed
1562372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * @return  the formatted phone number
1563372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   */
1564d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia  public String formatOutOfCountryKeepingAlphaChars(PhoneNumber number,
1565d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia                                                    String regionCallingFrom) {
1566372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    String rawInput = number.getRawInput();
1567372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    // If there is no raw input, then we can't keep alpha characters because there aren't any.
1568372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    // In this case, we return formatOutOfCountryCallingNumber.
1569372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    if (rawInput.length() == 0) {
1570372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      return formatOutOfCountryCallingNumber(number, regionCallingFrom);
1571372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    }
1572372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    int countryCode = number.getCountryCode();
1573528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    if (!hasValidCountryCallingCode(countryCode)) {
1574372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      return rawInput;
1575372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    }
1576372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    // Strip any prefix such as country calling code, IDD, that was present. We do this by comparing
1577372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    // the number in raw_input with the parsed number.
1578372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    // To do this, first we normalize punctuation. We retain number grouping symbols such as " "
1579372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    // only.
1580372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    rawInput = normalizeHelper(rawInput, ALL_PLUS_NUMBER_GROUPING_SYMBOLS, true);
1581372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    // Now we trim everything before the first three digits in the parsed number. We choose three
1582372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    // because all valid alpha numbers have 3 digits at the start - if it does not, then we don't
1583372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    // trim anything at all. Similarly, if the national number was less than three digits, we don't
1584372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    // trim anything at all.
1585372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    String nationalNumber = getNationalSignificantNumber(number);
1586372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    if (nationalNumber.length() > 3) {
1587372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      int firstNationalNumberDigit = rawInput.indexOf(nationalNumber.substring(0, 3));
1588372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      if (firstNationalNumberDigit != -1) {
1589372bff8dd464574d36737d47e495cad14346653cShaopeng Jia        rawInput = rawInput.substring(firstNationalNumberDigit);
1590372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      }
1591372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    }
1592528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    PhoneMetadata metadataForRegionCallingFrom = getMetadataForRegion(regionCallingFrom);
1593372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    if (countryCode == NANPA_COUNTRY_CODE) {
1594372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      if (isNANPACountry(regionCallingFrom)) {
1595372bff8dd464574d36737d47e495cad14346653cShaopeng Jia        return countryCode + " " + rawInput;
1596372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      }
1597203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    } else if (metadataForRegionCallingFrom != null &&
1598cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia               countryCode == getCountryCodeForValidRegion(regionCallingFrom)) {
1599cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia      NumberFormat formattingPattern =
160093399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller          chooseFormattingPatternForNumber(metadataForRegionCallingFrom.numberFormats(),
1601cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia                                           nationalNumber);
1602cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia      if (formattingPattern == null) {
1603cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia        // If no pattern above is matched, we format the original input.
1604cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia        return rawInput;
1605372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      }
160693399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller      NumberFormat newFormat = new NumberFormat();
160793399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller      newFormat.mergeFrom(formattingPattern);
1608cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia      // The first group is the first group of digits that the user wrote together.
160993399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller      newFormat.setPattern("(\\d+)(.*)");
1610cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia      // Here we just concatenate them back together after the national prefix has been fixed.
161193399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller      newFormat.setFormat("$1$2");
1612cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia      // Now we format using this pattern instead of the default pattern, but with the national
1613cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia      // prefix prefixed if necessary.
1614372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      // This will not work in the cases where the pattern (and not the leading digits) decide
1615372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      // whether a national prefix needs to be used, since we have overridden the pattern to match
1616372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      // anything, but that is not the case in the metadata to date.
1617cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia      return formatNsnUsingPattern(rawInput, newFormat, PhoneNumberFormat.NATIONAL);
1618372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    }
1619528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    String internationalPrefixForFormatting = "";
1620528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    // If an unsupported region-calling-from is entered, or a country with multiple international
1621528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    // prefixes, the international format of the number is returned, unless there is a preferred
1622528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    // international prefix.
1623528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    if (metadataForRegionCallingFrom != null) {
162493399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller      String internationalPrefix = metadataForRegionCallingFrom.getInternationalPrefix();
1625528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia      internationalPrefixForFormatting =
1626528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia          UNIQUE_INTERNATIONAL_PREFIX.matcher(internationalPrefix).matches()
1627528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia          ? internationalPrefix
162893399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller          : metadataForRegionCallingFrom.getPreferredInternationalPrefix();
1629528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    }
1630372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    StringBuilder formattedNumber = new StringBuilder(rawInput);
1631528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    String regionCode = getRegionCodeForCountryCode(countryCode);
1632203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    // Metadata cannot be null because the country calling code is valid.
1633528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    PhoneMetadata metadataForRegion = getMetadataForRegionOrCallingCode(countryCode, regionCode);
1634cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia    maybeAppendFormattedExtension(number, metadataForRegion,
1635cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia                                  PhoneNumberFormat.INTERNATIONAL, formattedNumber);
1636372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    if (internationalPrefixForFormatting.length() > 0) {
1637372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      formattedNumber.insert(0, " ").insert(0, countryCode).insert(0, " ")
1638372bff8dd464574d36737d47e495cad14346653cShaopeng Jia          .insert(0, internationalPrefixForFormatting);
1639372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    } else {
1640528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia      // Invalid region entered as country-calling-from (so no metadata was found for it) or the
1641528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia      // region chosen has multiple international dialling prefixes.
164293399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller      logger.log(Level.WARNING,
164393399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller                 "Trying to format number from invalid region "
164493399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller                 + regionCallingFrom
164593399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller                 + ". International formatting applied.");
1646cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia      prefixNumberWithCountryCallingCode(countryCode,
1647b0e21c22b1ca6b9aeb1426924cdf42a221c3d416Shaopeng Jia                                         PhoneNumberFormat.INTERNATIONAL,
1648b0e21c22b1ca6b9aeb1426924cdf42a221c3d416Shaopeng Jia                                         formattedNumber);
1649372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    }
1650372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    return formattedNumber.toString();
1651372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  }
1652372bff8dd464574d36737d47e495cad14346653cShaopeng Jia
1653372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  /**
16545c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia   * Gets the national significant number of the a phone number. Note a national significant number
16555c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia   * doesn't contain a national prefix or any formatting.
16565c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia   *
1657d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   * @param number  the phone number for which the national significant number is needed
16585c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia   * @return  the national significant number of the PhoneNumber object passed in
16595c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia   */
1660372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  public String getNationalSignificantNumber(PhoneNumber number) {
1661f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia    // If leading zero(s) have been set, we prefix this now. Note this is not a national prefix.
1662f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia    StringBuilder nationalNumber = new StringBuilder();
1663f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia    if (number.isItalianLeadingZero()) {
1664f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia      char[] zeros = new char[number.getNumberOfLeadingZeros()];
1665f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia      Arrays.fill(zeros, '0');
1666f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia      nationalNumber.append(new String(zeros));
1667f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia    }
16681524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    nationalNumber.append(number.getNationalNumber());
16691524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    return nationalNumber.toString();
16701524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
16711524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
16721524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
16731524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * A helper function that is used by format and formatByPattern.
16741524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
1675cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia  private void prefixNumberWithCountryCallingCode(int countryCallingCode,
1676cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia                                                  PhoneNumberFormat numberFormat,
1677cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia                                                  StringBuilder formattedNumber) {
16781524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    switch (numberFormat) {
16791524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      case E164:
1680372bff8dd464574d36737d47e495cad14346653cShaopeng Jia        formattedNumber.insert(0, countryCallingCode).insert(0, PLUS_SIGN);
1681be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia        return;
16821524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      case INTERNATIONAL:
1683372bff8dd464574d36737d47e495cad14346653cShaopeng Jia        formattedNumber.insert(0, " ").insert(0, countryCallingCode).insert(0, PLUS_SIGN);
1684372bff8dd464574d36737d47e495cad14346653cShaopeng Jia        return;
1685372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      case RFC3966:
1686b0e21c22b1ca6b9aeb1426924cdf42a221c3d416Shaopeng Jia        formattedNumber.insert(0, "-").insert(0, countryCallingCode).insert(0, PLUS_SIGN)
1687b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia            .insert(0, RFC3966_PREFIX);
1688be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia        return;
16891524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      case NATIONAL:
16901524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      default:
1691be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia        return;
16921524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
16931524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
16941524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
1695cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia  // Simple wrapper of formatNsn for the common case of no carrier code.
1696cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia  private String formatNsn(String number, PhoneMetadata metadata, PhoneNumberFormat numberFormat) {
1697cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia    return formatNsn(number, metadata, numberFormat, null);
1698df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia  }
16994b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia
1700372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  // Note in some regions, the national number can be written in two completely different ways
17011524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  // depending on whether it forms part of the NATIONAL format or INTERNATIONAL format. The
17024b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia  // numberFormat parameter here is used to specify which format to use for those cases. If a
17034b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia  // carrierCode is specified, this will be inserted into the formatted string to replace $CC.
1704cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia  private String formatNsn(String number,
1705cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia                           PhoneMetadata metadata,
1706cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia                           PhoneNumberFormat numberFormat,
1707cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia                           String carrierCode) {
170893399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller    List<NumberFormat> intlNumberFormats = metadata.intlNumberFormats();
17091524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    // When the intlNumberFormats exists, we use that to format national number for the
17101524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    // INTERNATIONAL format instead of using the numberDesc.numberFormats.
171193399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller    List<NumberFormat> availableFormats =
171293399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller        (intlNumberFormats.size() == 0 || numberFormat == PhoneNumberFormat.NATIONAL)
171393399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller        ? metadata.numberFormats()
171493399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller        : metadata.intlNumberFormats();
1715cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia    NumberFormat formattingPattern = chooseFormattingPatternForNumber(availableFormats, number);
1716cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia    return (formattingPattern == null)
1717cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia        ? number
1718cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia        : formatNsnUsingPattern(number, formattingPattern, numberFormat, carrierCode);
17191524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
17201524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
172193399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller  NumberFormat chooseFormattingPatternForNumber(List<NumberFormat> availableFormats,
1722b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia                                                String nationalNumber) {
1723a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia    for (NumberFormat numFormat : availableFormats) {
172493399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller      int size = numFormat.leadingDigitsPatternSize();
1725a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia      if (size == 0 || regexCache.getPatternForRegex(
1726a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia              // We always use the last leading_digits_pattern, as it is the most detailed.
172793399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller              numFormat.getLeadingDigitsPattern(size - 1)).matcher(nationalNumber).lookingAt()) {
172893399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller        Matcher m = regexCache.getPatternForRegex(numFormat.getPattern()).matcher(nationalNumber);
1729a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia        if (m.matches()) {
1730a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia          return numFormat;
1731a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia        }
1732a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia      }
1733a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia    }
1734a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia    return null;
1735a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia  }
1736a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia
1737cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia  // Simple wrapper of formatNsnUsingPattern for the common case of no carrier code.
1738b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia  String formatNsnUsingPattern(String nationalNumber,
1739b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia                               NumberFormat formattingPattern,
1740b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia                               PhoneNumberFormat numberFormat) {
1741cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia    return formatNsnUsingPattern(nationalNumber, formattingPattern, numberFormat, null);
17424b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia  }
17434b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia
1744203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia  // Note that carrierCode is optional - if null or an empty string, no carrier code replacement
174552699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia  // will take place.
1746cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia  private String formatNsnUsingPattern(String nationalNumber,
1747cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia                                       NumberFormat formattingPattern,
1748cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia                                       PhoneNumberFormat numberFormat,
1749cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia                                       String carrierCode) {
175093399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller    String numberFormatRule = formattingPattern.getFormat();
1751cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia    Matcher m =
175293399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller        regexCache.getPatternForRegex(formattingPattern.getPattern()).matcher(nationalNumber);
1753cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia    String formattedNationalNumber = "";
1754a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia    if (numberFormat == PhoneNumberFormat.NATIONAL &&
1755a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia        carrierCode != null && carrierCode.length() > 0 &&
175693399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller        formattingPattern.getDomesticCarrierCodeFormattingRule().length() > 0) {
1757a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia      // Replace the $CC in the formatting rule with the desired carrier code.
175893399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller      String carrierCodeFormattingRule = formattingPattern.getDomesticCarrierCodeFormattingRule();
1759a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia      carrierCodeFormattingRule =
1760a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia          CC_PATTERN.matcher(carrierCodeFormattingRule).replaceFirst(carrierCode);
1761a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia      // Now replace the $FG in the formatting rule with the first group and the carrier code
1762a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia      // combined in the appropriate way.
1763a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia      numberFormatRule = FIRST_GROUP_PATTERN.matcher(numberFormatRule)
1764a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia          .replaceFirst(carrierCodeFormattingRule);
1765cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia      formattedNationalNumber = m.replaceAll(numberFormatRule);
1766a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia    } else {
1767a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia      // Use the national prefix formatting rule instead.
176893399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller      String nationalPrefixFormattingRule = formattingPattern.getNationalPrefixFormattingRule();
1769a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia      if (numberFormat == PhoneNumberFormat.NATIONAL &&
1770a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia          nationalPrefixFormattingRule != null &&
1771a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia          nationalPrefixFormattingRule.length() > 0) {
1772a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia        Matcher firstGroupMatcher = FIRST_GROUP_PATTERN.matcher(numberFormatRule);
1773cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia        formattedNationalNumber =
1774cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia            m.replaceAll(firstGroupMatcher.replaceFirst(nationalPrefixFormattingRule));
1775a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia      } else {
1776cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia        formattedNationalNumber = m.replaceAll(numberFormatRule);
17771524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      }
17781524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
1779cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia    if (numberFormat == PhoneNumberFormat.RFC3966) {
1780cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia      // Strip any leading punctuation.
1781cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia      Matcher matcher = SEPARATOR_PATTERN.matcher(formattedNationalNumber);
1782cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia      if (matcher.lookingAt()) {
1783cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia        formattedNationalNumber = matcher.replaceFirst("");
1784cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia      }
1785cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia      // Replace the rest with a dash between each number group.
1786cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia      formattedNationalNumber = matcher.reset(formattedNationalNumber).replaceAll("-");
1787cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia    }
1788cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia    return formattedNationalNumber;
17891524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
17901524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
17911524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
1792372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * Gets a valid number for the specified region.
17931524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *
1794d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   * @param regionCode  the region for which an example number is needed
1795372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * @return  a valid fixed-line number for the specified region. Returns null when the metadata
1796528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia   *    does not contain such information, or the region 001 is passed in. For 001 (representing
1797528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia   *    non-geographical numbers), call {@link #getExampleNumberForNonGeoEntity} instead.
17981524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
17991524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  public PhoneNumber getExampleNumber(String regionCode) {
18001524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    return getExampleNumberForType(regionCode, PhoneNumberType.FIXED_LINE);
18011524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
18021524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
18031524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
1804372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * Gets a valid number for the specified region and number type.
18051524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *
1806d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   * @param regionCode  the region for which an example number is needed
18071524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @param type  the type of number that is needed
1808372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * @return  a valid number for the specified region and type. Returns null when the metadata
1809528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia   *     does not contain such information or if an invalid region or region 001 was entered.
1810528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia   *     For 001 (representing non-geographical numbers), call
1811528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia   *     {@link #getExampleNumberForNonGeoEntity} instead.
18121524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
18131524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  public PhoneNumber getExampleNumberForType(String regionCode, PhoneNumberType type) {
1814372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    // Check the region code is valid.
1815372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    if (!isValidRegionCode(regionCode)) {
1816bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia      logger.log(Level.WARNING, "Invalid or unknown region code provided: " + regionCode);
1817372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      return null;
1818372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    }
18191524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    PhoneNumberDesc desc = getNumberDescByType(getMetadataForRegion(regionCode), type);
18201524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    try {
182193399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller      if (desc.hasExampleNumber()) {
182293399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller        return parse(desc.getExampleNumber(), regionCode);
18231524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      }
18241524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    } catch (NumberParseException e) {
1825bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia      logger.log(Level.SEVERE, e.toString());
18261524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
18271524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    return null;
18281524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
18291524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
18301524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
1831528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia   * Gets a valid number for the specified country calling code for a non-geographical entity.
1832528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia   *
1833528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia   * @param countryCallingCode  the country calling code for a non-geographical entity
1834528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia   * @return  a valid number for the non-geographical entity. Returns null when the metadata
1835528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia   *    does not contain such information, or the country calling code passed in does not belong
1836528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia   *    to a non-geographical entity.
1837528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia   */
1838528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia  public PhoneNumber getExampleNumberForNonGeoEntity(int countryCallingCode) {
1839528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    PhoneMetadata metadata = getMetadataForNonGeographicalRegion(countryCallingCode);
1840528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    if (metadata != null) {
184193399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller      PhoneNumberDesc desc = metadata.getGeneralDesc();
1842528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia      try {
184393399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller        if (desc.hasExampleNumber()) {
184493399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller          return parse("+" + countryCallingCode + desc.getExampleNumber(), "ZZ");
1845528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        }
1846528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia      } catch (NumberParseException e) {
1847bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia        logger.log(Level.SEVERE, e.toString());
1848528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia      }
1849cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia    } else {
1850bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia      logger.log(Level.WARNING,
1851cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia                 "Invalid or unknown country calling code provided: " + countryCallingCode);
1852528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    }
1853528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    return null;
1854528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia  }
1855528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia
1856528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia  /**
1857be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia   * Appends the formatted extension of a phone number to formattedNumber, if the phone number had
1858be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia   * an extension specified.
18591524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
1860cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia  private void maybeAppendFormattedExtension(PhoneNumber number, PhoneMetadata metadata,
1861cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia                                             PhoneNumberFormat numberFormat,
1862cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia                                             StringBuilder formattedNumber) {
1863372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    if (number.hasExtension() && number.getExtension().length() > 0) {
1864372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      if (numberFormat == PhoneNumberFormat.RFC3966) {
1865372bff8dd464574d36737d47e495cad14346653cShaopeng Jia        formattedNumber.append(RFC3966_EXTN_PREFIX).append(number.getExtension());
1866be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia      } else {
186793399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller        if (metadata.hasPreferredExtnPrefix()) {
186893399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller          formattedNumber.append(metadata.getPreferredExtnPrefix()).append(number.getExtension());
1869cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia        } else {
1870cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia          formattedNumber.append(DEFAULT_EXTN_PREFIX).append(number.getExtension());
1871cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia        }
1872be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia      }
1873372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    }
1874372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  }
1875372bff8dd464574d36737d47e495cad14346653cShaopeng Jia
18761524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  PhoneNumberDesc getNumberDescByType(PhoneMetadata metadata, PhoneNumberType type) {
18771524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    switch (type) {
18781524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      case PREMIUM_RATE:
187993399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller        return metadata.getPremiumRate();
18801524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      case TOLL_FREE:
188193399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller        return metadata.getTollFree();
18821524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      case MOBILE:
188393399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller        return metadata.getMobile();
18841524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      case FIXED_LINE:
18851524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      case FIXED_LINE_OR_MOBILE:
188693399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller        return metadata.getFixedLine();
18871524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      case SHARED_COST:
188893399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller        return metadata.getSharedCost();
18891524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      case VOIP:
189093399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller        return metadata.getVoip();
18911524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      case PERSONAL_NUMBER:
189293399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller        return metadata.getPersonalNumber();
1893b2697412130f6d087dde01fb1a978f7e5840a5faShaopeng Jia      case PAGER:
189493399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller        return metadata.getPager();
189574aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia      case UAN:
189693399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller        return metadata.getUan();
1897528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia      case VOICEMAIL:
189893399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller        return metadata.getVoicemail();
18991524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      default:
190093399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller        return metadata.getGeneralDesc();
19011524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
19021524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
19031524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
19041524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
19051524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * Gets the type of a phone number.
19061524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *
19071524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @param number  the phone number that we want to know the type
19081524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @return  the type of the phone number
19091524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
19101524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  public PhoneNumberType getNumberType(PhoneNumber number) {
19111524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    String regionCode = getRegionCodeForNumber(number);
1912203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    PhoneMetadata metadata = getMetadataForRegionOrCallingCode(number.getCountryCode(), regionCode);
1913203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    if (metadata == null) {
19141524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      return PhoneNumberType.UNKNOWN;
19151524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
1916be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    String nationalSignificantNumber = getNationalSignificantNumber(number);
1917528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    return getNumberTypeHelper(nationalSignificantNumber, metadata);
19181524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
19191524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
19201524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  private PhoneNumberType getNumberTypeHelper(String nationalNumber, PhoneMetadata metadata) {
192193399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller    if (!isNumberMatchingDesc(nationalNumber, metadata.getGeneralDesc())) {
19221524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      return PhoneNumberType.UNKNOWN;
19231524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
19241524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
192593399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller    if (isNumberMatchingDesc(nationalNumber, metadata.getPremiumRate())) {
19261524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      return PhoneNumberType.PREMIUM_RATE;
19271524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
192893399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller    if (isNumberMatchingDesc(nationalNumber, metadata.getTollFree())) {
19291524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      return PhoneNumberType.TOLL_FREE;
19301524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
193193399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller    if (isNumberMatchingDesc(nationalNumber, metadata.getSharedCost())) {
19321524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      return PhoneNumberType.SHARED_COST;
19331524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
193493399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller    if (isNumberMatchingDesc(nationalNumber, metadata.getVoip())) {
19351524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      return PhoneNumberType.VOIP;
19361524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
193793399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller    if (isNumberMatchingDesc(nationalNumber, metadata.getPersonalNumber())) {
19381524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      return PhoneNumberType.PERSONAL_NUMBER;
19391524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
194093399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller    if (isNumberMatchingDesc(nationalNumber, metadata.getPager())) {
1941b2697412130f6d087dde01fb1a978f7e5840a5faShaopeng Jia      return PhoneNumberType.PAGER;
1942b2697412130f6d087dde01fb1a978f7e5840a5faShaopeng Jia    }
194393399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller    if (isNumberMatchingDesc(nationalNumber, metadata.getUan())) {
194474aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia      return PhoneNumberType.UAN;
194574aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia    }
194693399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller    if (isNumberMatchingDesc(nationalNumber, metadata.getVoicemail())) {
1947528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia      return PhoneNumberType.VOICEMAIL;
1948528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    }
19491524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
195093399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller    boolean isFixedLine = isNumberMatchingDesc(nationalNumber, metadata.getFixedLine());
19511524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    if (isFixedLine) {
195293399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller      if (metadata.isSameMobileAndFixedLinePattern()) {
19531524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia        return PhoneNumberType.FIXED_LINE_OR_MOBILE;
195493399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller      } else if (isNumberMatchingDesc(nationalNumber, metadata.getMobile())) {
19551524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia        return PhoneNumberType.FIXED_LINE_OR_MOBILE;
19561524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      }
19571524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      return PhoneNumberType.FIXED_LINE;
19581524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
19591524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    // Otherwise, test to see if the number is mobile. Only do this if certain that the patterns for
19601524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    // mobile and fixed line aren't the same.
196193399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller    if (!metadata.isSameMobileAndFixedLinePattern() &&
196293399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller        isNumberMatchingDesc(nationalNumber, metadata.getMobile())) {
19631524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      return PhoneNumberType.MOBILE;
19641524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
19651524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    return PhoneNumberType.UNKNOWN;
19661524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
19671524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
1968203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia  /**
1969203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia   * Returns the metadata for the given region code or {@code null} if the region code is invalid
1970203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia   * or unknown.
1971203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia   */
19721524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  PhoneMetadata getMetadataForRegion(String regionCode) {
1973fa42140081949568565af7dc8c22f0600ad90a8aShaopeng Jia    if (!isValidRegionCode(regionCode)) {
19741524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      return null;
19751524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
1976279df210d5a4215ee2273bd23d29de5dc29e8370Neil Fuller    return metadataSource.getMetadataForRegion(regionCode);
19771524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
19781524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
1979528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia  PhoneMetadata getMetadataForNonGeographicalRegion(int countryCallingCode) {
1980279df210d5a4215ee2273bd23d29de5dc29e8370Neil Fuller    if (!countryCallingCodeToRegionCodeMap.containsKey(countryCallingCode)) {
1981279df210d5a4215ee2273bd23d29de5dc29e8370Neil Fuller      return null;
1982528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    }
1983279df210d5a4215ee2273bd23d29de5dc29e8370Neil Fuller    return metadataSource.getMetadataForNonGeographicalRegion(countryCallingCode);
1984528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia  }
1985528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia
1986bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia  boolean isNumberPossibleForDesc(String nationalNumber, PhoneNumberDesc numberDesc) {
1987be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    Matcher possibleNumberPatternMatcher =
198893399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller        regexCache.getPatternForRegex(numberDesc.getPossibleNumberPattern())
1989be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia            .matcher(nationalNumber);
1990bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia    return possibleNumberPatternMatcher.matches();
1991bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia  }
1992bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia
1993bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia  boolean isNumberMatchingDesc(String nationalNumber, PhoneNumberDesc numberDesc) {
1994be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    Matcher nationalNumberPatternMatcher =
199593399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller        regexCache.getPatternForRegex(numberDesc.getNationalNumberPattern())
1996be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia            .matcher(nationalNumber);
1997bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia    return isNumberPossibleForDesc(nationalNumber, numberDesc) &&
1998bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia        nationalNumberPatternMatcher.matches();
19991524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
20001524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
20011524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
20021524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * Tests whether a phone number matches a valid pattern. Note this doesn't verify the number
20031524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * is actually in use, which is impossible to tell by just looking at a number itself.
20041524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *
20051524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @param number       the phone number that we want to validate
20061524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @return  a boolean that indicates whether the number is of a valid pattern
20071524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
20081524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  public boolean isValidNumber(PhoneNumber number) {
20091524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    String regionCode = getRegionCodeForNumber(number);
2010528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    return isValidNumberForRegion(number, regionCode);
20111524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
20121524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
20131524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
20141524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * Tests whether a phone number is valid for a certain region. Note this doesn't verify the number
20151524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * is actually in use, which is impossible to tell by just looking at a number itself. If the
2016372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * country calling code is not the same as the country calling code for the region, this
2017372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * immediately exits with false. After this, the specific number pattern rules for the region are
2018372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * examined. This is useful for determining for example whether a particular number is valid for
2019372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * Canada, rather than just a valid NANPA number.
2020203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia   * Warning: In most cases, you want to use {@link #isValidNumber} instead. For example, this
2021203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia   * method will mark numbers from British Crown dependencies such as the Isle of Man as invalid for
2022203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia   * the region "GB" (United Kingdom), since it has its own region code, "IM", which may be
2023203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia   * undesirable.
20241524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *
20251524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @param number       the phone number that we want to validate
2026d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   * @param regionCode   the region that we want to validate the phone number for
20271524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @return  a boolean that indicates whether the number is of a valid pattern
20281524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
20291524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  public boolean isValidNumberForRegion(PhoneNumber number, String regionCode) {
2030528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    int countryCode = number.getCountryCode();
2031cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia    PhoneMetadata metadata = getMetadataForRegionOrCallingCode(countryCode, regionCode);
2032cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia    if ((metadata == null) ||
2033528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        (!REGION_CODE_FOR_NON_GEO_ENTITY.equals(regionCode) &&
2034cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia         countryCode != getCountryCodeForValidRegion(regionCode))) {
2035cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia      // Either the region code was invalid, or the country calling code for this number does not
2036cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia      // match that of the region code.
20371524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      return false;
20381524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
20395c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia    String nationalSignificantNumber = getNationalSignificantNumber(number);
204009104d6c45e3cfae9264367232dd17890e0e8675Shaopeng Jia    return getNumberTypeHelper(nationalSignificantNumber, metadata) != PhoneNumberType.UNKNOWN;
20411524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
20421524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
20431524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
2044372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * Returns the region where a phone number is from. This could be used for geocoding at the region
2045372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * level.
20461524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *
20471524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @param number  the phone number whose origin we want to know
2048372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * @return  the region where the phone number is from, or null if no region matches this calling
2049372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *     code
20501524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
20511524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  public String getRegionCodeForNumber(PhoneNumber number) {
20521524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    int countryCode = number.getCountryCode();
2053372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    List<String> regions = countryCallingCodeToRegionCodeMap.get(countryCode);
20544b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia    if (regions == null) {
2055528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia      String numberString = getNationalSignificantNumber(number);
2056279df210d5a4215ee2273bd23d29de5dc29e8370Neil Fuller      logger.log(Level.INFO,
2057528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia                 "Missing/invalid country_code (" + countryCode + ") for number " + numberString);
20584b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia      return null;
20594b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia    }
20604b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia    if (regions.size() == 1) {
20614b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia      return regions.get(0);
20624b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia    } else {
20634b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia      return getRegionCodeForNumberFromRegionList(number, regions);
20641524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
20651524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
20661524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
20671524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  private String getRegionCodeForNumberFromRegionList(PhoneNumber number,
20684b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia                                                      List<String> regionCodes) {
2069372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    String nationalNumber = getNationalSignificantNumber(number);
20701524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    for (String regionCode : regionCodes) {
20714b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia      // If leadingDigits is present, use this. Otherwise, do full validation.
2072203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia      // Metadata cannot be null because the region codes come from the country calling code map.
20734b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia      PhoneMetadata metadata = getMetadataForRegion(regionCode);
207493399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller      if (metadata.hasLeadingDigits()) {
207593399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller        if (regexCache.getPatternForRegex(metadata.getLeadingDigits())
20764b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia                .matcher(nationalNumber).lookingAt()) {
20774b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia          return regionCode;
20784b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia        }
20794b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia      } else if (getNumberTypeHelper(nationalNumber, metadata) != PhoneNumberType.UNKNOWN) {
20801524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia        return regionCode;
20811524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      }
20821524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
20831524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    return null;
20841524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
20851524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
20861524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
2087372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * Returns the region code that matches the specific country calling code. In the case of no
2088372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * region code being found, ZZ will be returned. In the case of multiple regions, the one
2089f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia   * designated in the metadata as the "main" region for this calling code will be returned. If the
2090f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia   * countryCallingCode entered is valid but doesn't match a specific region (such as in the case of
2091f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia   * non-geographical calling codes like 800) the value "001" will be returned (corresponding to
2092f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia   * the value for World in the UN M.49 schema).
20931524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
2094372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  public String getRegionCodeForCountryCode(int countryCallingCode) {
2095372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    List<String> regionCodes = countryCallingCodeToRegionCodeMap.get(countryCallingCode);
209674aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia    return regionCodes == null ? UNKNOWN_REGION : regionCodes.get(0);
20971524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
20981524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
20991524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
2100203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia   * Returns a list with the region codes that match the specific country calling code. For
2101203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia   * non-geographical country calling codes, the region code 001 is returned. Also, in the case
2102203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia   * of no region code being found, an empty list is returned.
2103203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia   */
2104203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia  public List<String> getRegionCodesForCountryCode(int countryCallingCode) {
2105203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    List<String> regionCodes = countryCallingCodeToRegionCodeMap.get(countryCallingCode);
2106203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    return Collections.unmodifiableList(regionCodes == null ? new ArrayList<String>(0)
2107203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia                                                            : regionCodes);
2108203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia  }
2109203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia
2110203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia  /**
21111524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * Returns the country calling code for a specific region. For example, this would be 1 for the
21121524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * United States, and 64 for New Zealand.
21131524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *
2114d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   * @param regionCode  the region that we want to get the country calling code for
2115372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * @return  the country calling code for the region denoted by regionCode
21161524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
21171524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  public int getCountryCodeForRegion(String regionCode) {
2118be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    if (!isValidRegionCode(regionCode)) {
2119bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia      logger.log(Level.WARNING,
2120528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia                 "Invalid or missing region code ("
2121528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia                  + ((regionCode == null) ? "null" : regionCode)
2122528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia                  + ") provided.");
21231524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      return 0;
21241524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
2125cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia    return getCountryCodeForValidRegion(regionCode);
2126cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia  }
2127cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia
2128cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia  /**
2129cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia   * Returns the country calling code for a specific region. For example, this would be 1 for the
2130cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia   * United States, and 64 for New Zealand. Assumes the region is already valid.
2131cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia   *
2132cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia   * @param regionCode  the region that we want to get the country calling code for
2133cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia   * @return  the country calling code for the region denoted by regionCode
2134203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia   * @throws IllegalArgumentException if the region is invalid
2135cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia   */
2136cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia  private int getCountryCodeForValidRegion(String regionCode) {
2137be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    PhoneMetadata metadata = getMetadataForRegion(regionCode);
2138203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    if (metadata == null) {
2139203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia      throw new IllegalArgumentException("Invalid region code: " + regionCode);
2140203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    }
214193399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller    return metadata.getCountryCode();
21421524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
21431524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
21441524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
2145f59ccfca9dd02c4e3cf3e06b5cf184a8d0e67626Shaopeng Jia   * Returns the national dialling prefix for a specific region. For example, this would be 1 for
2146f59ccfca9dd02c4e3cf3e06b5cf184a8d0e67626Shaopeng Jia   * the United States, and 0 for New Zealand. Set stripNonDigits to true to strip symbols like "~"
2147f59ccfca9dd02c4e3cf3e06b5cf184a8d0e67626Shaopeng Jia   * (which indicates a wait for a dialling tone) from the prefix returned. If no national prefix is
2148f59ccfca9dd02c4e3cf3e06b5cf184a8d0e67626Shaopeng Jia   * present, we return null.
2149f59ccfca9dd02c4e3cf3e06b5cf184a8d0e67626Shaopeng Jia   *
2150372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * <p>Warning: Do not use this method for do-your-own formatting - for some regions, the
2151372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * national dialling prefix is used only for certain types of numbers. Use the library's
2152372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * formatting functions to prefix the national prefix when required.
2153f59ccfca9dd02c4e3cf3e06b5cf184a8d0e67626Shaopeng Jia   *
2154d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   * @param regionCode  the region that we want to get the dialling prefix for
2155f59ccfca9dd02c4e3cf3e06b5cf184a8d0e67626Shaopeng Jia   * @param stripNonDigits  true to strip non-digits from the national dialling prefix
2156372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * @return  the dialling prefix for the region denoted by regionCode
2157f59ccfca9dd02c4e3cf3e06b5cf184a8d0e67626Shaopeng Jia   */
2158f59ccfca9dd02c4e3cf3e06b5cf184a8d0e67626Shaopeng Jia  public String getNddPrefixForRegion(String regionCode, boolean stripNonDigits) {
2159203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    PhoneMetadata metadata = getMetadataForRegion(regionCode);
2160203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    if (metadata == null) {
2161bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia      logger.log(Level.WARNING,
2162528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia                 "Invalid or missing region code ("
2163528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia                  + ((regionCode == null) ? "null" : regionCode)
2164528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia                  + ") provided.");
2165f59ccfca9dd02c4e3cf3e06b5cf184a8d0e67626Shaopeng Jia      return null;
2166f59ccfca9dd02c4e3cf3e06b5cf184a8d0e67626Shaopeng Jia    }
216793399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller    String nationalPrefix = metadata.getNationalPrefix();
2168f59ccfca9dd02c4e3cf3e06b5cf184a8d0e67626Shaopeng Jia    // If no national prefix was found, we return null.
2169f59ccfca9dd02c4e3cf3e06b5cf184a8d0e67626Shaopeng Jia    if (nationalPrefix.length() == 0) {
2170f59ccfca9dd02c4e3cf3e06b5cf184a8d0e67626Shaopeng Jia      return null;
2171f59ccfca9dd02c4e3cf3e06b5cf184a8d0e67626Shaopeng Jia    }
2172f59ccfca9dd02c4e3cf3e06b5cf184a8d0e67626Shaopeng Jia    if (stripNonDigits) {
2173f59ccfca9dd02c4e3cf3e06b5cf184a8d0e67626Shaopeng Jia      // Note: if any other non-numeric symbols are ever used in national prefixes, these would have
2174f59ccfca9dd02c4e3cf3e06b5cf184a8d0e67626Shaopeng Jia      // to be removed here as well.
2175f59ccfca9dd02c4e3cf3e06b5cf184a8d0e67626Shaopeng Jia      nationalPrefix = nationalPrefix.replace("~", "");
2176f59ccfca9dd02c4e3cf3e06b5cf184a8d0e67626Shaopeng Jia    }
2177f59ccfca9dd02c4e3cf3e06b5cf184a8d0e67626Shaopeng Jia    return nationalPrefix;
2178f59ccfca9dd02c4e3cf3e06b5cf184a8d0e67626Shaopeng Jia  }
2179f59ccfca9dd02c4e3cf3e06b5cf184a8d0e67626Shaopeng Jia
2180f59ccfca9dd02c4e3cf3e06b5cf184a8d0e67626Shaopeng Jia  /**
2181372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * Checks if this is a region under the North American Numbering Plan Administration (NANPA).
21821524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *
2183372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * @return  true if regionCode is one of the regions under NANPA
21841524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
21857900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia  public boolean isNANPACountry(String regionCode) {
2186f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia    return nanpaRegions.contains(regionCode);
2187372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  }
2188372bff8dd464574d36737d47e495cad14346653cShaopeng Jia
2189372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  /**
21909651f4d6f2740017c0c4ea9c1c340af6f644d609Shaopeng Jia   * Checks whether the country calling code is from a region whose national significant number
21919651f4d6f2740017c0c4ea9c1c340af6f644d609Shaopeng Jia   * could contain a leading zero. An example of such a region is Italy. Returns false if no
21929651f4d6f2740017c0c4ea9c1c340af6f644d609Shaopeng Jia   * metadata for the country is found.
2193372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   */
2194f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia  boolean isLeadingZeroPossible(int countryCallingCode) {
2195203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    PhoneMetadata mainMetadataForCallingCode =
2196203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia        getMetadataForRegionOrCallingCode(countryCallingCode,
2197203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia                                          getRegionCodeForCountryCode(countryCallingCode));
2198372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    if (mainMetadataForCallingCode == null) {
2199372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      return false;
2200372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    }
220193399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller    return mainMetadataForCallingCode.isLeadingZeroPossible();
22021524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
22031524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
22041524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
2205372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * Checks if the number is a valid vanity (alpha) number such as 800 MICROSOFT. A valid vanity
2206372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * number will start with at least 3 digits and will have three or more alpha characters. This
2207372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * does not do region-specific checks - to work out if this number is actually valid for a region,
2208372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * it should be parsed and methods such as {@link #isPossibleNumberWithReason} and
2209372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * {@link #isValidNumber} should be used.
2210372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *
2211372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * @param number  the number that needs to be checked
2212372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * @return  true if the number is a valid vanity number
2213f59ccfca9dd02c4e3cf3e06b5cf184a8d0e67626Shaopeng Jia   */
2214372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  public boolean isAlphaNumber(String number) {
2215372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    if (!isViablePhoneNumber(number)) {
2216372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      // Number is too short, or doesn't match the basic phone number pattern.
2217372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      return false;
2218372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    }
2219372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    StringBuilder strippedNumber = new StringBuilder(number);
2220372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    maybeStripExtension(strippedNumber);
2221372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    return VALID_ALPHA_PHONE_PATTERN.matcher(strippedNumber).matches();
2222f59ccfca9dd02c4e3cf3e06b5cf184a8d0e67626Shaopeng Jia  }
2223f59ccfca9dd02c4e3cf3e06b5cf184a8d0e67626Shaopeng Jia
2224f59ccfca9dd02c4e3cf3e06b5cf184a8d0e67626Shaopeng Jia  /**
2225372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * Convenience wrapper around {@link #isPossibleNumberWithReason}. Instead of returning the reason
2226372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * for failure, this method returns a boolean value.
22271524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @param number  the number that needs to be checked
22281524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @return  true if the number is possible
22291524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
22301524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  public boolean isPossibleNumber(PhoneNumber number) {
22311524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    return isPossibleNumberWithReason(number) == ValidationResult.IS_POSSIBLE;
22321524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
22331524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
22341524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
2235372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * Helper method to check a number against a particular pattern and determine whether it matches,
2236372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * or is too short or too long. Currently, if a number pattern suggests that numbers of length 7
2237372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * and 10 are possible, and a number in between these possible lengths is entered, such as of
2238372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * length 8, this will return TOO_LONG.
2239372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   */
2240372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  private ValidationResult testNumberLengthAgainstPattern(Pattern numberPattern, String number) {
2241372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    Matcher numberMatcher = numberPattern.matcher(number);
2242372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    if (numberMatcher.matches()) {
2243372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      return ValidationResult.IS_POSSIBLE;
2244372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    }
2245372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    if (numberMatcher.lookingAt()) {
2246372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      return ValidationResult.TOO_LONG;
2247372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    } else {
2248372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      return ValidationResult.TOO_SHORT;
2249372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    }
2250372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  }
2251372bff8dd464574d36737d47e495cad14346653cShaopeng Jia
2252372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  /**
2253f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia   * Helper method to check whether a number is too short to be a regular length phone number in a
2254f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia   * region.
2255f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia   */
2256f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia  private boolean isShorterThanPossibleNormalNumber(PhoneMetadata regionMetadata, String number) {
2257f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia    Pattern possibleNumberPattern = regexCache.getPatternForRegex(
225893399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller        regionMetadata.getGeneralDesc().getPossibleNumberPattern());
2259f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia    return testNumberLengthAgainstPattern(possibleNumberPattern, number) ==
2260f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia        ValidationResult.TOO_SHORT;
2261f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia  }
2262f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia
2263f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia  /**
22641524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * Check whether a phone number is a possible number. It provides a more lenient check than
2265372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * {@link #isValidNumber} in the following sense:
2266372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *<ol>
2267372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * <li> It only checks the length of phone numbers. In particular, it doesn't check starting
22681524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *      digits of the number.
2269372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * <li> It doesn't attempt to figure out the type of the number, but uses general rules which
2270372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *      applies to all types of phone numbers in a region. Therefore, it is much faster than
22711524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *      isValidNumber.
2272372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * <li> For fixed line numbers, many regions have the concept of area code, which together with
22731524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *      subscriber number constitute the national significant number. It is sometimes okay to dial
22741524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *      the subscriber number only when dialing in the same area. This function will return
22751524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *      true if the subscriber-number-only version is passed in. On the other hand, because
22761524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *      isValidNumber validates using information on both starting digits (for fixed line
22771524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *      numbers, that would most likely be area codes) and length (obviously includes the
22781524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *      length of area codes for fixed line numbers), it will return false for the
22791524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *      subscriber-number-only version.
2280203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia   * </ol>
22811524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @param number  the number that needs to be checked
22821524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @return  a ValidationResult object which indicates whether the number is possible
22831524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
22841524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  public ValidationResult isPossibleNumberWithReason(PhoneNumber number) {
2285372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    String nationalNumber = getNationalSignificantNumber(number);
22861524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    int countryCode = number.getCountryCode();
22871524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    // Note: For Russian Fed and NANPA numbers, we just use the rules from the default region (US or
22881524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    // Russia) since the getRegionCodeForNumber will not work if the number is possible but not
22891524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    // valid. This would need to be revisited if the possible number pattern ever differed between
2290372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    // various regions within those plans.
2291528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    if (!hasValidCountryCallingCode(countryCode)) {
22921524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      return ValidationResult.INVALID_COUNTRY_CODE;
22931524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
2294528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    String regionCode = getRegionCodeForCountryCode(countryCode);
2295203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    // Metadata cannot be null because the country calling code is valid.
2296528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    PhoneMetadata metadata = getMetadataForRegionOrCallingCode(countryCode, regionCode);
2297372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    Pattern possibleNumberPattern =
229893399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller        regexCache.getPatternForRegex(metadata.getGeneralDesc().getPossibleNumberPattern());
2299372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    return testNumberLengthAgainstPattern(possibleNumberPattern, nationalNumber);
23001524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
23011524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
23021524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
23031524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * Check whether a phone number is a possible number given a number in the form of a string, and
2304372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * the region where the number could be dialed from. It provides a more lenient check than
230596a7214cdabf08f53f5b1a560304601c9f65e0b9Shaopeng Jia   * {@link #isValidNumber}. See {@link #isPossibleNumber(PhoneNumber)} for details.
23061524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *
230796a7214cdabf08f53f5b1a560304601c9f65e0b9Shaopeng Jia   * <p>This method first parses the number, then invokes {@link #isPossibleNumber(PhoneNumber)}
230896a7214cdabf08f53f5b1a560304601c9f65e0b9Shaopeng Jia   * with the resultant PhoneNumber object.
23091524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *
23101524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @param number  the number that needs to be checked, in the form of a string
2311d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   * @param regionDialingFrom  the region that we are expecting the number to be dialed from.
2312372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *     Note this is different from the region where the number belongs.  For example, the number
2313372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *     +1 650 253 0000 is a number that belongs to US. When written in this form, it can be
2314372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *     dialed from any region. When it is written as 00 1 650 253 0000, it can be dialed from any
2315372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *     region which uses an international dialling prefix of 00. When it is written as
2316372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *     650 253 0000, it can only be dialed from within the US, and when written as 253 0000, it
2317372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *     can only be dialed from within a smaller area in the US (Mountain View, CA, to be more
231874aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia   *     specific).
23191524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @return  true if the number is possible
23201524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
2321372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  public boolean isPossibleNumber(String number, String regionDialingFrom) {
23221524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    try {
2323372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      return isPossibleNumber(parse(number, regionDialingFrom));
23241524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    } catch (NumberParseException e) {
23251524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      return false;
23261524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
23271524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
23281524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
23291524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
2330df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia   * Attempts to extract a valid number from a phone number that is too long to be valid, and resets
2331df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia   * the PhoneNumber object passed in to that valid version. If no valid number could be extracted,
2332df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia   * the PhoneNumber object passed in will not be modified.
2333df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia   * @param number a PhoneNumber object which contains a number that is too long to be valid.
2334df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia   * @return  true if a valid phone number can be successfully extracted.
2335df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia   */
2336df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia  public boolean truncateTooLongNumber(PhoneNumber number) {
2337df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia    if (isValidNumber(number)) {
2338df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia      return true;
2339df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia    }
2340df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia    PhoneNumber numberCopy = new PhoneNumber();
2341df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia    numberCopy.mergeFrom(number);
2342df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia    long nationalNumber = number.getNationalNumber();
2343df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia    do {
2344df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia      nationalNumber /= 10;
2345df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia      numberCopy.setNationalNumber(nationalNumber);
2346df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia      if (isPossibleNumberWithReason(numberCopy) == ValidationResult.TOO_SHORT ||
2347df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia          nationalNumber == 0) {
2348df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia        return false;
2349df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia      }
2350df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia    } while (!isValidNumber(numberCopy));
2351df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia    number.setNationalNumber(nationalNumber);
2352df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia    return true;
2353df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia  }
2354df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia
2355df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia  /**
2356a77faddfc3b3e4cca8f585c82d669054aec221f4Narayan Kamath   * Gets an {@link com.google.i18n.phonenumbers.AsYouTypeFormatter} for the specific region.
23571524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *
2358d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   * @param regionCode  the region where the phone number is being entered
2359a77faddfc3b3e4cca8f585c82d669054aec221f4Narayan Kamath   * @return  an {@link com.google.i18n.phonenumbers.AsYouTypeFormatter} object, which can be used
2360372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *     to format phone numbers in the specific region "as you type"
23611524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
23621524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  public AsYouTypeFormatter getAsYouTypeFormatter(String regionCode) {
23631524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    return new AsYouTypeFormatter(regionCode);
23641524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
23651524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
2366372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  // Extracts country calling code from fullNumber, returns it and places the remaining number in
23671524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  // nationalNumber. It assumes that the leading plus sign or IDD has already been removed. Returns
2368372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  // 0 if fullNumber doesn't start with a valid country calling code, and leaves nationalNumber
2369372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  // unmodified.
2370372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  int extractCountryCode(StringBuilder fullNumber, StringBuilder nationalNumber) {
2371ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia    if ((fullNumber.length() == 0) || (fullNumber.charAt(0) == '0')) {
2372ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia      // Country codes do not begin with a '0'.
2373ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia      return 0;
2374ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia    }
23751524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    int potentialCountryCode;
2376df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia    int numberLength = fullNumber.length();
237774aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia    for (int i = 1; i <= MAX_LENGTH_COUNTRY_CODE && i <= numberLength; i++) {
23781524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      potentialCountryCode = Integer.parseInt(fullNumber.substring(0, i));
2379372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      if (countryCallingCodeToRegionCodeMap.containsKey(potentialCountryCode)) {
23801524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia        nationalNumber.append(fullNumber.substring(i));
23811524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia        return potentialCountryCode;
23821524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      }
23831524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
23841524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    return 0;
23851524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
23861524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
23871524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
2388372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * Tries to extract a country calling code from a number. This method will return zero if no
2389372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * country calling code is considered to be present. Country calling codes are extracted in the
2390372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * following ways:
2391372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * <ul>
2392372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *  <li> by stripping the international dialing prefix of the region the person is dialing from,
23931524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *       if this is present in the number, and looking at the next digits
2394372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *  <li> by stripping the '+' sign if present and then looking at the next digits
2395372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *  <li> by comparing the start of the number and the country calling code of the default region.
2396372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *       If the number is not considered possible for the numbering plan of the default region
2397372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *       initially, but starts with the country calling code of this region, validation will be
2398372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *       reattempted after stripping this country calling code. If this number is considered a
2399372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *       possible number, then the first digits will be considered the country calling code and
2400372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *       removed as such.
2401372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * </ul>
2402372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * It will throw a NumberParseException if the number starts with a '+' but the country calling
2403372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * code supplied after this does not match that of any known region.
24041524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *
2405372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * @param number  non-normalized telephone number that we wish to extract a country calling
24061524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *     code from - may begin with '+'
24071524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @param defaultRegionMetadata  metadata about the region this number may be from
24081524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @param nationalNumber  a string buffer to store the national significant number in, in the case
2409372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *     that a country calling code was extracted. The number is appended to any existing contents.
2410372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *     If no country calling code was extracted, this will be left unchanged.
241152699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia   * @param keepRawInput  true if the country_code_source and preferred_carrier_code fields of
241252699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia   *     phoneNumber should be populated.
2413372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * @param phoneNumber  the PhoneNumber object where the country_code and country_code_source need
2414372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *     to be populated. Note the country_code is always populated, whereas country_code_source is
2415372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *     only populated when keepCountryCodeSource is true.
2416372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * @return  the country calling code extracted or 0 if none could be extracted
24171524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
2418ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia  // @VisibleForTesting
24191524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  int maybeExtractCountryCode(String number, PhoneMetadata defaultRegionMetadata,
2420372bff8dd464574d36737d47e495cad14346653cShaopeng Jia                              StringBuilder nationalNumber, boolean keepRawInput,
242176f6569af0619d12afd19991d8ff69a9bea4c142Shaopeng Jia                              PhoneNumber phoneNumber)
24221524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      throws NumberParseException {
24235c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia    if (number.length() == 0) {
24245c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia      return 0;
24255c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia    }
2426372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    StringBuilder fullNumber = new StringBuilder(number);
24271524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    // Set the default prefix to be something that will never match.
24281524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    String possibleCountryIddPrefix = "NonMatch";
24291524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    if (defaultRegionMetadata != null) {
243093399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller      possibleCountryIddPrefix = defaultRegionMetadata.getInternationalPrefix();
24311524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
24325c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia
24335c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia    CountryCodeSource countryCodeSource =
24345c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia        maybeStripInternationalPrefixAndNormalize(fullNumber, possibleCountryIddPrefix);
243552699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia    if (keepRawInput) {
24365c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia      phoneNumber.setCountryCodeSource(countryCodeSource);
24375c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia    }
24385c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia    if (countryCodeSource != CountryCodeSource.FROM_DEFAULT_COUNTRY) {
2439bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia      if (fullNumber.length() <= MIN_LENGTH_FOR_NSN) {
24401524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia        throw new NumberParseException(NumberParseException.ErrorType.TOO_SHORT_AFTER_IDD,
24411524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia                                       "Phone number had an IDD, but after this was not "
24421524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia                                       + "long enough to be a viable phone number.");
24431524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      }
24441524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      int potentialCountryCode = extractCountryCode(fullNumber, nationalNumber);
24451524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      if (potentialCountryCode != 0) {
24465c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia        phoneNumber.setCountryCode(potentialCountryCode);
24471524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia        return potentialCountryCode;
24481524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      }
24491524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
2450372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      // If this fails, they must be using a strange country calling code that we don't recognize,
2451372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      // or that doesn't exist.
24521524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      throw new NumberParseException(NumberParseException.ErrorType.INVALID_COUNTRY_CODE,
2453372bff8dd464574d36737d47e495cad14346653cShaopeng Jia                                     "Country calling code supplied was not recognised.");
24541524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    } else if (defaultRegionMetadata != null) {
2455372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      // Check to see if the number starts with the country calling code for the default region. If
2456372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      // so, we remove the country calling code, and do some checks on the validity of the number
2457372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      // before and after.
245893399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller      int defaultCountryCode = defaultRegionMetadata.getCountryCode();
2459372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      String defaultCountryCodeString = String.valueOf(defaultCountryCode);
2460372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      String normalizedNumber = fullNumber.toString();
2461372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      if (normalizedNumber.startsWith(defaultCountryCodeString)) {
2462372bff8dd464574d36737d47e495cad14346653cShaopeng Jia        StringBuilder potentialNationalNumber =
2463372bff8dd464574d36737d47e495cad14346653cShaopeng Jia            new StringBuilder(normalizedNumber.substring(defaultCountryCodeString.length()));
246493399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller        PhoneNumberDesc generalDesc = defaultRegionMetadata.getGeneralDesc();
2465372bff8dd464574d36737d47e495cad14346653cShaopeng Jia        Pattern validNumberPattern =
246693399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller            regexCache.getPatternForRegex(generalDesc.getNationalNumberPattern());
2467a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia        maybeStripNationalPrefixAndCarrierCode(
2468a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia            potentialNationalNumber, defaultRegionMetadata, null /* Don't need the carrier code */);
2469372bff8dd464574d36737d47e495cad14346653cShaopeng Jia        Pattern possibleNumberPattern =
247093399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller            regexCache.getPatternForRegex(generalDesc.getPossibleNumberPattern());
2471372bff8dd464574d36737d47e495cad14346653cShaopeng Jia        // If the number was not valid before but is valid now, or if it was too long before, we
2472372bff8dd464574d36737d47e495cad14346653cShaopeng Jia        // consider the number with the country calling code stripped to be a better result and
2473372bff8dd464574d36737d47e495cad14346653cShaopeng Jia        // keep that instead.
2474372bff8dd464574d36737d47e495cad14346653cShaopeng Jia        if ((!validNumberPattern.matcher(fullNumber).matches() &&
2475372bff8dd464574d36737d47e495cad14346653cShaopeng Jia             validNumberPattern.matcher(potentialNationalNumber).matches()) ||
2476372bff8dd464574d36737d47e495cad14346653cShaopeng Jia             testNumberLengthAgainstPattern(possibleNumberPattern, fullNumber.toString())
2477372bff8dd464574d36737d47e495cad14346653cShaopeng Jia                  == ValidationResult.TOO_LONG) {
2478372bff8dd464574d36737d47e495cad14346653cShaopeng Jia          nationalNumber.append(potentialNationalNumber);
2479372bff8dd464574d36737d47e495cad14346653cShaopeng Jia          if (keepRawInput) {
2480372bff8dd464574d36737d47e495cad14346653cShaopeng Jia            phoneNumber.setCountryCodeSource(CountryCodeSource.FROM_NUMBER_WITHOUT_PLUS_SIGN);
24811524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia          }
2482372bff8dd464574d36737d47e495cad14346653cShaopeng Jia          phoneNumber.setCountryCode(defaultCountryCode);
2483372bff8dd464574d36737d47e495cad14346653cShaopeng Jia          return defaultCountryCode;
24841524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia        }
24851524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      }
24861524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
2487372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    // No country calling code present.
24885c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia    phoneNumber.setCountryCode(0);
24891524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    return 0;
24901524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
24911524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
24921524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
24931524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * Strips the IDD from the start of the number if present. Helper function used by
24941524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * maybeStripInternationalPrefixAndNormalize.
24951524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
2496372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  private boolean parsePrefixAsIdd(Pattern iddPattern, StringBuilder number) {
24971524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    Matcher m = iddPattern.matcher(number);
24981524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    if (m.lookingAt()) {
24991524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      int matchEnd = m.end();
2500372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      // Only strip this if the first digit after the match is not a 0, since country calling codes
2501372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      // cannot begin with 0.
25021524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      Matcher digitMatcher = CAPTURING_DIGIT_PATTERN.matcher(number.substring(matchEnd));
25031524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      if (digitMatcher.find()) {
2504d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia        String normalizedGroup = normalizeDigitsOnly(digitMatcher.group(1));
25051524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia        if (normalizedGroup.equals("0")) {
25061524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia          return false;
25071524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia        }
25081524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      }
25091524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      number.delete(0, matchEnd);
25101524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      return true;
25111524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
25121524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    return false;
25131524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
25141524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
25151524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
25161524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * Strips any international prefix (such as +, 00, 011) present in the number provided, normalizes
2517f59ccfca9dd02c4e3cf3e06b5cf184a8d0e67626Shaopeng Jia   * the resulting number, and indicates if an international prefix was present.
25181524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *
25191524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @param number  the non-normalized telephone number that we wish to strip any international
252074aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia   *     dialing prefix from.
2521372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * @param possibleIddPrefix  the international direct dialing prefix from the region we
25221524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *     think this number may be dialed in
25235c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia   * @return  the corresponding CountryCodeSource if an international dialing prefix could be
2524372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *     removed from the number, otherwise CountryCodeSource.FROM_DEFAULT_COUNTRY if the number did
2525372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *     not seem to be in international format.
25261524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
2527ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia  // @VisibleForTesting
25285c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia  CountryCodeSource maybeStripInternationalPrefixAndNormalize(
2529372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      StringBuilder number,
25305c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia      String possibleIddPrefix) {
25311524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    if (number.length() == 0) {
25325c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia      return CountryCodeSource.FROM_DEFAULT_COUNTRY;
25331524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
2534256a5f71a05ffd182a0fda2cfed6f93345cc889fLara Rennie    // Check to see if the number begins with one or more plus signs.
2535256a5f71a05ffd182a0fda2cfed6f93345cc889fLara Rennie    Matcher m = PLUS_CHARS_PATTERN.matcher(number);
2536256a5f71a05ffd182a0fda2cfed6f93345cc889fLara Rennie    if (m.lookingAt()) {
2537256a5f71a05ffd182a0fda2cfed6f93345cc889fLara Rennie      number.delete(0, m.end());
25381524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      // Can now normalize the rest of the number since we've consumed the "+" sign at the start.
25391524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      normalize(number);
25405c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia      return CountryCodeSource.FROM_NUMBER_WITH_PLUS_SIGN;
25411524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
25421524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    // Attempt to parse the first digits as an international prefix.
2543be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    Pattern iddPattern = regexCache.getPatternForRegex(possibleIddPrefix);
25441524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    normalize(number);
25455c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia    return parsePrefixAsIdd(iddPattern, number)
2546f59ccfca9dd02c4e3cf3e06b5cf184a8d0e67626Shaopeng Jia           ? CountryCodeSource.FROM_NUMBER_WITH_IDD
2547f59ccfca9dd02c4e3cf3e06b5cf184a8d0e67626Shaopeng Jia           : CountryCodeSource.FROM_DEFAULT_COUNTRY;
25481524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
25491524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
25501524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
25511524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * Strips any national prefix (such as 0, 1) present in the number provided.
25521524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *
25531524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @param number  the normalized telephone number that we wish to strip any national
25541524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *     dialing prefix from
2555372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * @param metadata  the metadata for the region that we think this number is from
2556a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia   * @param carrierCode  a place to insert the carrier code if one is extracted
2557a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia   * @return true if a national prefix or carrier code (or both) could be extracted.
25581524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
2559ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia  // @VisibleForTesting
2560a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia  boolean maybeStripNationalPrefixAndCarrierCode(
2561a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia      StringBuilder number, PhoneMetadata metadata, StringBuilder carrierCode) {
25621524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    int numberLength = number.length();
256393399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller    String possibleNationalPrefix = metadata.getNationalPrefixForParsing();
2564be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    if (numberLength == 0 || possibleNationalPrefix.length() == 0) {
25651524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      // Early return for numbers of zero length.
2566a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia      return false;
25671524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
25681524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    // Attempt to parse the first digits as a national prefix.
256952699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia    Matcher prefixMatcher = regexCache.getPatternForRegex(possibleNationalPrefix).matcher(number);
257052699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia    if (prefixMatcher.lookingAt()) {
257152699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia      Pattern nationalNumberRule =
257293399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller          regexCache.getPatternForRegex(metadata.getGeneralDesc().getNationalNumberPattern());
2573f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia      // Check if the original number is viable.
2574f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia      boolean isViableOriginalNumber = nationalNumberRule.matcher(number).matches();
257552699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia      // prefixMatcher.group(numOfGroups) == null implies nothing was captured by the capturing
257652699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia      // groups in possibleNationalPrefix; therefore, no transformation is necessary, and we just
257752699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia      // remove the national prefix.
257852699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia      int numOfGroups = prefixMatcher.groupCount();
257993399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller      String transformRule = metadata.getNationalPrefixTransformRule();
258052699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia      if (transformRule == null || transformRule.length() == 0 ||
258152699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia          prefixMatcher.group(numOfGroups) == null) {
2582f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia        // If the original number was viable, and the resultant number is not, we return.
2583f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia        if (isViableOriginalNumber &&
2584f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia            !nationalNumberRule.matcher(number.substring(prefixMatcher.end())).matches()) {
2585a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia          return false;
258652699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia        }
2587a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia        if (carrierCode != null && numOfGroups > 0 && prefixMatcher.group(numOfGroups) != null) {
2588a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia          carrierCode.append(prefixMatcher.group(1));
25891524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia        }
259052699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia        number.delete(0, prefixMatcher.end());
2591a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia        return true;
25921524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      } else {
2593f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia        // Check that the resultant number is still viable. If not, return. Check this by copying
2594f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia        // the string buffer and making the transformation on the copy first.
2595372bff8dd464574d36737d47e495cad14346653cShaopeng Jia        StringBuilder transformedNumber = new StringBuilder(number);
259652699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia        transformedNumber.replace(0, numberLength, prefixMatcher.replaceFirst(transformRule));
2597f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia        if (isViableOriginalNumber &&
2598f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia            !nationalNumberRule.matcher(transformedNumber.toString()).matches()) {
2599a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia          return false;
260052699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia        }
2601a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia        if (carrierCode != null && numOfGroups > 1) {
2602a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia          carrierCode.append(prefixMatcher.group(1));
26031524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia        }
26041524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia        number.replace(0, number.length(), transformedNumber.toString());
2605a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia        return true;
26061524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      }
26071524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
2608a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia    return false;
26091524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
26101524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
26111524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
26121524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * Strips any extension (as in, the part of the number dialled after the call is connected,
26131524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * usually indicated with extn, ext, x or similar) from the end of the number, and returns it.
26141524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *
26151524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @param number  the non-normalized telephone number that we wish to strip the extension from
26161524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @return        the phone extension
26171524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
2618ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia  // @VisibleForTesting
2619372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  String maybeStripExtension(StringBuilder number) {
26201524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    Matcher m = EXTN_PATTERN.matcher(number);
26211524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    // If we find a potential extension, and the number preceding this is a viable number, we assume
26221524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    // it is an extension.
26231524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    if (m.find() && isViablePhoneNumber(number.substring(0, m.start()))) {
26241524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      // The numbers are captured into groups in the regular expression.
26254b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia      for (int i = 1, length = m.groupCount(); i <= length; i++) {
26261524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia        if (m.group(i) != null) {
26271524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia          // We go through the capturing groups until we find one that captured some digits. If none
26281524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia          // did, then we will return the empty string.
26291524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia          String extension = m.group(i);
26301524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia          number.delete(m.start(), number.length());
26311524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia          return extension;
26321524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia        }
26331524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      }
26341524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
26351524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    return "";
26361524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
26371524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
26381524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
263974aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia   * Checks to see that the region code used is valid, or if it is not valid, that the number to
2640372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * parse starts with a + symbol so that we can attempt to infer the region from the number.
264174aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia   * Returns false if it cannot use the region provided and the region cannot be inferred.
264274aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia   */
2643372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  private boolean checkRegionForParsing(String numberToParse, String defaultRegion) {
2644372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    if (!isValidRegionCode(defaultRegion)) {
2645372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      // If the number is null or empty, we can't infer the region.
26467a81979b0076f18b31b47b7df2beac29735f3a37Cecilia Roes      if ((numberToParse == null) || (numberToParse.length() == 0) ||
264774aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia          !PLUS_CHARS_PATTERN.matcher(numberToParse).lookingAt()) {
264874aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia        return false;
264974aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia      }
265074aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia    }
265174aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia    return true;
265274aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia  }
265374aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia
265474aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia  /**
26551524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * Parses a string and returns it in proto buffer format. This method will throw a
2656a77faddfc3b3e4cca8f585c82d669054aec221f4Narayan Kamath   * {@link com.google.i18n.phonenumbers.NumberParseException} if the number is not considered to be
2657372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * a possible number. Note that validation of whether the number is actually a valid number for a
2658372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * particular region is not performed. This can be done separately with {@link #isValidNumber}.
26591524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *
26601524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @param numberToParse     number that we are attempting to parse. This can contain formatting
2661bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia   *                          such as +, ( and -, as well as a phone number extension. It can also
2662bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia   *                          be provided in RFC3966 format.
2663d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   * @param defaultRegion     region that we are expecting the number to be from. This is only used
2664d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   *                          if the number being parsed is not written in international format.
2665372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *                          The country_code for the number in this case would be stored as that
2666372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *                          of the default region supplied. If the number is guaranteed to
2667d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   *                          start with a '+' followed by the country calling code, then
2668d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   *                          "ZZ" or null can be supplied.
26691524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @return                  a phone number proto buffer filled with the parsed number
26701524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @throws NumberParseException  if the string is not considered to be a viable phone number or if
2671372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *                               no default region was supplied and the number is not in
2672f59ccfca9dd02c4e3cf3e06b5cf184a8d0e67626Shaopeng Jia   *                               international format (does not start with +)
26731524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
2674372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  public PhoneNumber parse(String numberToParse, String defaultRegion)
26751524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      throws NumberParseException {
267676f6569af0619d12afd19991d8ff69a9bea4c142Shaopeng Jia    PhoneNumber phoneNumber = new PhoneNumber();
2677372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    parse(numberToParse, defaultRegion, phoneNumber);
267876f6569af0619d12afd19991d8ff69a9bea4c142Shaopeng Jia    return phoneNumber;
2679be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia  }
2680be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia
2681d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia  /**
2682d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   * Same as {@link #parse(String, String)}, but accepts mutable PhoneNumber as a parameter to
2683d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   * decrease object creation when invoked many times.
2684d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   */
2685372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  public void parse(String numberToParse, String defaultRegion, PhoneNumber phoneNumber)
2686be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia      throws NumberParseException {
2687372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    parseHelper(numberToParse, defaultRegion, false, true, phoneNumber);
26887900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia  }
26897900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia
26907900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia  /**
2691372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * Parses a string and returns it in proto buffer format. This method differs from {@link #parse}
2692372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * in that it always populates the raw_input field of the protocol buffer with numberToParse as
2693372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * well as the country_code_source field.
26947900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia   *
26957900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia   * @param numberToParse     number that we are attempting to parse. This can contain formatting
26967900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia   *                          such as +, ( and -, as well as a phone number extension.
2697d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   * @param defaultRegion     region that we are expecting the number to be from. This is only used
2698d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   *                          if the number being parsed is not written in international format.
2699d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   *                          The country calling code for the number in this case would be stored
2700d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   *                          as that of the default region supplied.
27017900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia   * @return                  a phone number proto buffer filled with the parsed number
27027900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia   * @throws NumberParseException  if the string is not considered to be a viable phone number or if
2703372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *                               no default region was supplied
27047900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia   */
2705372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  public PhoneNumber parseAndKeepRawInput(String numberToParse, String defaultRegion)
27067900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia      throws NumberParseException {
270776f6569af0619d12afd19991d8ff69a9bea4c142Shaopeng Jia    PhoneNumber phoneNumber = new PhoneNumber();
2708372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    parseAndKeepRawInput(numberToParse, defaultRegion, phoneNumber);
270976f6569af0619d12afd19991d8ff69a9bea4c142Shaopeng Jia    return phoneNumber;
2710be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia  }
2711be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia
2712d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia  /**
2713d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   * Same as{@link #parseAndKeepRawInput(String, String)}, but accepts a mutable PhoneNumber as
2714d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   * a parameter to decrease object creation when invoked many times.
2715d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   */
2716372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  public void parseAndKeepRawInput(String numberToParse, String defaultRegion,
271776f6569af0619d12afd19991d8ff69a9bea4c142Shaopeng Jia                                   PhoneNumber phoneNumber)
2718be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia      throws NumberParseException {
2719372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    parseHelper(numberToParse, defaultRegion, true, true, phoneNumber);
27201524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
27211524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
27221524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
272352699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia   * Returns an iterable over all {@link PhoneNumberMatch PhoneNumberMatches} in {@code text}. This
272452699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia   * is a shortcut for {@link #findNumbers(CharSequence, String, Leniency, long)
2725372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * getMatcher(text, defaultRegion, Leniency.VALID, Long.MAX_VALUE)}.
272652699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia   *
272752699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia   * @param text              the text to search for phone numbers, null for no text
2728d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   * @param defaultRegion     region that we are expecting the number to be from. This is only used
2729d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   *                          if the number being parsed is not written in international format. The
2730d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   *                          country_code for the number in this case would be stored as that of
2731d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   *                          the default region supplied. May be null if only international
273252699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia   *                          numbers are expected.
273352699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia   */
2734372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  public Iterable<PhoneNumberMatch> findNumbers(CharSequence text, String defaultRegion) {
2735372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    return findNumbers(text, defaultRegion, Leniency.VALID, Long.MAX_VALUE);
273652699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia  }
273752699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia
273852699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia  /**
273952699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia   * Returns an iterable over all {@link PhoneNumberMatch PhoneNumberMatches} in {@code text}.
274052699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia   *
274152699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia   * @param text              the text to search for phone numbers, null for no text
2742d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   * @param defaultRegion     region that we are expecting the number to be from. This is only used
2743d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   *                          if the number being parsed is not written in international format. The
2744d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   *                          country_code for the number in this case would be stored as that of
2745d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   *                          the default region supplied. May be null if only international
274652699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia   *                          numbers are expected.
274752699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia   * @param leniency          the leniency to use when evaluating candidate phone numbers
274852699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia   * @param maxTries          the maximum number of invalid numbers to try before giving up on the
274952699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia   *                          text. This is to cover degenerate cases where the text has a lot of
275052699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia   *                          false positives in it. Must be {@code >= 0}.
275152699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia   */
275252699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia  public Iterable<PhoneNumberMatch> findNumbers(
2753372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      final CharSequence text, final String defaultRegion, final Leniency leniency,
275452699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia      final long maxTries) {
275552699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia
275652699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia    return new Iterable<PhoneNumberMatch>() {
2757b0d1cb1662daab3451e5fa59b8f073e9992b628bAndy Staudacher      @Override
275852699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia      public Iterator<PhoneNumberMatch> iterator() {
275952699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia        return new PhoneNumberMatcher(
2760372bff8dd464574d36737d47e495cad14346653cShaopeng Jia            PhoneNumberUtil.this, text, defaultRegion, leniency, maxTries);
276152699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia      }
276252699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia    };
276352699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia  }
276452699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia
276552699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia  /**
2766f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia   * A helper function to set the values related to leading zeros in a PhoneNumber.
2767f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia   */
2768f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia  static void setItalianLeadingZerosForPhoneNumber(String nationalNumber, PhoneNumber phoneNumber) {
2769f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia    if (nationalNumber.length() > 1 && nationalNumber.charAt(0) == '0') {
2770f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia      phoneNumber.setItalianLeadingZero(true);
2771f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia      int numberOfLeadingZeros = 1;
2772f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia      // Note that if the national number is all "0"s, the last "0" is not counted as a leading
2773f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia      // zero.
2774f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia      while (numberOfLeadingZeros < nationalNumber.length() - 1 &&
2775f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia             nationalNumber.charAt(numberOfLeadingZeros) == '0') {
2776f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia        numberOfLeadingZeros++;
2777f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia      }
2778f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia      if (numberOfLeadingZeros != 1) {
2779f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia        phoneNumber.setNumberOfLeadingZeros(numberOfLeadingZeros);
2780f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia      }
2781f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia    }
2782f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia  }
2783f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia
2784f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia  /**
2785be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia   * Parses a string and fills up the phoneNumber. This method is the same as the public
2786372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * parse() method, with the exception that it allows the default region to be null, for use by
2787372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * isNumberMatch(). checkRegion should be set to false if it is permitted for the default region
278874aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia   * to be null or unknown ("ZZ").
27891524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
2790372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  private void parseHelper(String numberToParse, String defaultRegion, boolean keepRawInput,
279174aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia                           boolean checkRegion, PhoneNumber phoneNumber)
27921524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      throws NumberParseException {
279374aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia    if (numberToParse == null) {
279474aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia      throw new NumberParseException(NumberParseException.ErrorType.NOT_A_NUMBER,
279574aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia                                     "The phone number supplied was null.");
2796b0e21c22b1ca6b9aeb1426924cdf42a221c3d416Shaopeng Jia    } else if (numberToParse.length() > MAX_INPUT_STRING_LENGTH) {
2797b0e21c22b1ca6b9aeb1426924cdf42a221c3d416Shaopeng Jia      throw new NumberParseException(NumberParseException.ErrorType.TOO_LONG,
2798b0e21c22b1ca6b9aeb1426924cdf42a221c3d416Shaopeng Jia                                     "The string supplied was too long to parse.");
279974aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia    }
2800b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia
2801b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia    StringBuilder nationalNumber = new StringBuilder();
2802bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia    buildNationalNumberForParsing(numberToParse, nationalNumber);
2803b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia
2804b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia    if (!isViablePhoneNumber(nationalNumber.toString())) {
28051524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      throw new NumberParseException(NumberParseException.ErrorType.NOT_A_NUMBER,
28061524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia                                     "The string supplied did not seem to be a phone number.");
28071524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
28081524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
2809372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    // Check the region supplied is valid, or that the extracted number starts with some sort of +
281074aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia    // sign so the number's region can be determined.
2811b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia    if (checkRegion && !checkRegionForParsing(nationalNumber.toString(), defaultRegion)) {
281274aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia      throw new NumberParseException(NumberParseException.ErrorType.INVALID_COUNTRY_CODE,
2813372bff8dd464574d36737d47e495cad14346653cShaopeng Jia                                     "Missing or invalid default region.");
281474aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia    }
281574aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia
28167900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia    if (keepRawInput) {
28177900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia      phoneNumber.setRawInput(numberToParse);
28187900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia    }
2819372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    // Attempt to parse extension first, since it doesn't require region-specific data and we want
28201524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    // to have the non-normalised number here.
28211524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    String extension = maybeStripExtension(nationalNumber);
2822be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    if (extension.length() > 0) {
28231524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      phoneNumber.setExtension(extension);
28241524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
28251524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
2826372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    PhoneMetadata regionMetadata = getMetadataForRegion(defaultRegion);
28271524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    // Check to see if the number is given in international format so we know whether this number is
2828372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    // from the default region or not.
2829372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    StringBuilder normalizedNationalNumber = new StringBuilder();
2830ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia    int countryCode = 0;
2831ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia    try {
2832ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia      // TODO: This method should really just take in the string buffer that has already
2833ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia      // been created, and just remove the prefix, rather than taking in a string and then
2834ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia      // outputting a string buffer.
2835ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia      countryCode = maybeExtractCountryCode(nationalNumber.toString(), regionMetadata,
2836ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia                                            normalizedNationalNumber, keepRawInput, phoneNumber);
2837ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia    } catch (NumberParseException e) {
2838ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia      Matcher matcher = PLUS_CHARS_PATTERN.matcher(nationalNumber.toString());
2839ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia      if (e.getErrorType() == NumberParseException.ErrorType.INVALID_COUNTRY_CODE &&
2840ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia          matcher.lookingAt()) {
2841ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia        // Strip the plus-char, and try again.
2842ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia        countryCode = maybeExtractCountryCode(nationalNumber.substring(matcher.end()),
2843ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia                                              regionMetadata, normalizedNationalNumber,
2844ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia                                              keepRawInput, phoneNumber);
2845ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia        if (countryCode == 0) {
2846ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia          throw new NumberParseException(NumberParseException.ErrorType.INVALID_COUNTRY_CODE,
2847ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia                                         "Could not interpret numbers after plus-sign.");
2848ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia        }
2849ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia      } else {
2850ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia        throw new NumberParseException(e.getErrorType(), e.getMessage());
2851ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia      }
2852ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia    }
28531524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    if (countryCode != 0) {
28541524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      String phoneNumberRegion = getRegionCodeForCountryCode(countryCode);
2855372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      if (!phoneNumberRegion.equals(defaultRegion)) {
2856203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia        // Metadata cannot be null because the country calling code is valid.
2857528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        regionMetadata = getMetadataForRegionOrCallingCode(countryCode, phoneNumberRegion);
28585c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia      }
28591524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    } else {
2860372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      // If no extracted country calling code, use the region supplied instead. The national number
2861372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      // is just the normalized version of the number we were given to parse.
28621524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      normalize(nationalNumber);
28631524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      normalizedNationalNumber.append(nationalNumber);
2864372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      if (defaultRegion != null) {
286593399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller        countryCode = regionMetadata.getCountryCode();
28665c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia        phoneNumber.setCountryCode(countryCode);
28675c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia      } else if (keepRawInput) {
28685c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia        phoneNumber.clearCountryCodeSource();
28691524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      }
28701524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
28711524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    if (normalizedNationalNumber.length() < MIN_LENGTH_FOR_NSN) {
28721524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      throw new NumberParseException(NumberParseException.ErrorType.TOO_SHORT_NSN,
28731524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia                                     "The string supplied is too short to be a phone number.");
28741524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
2875372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    if (regionMetadata != null) {
2876a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia      StringBuilder carrierCode = new StringBuilder();
2877f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia      StringBuilder potentialNationalNumber = new StringBuilder(normalizedNationalNumber);
2878f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia      maybeStripNationalPrefixAndCarrierCode(potentialNationalNumber, regionMetadata, carrierCode);
2879f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia      // We require that the NSN remaining after stripping the national prefix and carrier code be
2880f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia      // of a possible length for the region. Otherwise, we don't do the stripping, since the
2881f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia      // original number could be a valid short number.
2882f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia      if (!isShorterThanPossibleNormalNumber(regionMetadata, potentialNationalNumber.toString())) {
2883f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia        normalizedNationalNumber = potentialNationalNumber;
2884f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia        if (keepRawInput) {
2885f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia          phoneNumber.setPreferredDomesticCarrierCode(carrierCode.toString());
2886f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia        }
288752699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia      }
28881524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
28891524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    int lengthOfNationalNumber = normalizedNationalNumber.length();
28901524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    if (lengthOfNationalNumber < MIN_LENGTH_FOR_NSN) {
28911524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      throw new NumberParseException(NumberParseException.ErrorType.TOO_SHORT_NSN,
2892be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia                                     "The string supplied is too short to be a phone number.");
28931524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
28941524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    if (lengthOfNationalNumber > MAX_LENGTH_FOR_NSN) {
28951524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      throw new NumberParseException(NumberParseException.ErrorType.TOO_LONG,
2896be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia                                     "The string supplied is too long to be a phone number.");
28971524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
2898f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia    setItalianLeadingZerosForPhoneNumber(normalizedNationalNumber.toString(), phoneNumber);
28991524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    phoneNumber.setNationalNumber(Long.parseLong(normalizedNationalNumber.toString()));
29001524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
29011524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
29021524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
2903bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia   * Converts numberToParse to a form that we can parse and write it to nationalNumber if it is
2904bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia   * written in RFC3966; otherwise extract a possible number out of it and write to nationalNumber.
2905bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia   */
2906bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia  private void buildNationalNumberForParsing(String numberToParse, StringBuilder nationalNumber) {
2907bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia    int indexOfPhoneContext = numberToParse.indexOf(RFC3966_PHONE_CONTEXT);
2908bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia    if (indexOfPhoneContext > 0) {
2909bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia      int phoneContextStart = indexOfPhoneContext + RFC3966_PHONE_CONTEXT.length();
2910bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia      // If the phone context contains a phone number prefix, we need to capture it, whereas domains
2911bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia      // will be ignored.
2912bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia      if (numberToParse.charAt(phoneContextStart) == PLUS_SIGN) {
2913bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia        // Additional parameters might follow the phone context. If so, we will remove them here
2914bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia        // because the parameters after phone context are not important for parsing the
2915bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia        // phone number.
2916bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia        int phoneContextEnd = numberToParse.indexOf(';', phoneContextStart);
2917bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia        if (phoneContextEnd > 0) {
2918bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia          nationalNumber.append(numberToParse.substring(phoneContextStart, phoneContextEnd));
2919bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia        } else {
2920bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia          nationalNumber.append(numberToParse.substring(phoneContextStart));
2921bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia        }
2922bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia      }
2923bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia
2924bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia      // Now append everything between the "tel:" prefix and the phone-context. This should include
29257a81979b0076f18b31b47b7df2beac29735f3a37Cecilia Roes      // the national number, an optional extension or isdn-subaddress component. Note we also
29267a81979b0076f18b31b47b7df2beac29735f3a37Cecilia Roes      // handle the case when "tel:" is missing, as we have seen in some of the phone number inputs.
29277a81979b0076f18b31b47b7df2beac29735f3a37Cecilia Roes      // In that case, we append everything from the beginning.
29287a81979b0076f18b31b47b7df2beac29735f3a37Cecilia Roes      int indexOfRfc3966Prefix = numberToParse.indexOf(RFC3966_PREFIX);
29297a81979b0076f18b31b47b7df2beac29735f3a37Cecilia Roes      int indexOfNationalNumber = (indexOfRfc3966Prefix >= 0) ?
29307a81979b0076f18b31b47b7df2beac29735f3a37Cecilia Roes          indexOfRfc3966Prefix + RFC3966_PREFIX.length() : 0;
29317a81979b0076f18b31b47b7df2beac29735f3a37Cecilia Roes      nationalNumber.append(numberToParse.substring(indexOfNationalNumber, indexOfPhoneContext));
2932bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia    } else {
2933bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia      // Extract a possible number from the string passed in (this strips leading characters that
2934bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia      // could not be the start of a phone number.)
2935bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia      nationalNumber.append(extractPossibleNumber(numberToParse));
2936bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia    }
2937bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia
2938bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia    // Delete the isdn-subaddress and everything after it if it is present. Note extension won't
2939bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia    // appear at the same time with isdn-subaddress according to paragraph 5.3 of the RFC3966 spec,
2940bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia    int indexOfIsdn = nationalNumber.indexOf(RFC3966_ISDN_SUBADDRESS);
2941bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia    if (indexOfIsdn > 0) {
2942bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia      nationalNumber.delete(indexOfIsdn, nationalNumber.length());
2943bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia    }
2944bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia    // If both phone context and isdn-subaddress are absent but other parameters are present, the
2945bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia    // parameters are left in nationalNumber. This is because we are concerned about deleting
2946bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia    // content from a potential number string when there is no strong evidence that the number is
2947bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia    // actually written in RFC3966.
2948bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia  }
2949bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia
2950bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia  /**
29511524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * Takes two phone numbers and compares them for equality.
29521524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *
2953372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * <p>Returns EXACT_MATCH if the country_code, NSN, presence of a leading zero for Italian numbers
29541524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * and any extension present are the same.
2955372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * Returns NSN_MATCH if either or both has no region specified, and the NSNs and extensions are
29561524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * the same.
2957372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * Returns SHORT_NSN_MATCH if either or both has no region specified, or the region specified is
2958372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * the same, and one NSN could be a shorter version of the other number. This includes the case
29591524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * where one has an extension specified, and the other does not.
29601524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * Returns NO_MATCH otherwise.
29611524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * For example, the numbers +1 345 657 1234 and 657 1234 are a SHORT_NSN_MATCH.
29621524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * The numbers +1 345 657 1234 and 345 657 are a NO_MATCH.
29631524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *
29641524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @param firstNumberIn  first number to compare
29651524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @param secondNumberIn  second number to compare
29661524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *
29671524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @return  NO_MATCH, SHORT_NSN_MATCH, NSN_MATCH or EXACT_MATCH depending on the level of equality
29681524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *     of the two numbers, described in the method definition.
29691524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
29701524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  public MatchType isNumberMatch(PhoneNumber firstNumberIn, PhoneNumber secondNumberIn) {
29711524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    // Make copies of the phone number so that the numbers passed in are not edited.
297276f6569af0619d12afd19991d8ff69a9bea4c142Shaopeng Jia    PhoneNumber firstNumber = new PhoneNumber();
29731524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    firstNumber.mergeFrom(firstNumberIn);
297476f6569af0619d12afd19991d8ff69a9bea4c142Shaopeng Jia    PhoneNumber secondNumber = new PhoneNumber();
29751524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    secondNumber.mergeFrom(secondNumberIn);
297652699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia    // First clear raw_input, country_code_source and preferred_domestic_carrier_code fields and any
297752699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia    // empty-string extensions so that we can use the proto-buffer equality method.
29787900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia    firstNumber.clearRawInput();
29795c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia    firstNumber.clearCountryCodeSource();
298052699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia    firstNumber.clearPreferredDomesticCarrierCode();
29817900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia    secondNumber.clearRawInput();
29825c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia    secondNumber.clearCountryCodeSource();
298352699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia    secondNumber.clearPreferredDomesticCarrierCode();
29841524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    if (firstNumber.hasExtension() &&
2985be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia        firstNumber.getExtension().length() == 0) {
29861524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia        firstNumber.clearExtension();
29871524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
29881524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    if (secondNumber.hasExtension() &&
2989be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia        secondNumber.getExtension().length() == 0) {
29901524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia        secondNumber.clearExtension();
29911524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
29921524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    // Early exit if both had extensions and these are different.
299376f6569af0619d12afd19991d8ff69a9bea4c142Shaopeng Jia    if (firstNumber.hasExtension() && secondNumber.hasExtension() &&
299476f6569af0619d12afd19991d8ff69a9bea4c142Shaopeng Jia        !firstNumber.getExtension().equals(secondNumber.getExtension())) {
29951524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      return MatchType.NO_MATCH;
29961524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
299776f6569af0619d12afd19991d8ff69a9bea4c142Shaopeng Jia    int firstNumberCountryCode = firstNumber.getCountryCode();
299876f6569af0619d12afd19991d8ff69a9bea4c142Shaopeng Jia    int secondNumberCountryCode = secondNumber.getCountryCode();
2999372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    // Both had country_code specified.
30001524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    if (firstNumberCountryCode != 0 && secondNumberCountryCode != 0) {
300176f6569af0619d12afd19991d8ff69a9bea4c142Shaopeng Jia      if (firstNumber.exactlySameAs(secondNumber)) {
30021524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia        return MatchType.EXACT_MATCH;
30037900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia      } else if (firstNumberCountryCode == secondNumberCountryCode &&
300476f6569af0619d12afd19991d8ff69a9bea4c142Shaopeng Jia                 isNationalNumberSuffixOfTheOther(firstNumber, secondNumber)) {
30051524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia        // A SHORT_NSN_MATCH occurs if there is a difference because of the presence or absence of
30061524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia        // an 'Italian leading zero', the presence or absence of an extension, or one NSN being a
30071524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia        // shorter variant of the other.
30087900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia        return MatchType.SHORT_NSN_MATCH;
30091524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      }
30101524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      // This is not a match.
30111524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      return MatchType.NO_MATCH;
30121524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
3013372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    // Checks cases where one or both country_code fields were not specified. To make equality
3014372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    // checks easier, we first set the country_code fields to be equal.
301576f6569af0619d12afd19991d8ff69a9bea4c142Shaopeng Jia    firstNumber.setCountryCode(secondNumberCountryCode);
30161524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    // If all else was the same, then this is an NSN_MATCH.
301776f6569af0619d12afd19991d8ff69a9bea4c142Shaopeng Jia    if (firstNumber.exactlySameAs(secondNumber)) {
30181524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      return MatchType.NSN_MATCH;
30191524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
302076f6569af0619d12afd19991d8ff69a9bea4c142Shaopeng Jia    if (isNationalNumberSuffixOfTheOther(firstNumber, secondNumber)) {
30211524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      return MatchType.SHORT_NSN_MATCH;
30221524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
3023be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    return MatchType.NO_MATCH;
30241524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
30251524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
30267900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia  // Returns true when one national number is the suffix of the other or both are the same.
30277900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia  private boolean isNationalNumberSuffixOfTheOther(PhoneNumber firstNumber,
30287900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia                                                   PhoneNumber secondNumber) {
30297900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia    String firstNumberNationalNumber = String.valueOf(firstNumber.getNationalNumber());
30307900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia    String secondNumberNationalNumber = String.valueOf(secondNumber.getNationalNumber());
30317900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia    // Note that endsWith returns true if the numbers are equal.
30327900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia    return firstNumberNationalNumber.endsWith(secondNumberNationalNumber) ||
30337900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia           secondNumberNationalNumber.endsWith(firstNumberNationalNumber);
30347900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia  }
30357900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia
30361524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
30371524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * Takes two phone numbers as strings and compares them for equality. This is a convenience
303896a7214cdabf08f53f5b1a560304601c9f65e0b9Shaopeng Jia   * wrapper for {@link #isNumberMatch(PhoneNumber, PhoneNumber)}. No default region is known.
30391524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *
3040372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * @param firstNumber  first number to compare. Can contain formatting, and can have country
3041372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *     calling code specified with + at the start.
30421524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @param secondNumber  second number to compare. Can contain formatting, and can have country
3043372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *     calling code specified with + at the start.
304474aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia   * @return  NOT_A_NUMBER, NO_MATCH, SHORT_NSN_MATCH, NSN_MATCH, EXACT_MATCH. See
304596a7214cdabf08f53f5b1a560304601c9f65e0b9Shaopeng Jia   *     {@link #isNumberMatch(PhoneNumber, PhoneNumber)} for more details.
30461524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
304774aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia  public MatchType isNumberMatch(String firstNumber, String secondNumber) {
304874aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia    try {
304974aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia      PhoneNumber firstNumberAsProto = parse(firstNumber, UNKNOWN_REGION);
305074aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia      return isNumberMatch(firstNumberAsProto, secondNumber);
305174aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia    } catch (NumberParseException e) {
305274aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia      if (e.getErrorType() == NumberParseException.ErrorType.INVALID_COUNTRY_CODE) {
305374aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia        try {
305474aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia          PhoneNumber secondNumberAsProto = parse(secondNumber, UNKNOWN_REGION);
305574aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia          return isNumberMatch(secondNumberAsProto, firstNumber);
305674aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia        } catch (NumberParseException e2) {
305774aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia          if (e2.getErrorType() == NumberParseException.ErrorType.INVALID_COUNTRY_CODE) {
305874aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia            try {
305974aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia              PhoneNumber firstNumberProto = new PhoneNumber();
306074aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia              PhoneNumber secondNumberProto = new PhoneNumber();
306174aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia              parseHelper(firstNumber, null, false, false, firstNumberProto);
306274aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia              parseHelper(secondNumber, null, false, false, secondNumberProto);
306374aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia              return isNumberMatch(firstNumberProto, secondNumberProto);
306474aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia            } catch (NumberParseException e3) {
306574aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia              // Fall through and return MatchType.NOT_A_NUMBER.
306674aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia            }
306774aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia          }
306874aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia        }
306974aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia      }
307074aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia    }
307174aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia    // One or more of the phone numbers we are trying to match is not a viable phone number.
307274aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia    return MatchType.NOT_A_NUMBER;
30731524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
30741524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
30751524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
30761524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * Takes two phone numbers and compares them for equality. This is a convenience wrapper for
307796a7214cdabf08f53f5b1a560304601c9f65e0b9Shaopeng Jia   * {@link #isNumberMatch(PhoneNumber, PhoneNumber)}. No default region is known.
30781524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *
30791524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @param firstNumber  first number to compare in proto buffer format.
30801524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @param secondNumber  second number to compare. Can contain formatting, and can have country
3081372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *     calling code specified with + at the start.
308274aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia   * @return  NOT_A_NUMBER, NO_MATCH, SHORT_NSN_MATCH, NSN_MATCH, EXACT_MATCH. See
308396a7214cdabf08f53f5b1a560304601c9f65e0b9Shaopeng Jia   *     {@link #isNumberMatch(PhoneNumber, PhoneNumber)} for more details.
30841524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
308574aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia  public MatchType isNumberMatch(PhoneNumber firstNumber, String secondNumber) {
3086372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    // First see if the second number has an implicit country calling code, by attempting to parse
3087372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    // it.
308874aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia    try {
308974aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia      PhoneNumber secondNumberAsProto = parse(secondNumber, UNKNOWN_REGION);
309074aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia      return isNumberMatch(firstNumber, secondNumberAsProto);
309174aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia    } catch (NumberParseException e) {
309274aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia      if (e.getErrorType() == NumberParseException.ErrorType.INVALID_COUNTRY_CODE) {
3093372bff8dd464574d36737d47e495cad14346653cShaopeng Jia        // The second number has no country calling code. EXACT_MATCH is no longer possible.
309474aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia        // We parse it as if the region was the same as that for the first number, and if
309574aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia        // EXACT_MATCH is returned, we replace this with NSN_MATCH.
309674aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia        String firstNumberRegion = getRegionCodeForCountryCode(firstNumber.getCountryCode());
309774aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia        try {
309874aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia          if (!firstNumberRegion.equals(UNKNOWN_REGION)) {
309974aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia            PhoneNumber secondNumberWithFirstNumberRegion = parse(secondNumber, firstNumberRegion);
310074aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia            MatchType match = isNumberMatch(firstNumber, secondNumberWithFirstNumberRegion);
310174aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia            if (match == MatchType.EXACT_MATCH) {
310274aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia              return MatchType.NSN_MATCH;
310374aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia            }
310474aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia            return match;
310574aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia          } else {
3106372bff8dd464574d36737d47e495cad14346653cShaopeng Jia            // If the first number didn't have a valid country calling code, then we parse the
3107372bff8dd464574d36737d47e495cad14346653cShaopeng Jia            // second number without one as well.
310874aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia            PhoneNumber secondNumberProto = new PhoneNumber();
310974aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia            parseHelper(secondNumber, null, false, false, secondNumberProto);
311074aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia            return isNumberMatch(firstNumber, secondNumberProto);
311174aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia          }
311274aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia        } catch (NumberParseException e2) {
311374aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia          // Fall-through to return NOT_A_NUMBER.
311474aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia        }
311574aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia      }
311674aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia    }
311774aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia    // One or more of the phone numbers we are trying to match is not a viable phone number.
311874aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia    return MatchType.NOT_A_NUMBER;
311974aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia  }
312074aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia
312174aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia  /**
3122528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia   * Returns true if the number can be dialled from outside the region, or unknown. If the number
3123528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia   * can only be dialled from within the region, returns false. Does not check the number is a valid
31247a81979b0076f18b31b47b7df2beac29735f3a37Cecilia Roes   * number. Note that, at the moment, this method does not handle short numbers.
3125528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia   * TODO: Make this method public when we have enough metadata to make it worthwhile.
312674aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia   *
3127528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia   * @param number  the phone-number for which we want to know whether it is diallable from
3128528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia   *     outside the region
312974aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia   */
3130528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia  // @VisibleForTesting
313174aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia  boolean canBeInternationallyDialled(PhoneNumber number) {
3132203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    PhoneMetadata metadata = getMetadataForRegion(getRegionCodeForNumber(number));
3133203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    if (metadata == null) {
3134528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia      // Note numbers belonging to non-geographical entities (e.g. +800 numbers) are always
3135528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia      // internationally diallable, and will be caught here.
313674aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia      return true;
313774aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia    }
3138528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    String nationalSignificantNumber = getNationalSignificantNumber(number);
313993399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller    return !isNumberMatchingDesc(nationalSignificantNumber, metadata.getNoInternationalDialling());
31401524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
3141f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia
3142f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia  /**
3143f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia   * Returns true if the supplied region supports mobile number portability. Returns false for
3144f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia   * invalid, unknown or regions that don't support mobile number portability.
3145f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia   *
3146f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia   * @param regionCode  the region for which we want to know whether it supports mobile number
3147f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia   *                    portability or not.
3148f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia   */
3149f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia  public boolean isMobileNumberPortableRegion(String regionCode) {
3150f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia    PhoneMetadata metadata = getMetadataForRegion(regionCode);
3151f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia    if (metadata == null) {
3152f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia      logger.log(Level.WARNING, "Invalid or unknown region code provided: " + regionCode);
3153f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia      return false;
3154f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia    }
315593399cc7a32833de9cb538ef7940eed61a23edcaNeil Fuller    return metadata.isMobileNumberPortableRegion();
3156f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia  }
31571524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia}
3158