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
1793f6965c2c041ac707bf1b3bcf5a3f60e452f421Shaopeng Jiapackage com.android.i18n.phonenumbers;
181524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
1993f6965c2c041ac707bf1b3bcf5a3f60e452f421Shaopeng Jiaimport com.android.i18n.phonenumbers.Phonemetadata.NumberFormat;
2093f6965c2c041ac707bf1b3bcf5a3f60e452f421Shaopeng Jiaimport com.android.i18n.phonenumbers.Phonemetadata.PhoneMetadata;
2193f6965c2c041ac707bf1b3bcf5a3f60e452f421Shaopeng Jiaimport com.android.i18n.phonenumbers.Phonemetadata.PhoneMetadataCollection;
2293f6965c2c041ac707bf1b3bcf5a3f60e452f421Shaopeng Jiaimport com.android.i18n.phonenumbers.Phonemetadata.PhoneNumberDesc;
2393f6965c2c041ac707bf1b3bcf5a3f60e452f421Shaopeng Jiaimport com.android.i18n.phonenumbers.Phonenumber.PhoneNumber;
2493f6965c2c041ac707bf1b3bcf5a3f60e452f421Shaopeng Jiaimport com.android.i18n.phonenumbers.Phonenumber.PhoneNumber.CountryCodeSource;
251524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
261524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jiaimport java.io.IOException;
2752699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jiaimport java.io.InputStream;
28f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jiaimport java.io.ObjectInput;
295724d94f83d41d33bfdf9fdbaddbfebb1a0e77f0Shaopeng Jiaimport java.io.ObjectInputStream;
304b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jiaimport java.util.ArrayList;
311524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jiaimport java.util.Arrays;
321524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jiaimport java.util.Collections;
331524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jiaimport java.util.HashMap;
341524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jiaimport java.util.HashSet;
3552699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jiaimport java.util.Iterator;
361524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jiaimport java.util.List;
371524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jiaimport java.util.Map;
381524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jiaimport java.util.Set;
391524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jiaimport java.util.logging.Level;
401524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jiaimport java.util.logging.Logger;
411524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jiaimport java.util.regex.Matcher;
421524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jiaimport java.util.regex.Pattern;
431524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
441524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia/**
451524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia * Utility for international phone numbers. Functionality includes formatting, parsing and
461524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia * validation.
471524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia *
48372bff8dd464574d36737d47e495cad14346653cShaopeng Jia * <p>If you use this library, and want to be notified about important changes, please sign up to
49372bff8dd464574d36737d47e495cad14346653cShaopeng Jia * our <a href="http://groups.google.com/group/libphonenumber-discuss/about">mailing list</a>.
50372bff8dd464574d36737d47e495cad14346653cShaopeng Jia *
51d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia * NOTE: A lot of methods in this class require Region Code strings. These must be provided using
52d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia * ISO 3166-1 two-letter country-code format. These should be in upper-case. The list of the codes
53bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia * can be found here:
54bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia * http://www.iso.org/iso/country_codes/iso_3166_code_lists/country_names_and_code_elements.htm
55d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia *
561524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia * @author Shaopeng Jia
571524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia */
581524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jiapublic class PhoneNumberUtil {
599ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia  // @VisibleForTesting
609ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia  static final MetadataLoader DEFAULT_METADATA_LOADER = new MetadataLoader() {
619ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia    public InputStream loadMetadata(String metadataFileName) {
629ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia      return PhoneNumberUtil.class.getResourceAsStream(metadataFileName);
639ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia    }
649ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia  };
659ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia
66bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia  private static final Logger logger = Logger.getLogger(PhoneNumberUtil.class.getName());
67bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia
6874aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia  /** Flags to use when compiling regular expressions for phone numbers. */
6974aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia  static final int REGEX_FLAGS = Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE;
707900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia  // The minimum and maximum length of the national significant number.
71bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia  private static final int MIN_LENGTH_FOR_NSN = 2;
72ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia  // The ITU says the maximum length should be 15, but we have found longer numbers in Germany.
73b03a14984ad9b0d8b88337ca714cb831233b99c3Shaopeng Jia  static final int MAX_LENGTH_FOR_NSN = 17;
74372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  // The maximum length of the country calling code.
7574aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia  static final int MAX_LENGTH_COUNTRY_CODE = 3;
76b0e21c22b1ca6b9aeb1426924cdf42a221c3d416Shaopeng Jia  // We don't allow input strings for parsing to be longer than 250 chars. This prevents malicious
77b0e21c22b1ca6b9aeb1426924cdf42a221c3d416Shaopeng Jia  // input from overflowing the regular-expression engine.
78b0e21c22b1ca6b9aeb1426924cdf42a221c3d416Shaopeng Jia  private static final int MAX_INPUT_STRING_LENGTH = 250;
799ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia
809ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia  private static final String META_DATA_FILE_PREFIX =
818a26ae2f2ce661b8d90c93eb62899abe8df408adShaopeng Jia      "/com/android/i18n/phonenumbers/data/PhoneNumberMetadataProto";
821524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
8374aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia  // Region-code for the unknown region.
8474aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia  private static final String UNKNOWN_REGION = "ZZ";
85be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia
861524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  private static final int NANPA_COUNTRY_CODE = 1;
871524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
88ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia  // The prefix that needs to be inserted in front of a Colombian landline number when dialed from
89ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia  // a mobile phone in Colombia.
90ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia  private static final String COLOMBIA_MOBILE_TO_FIXED_LINE_PREFIX = "3";
91ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia
92f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia  // Map of country calling codes that use a mobile token before the area code. One example of when
93f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia  // this is relevant is when determining the length of the national destination code, which should
94f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia  // be the length of the area code plus the length of the mobile token.
95f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia  private static final Map<Integer, String> MOBILE_TOKEN_MAPPINGS;
96f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia
971524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  // The PLUS_SIGN signifies the international prefix.
981524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  static final char PLUS_SIGN = '+';
991524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
100cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia  private static final char STAR_SIGN = '*';
101cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia
102372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  private static final String RFC3966_EXTN_PREFIX = ";ext=";
103b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia  private static final String RFC3966_PREFIX = "tel:";
104bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia  private static final String RFC3966_PHONE_CONTEXT = ";phone-context=";
105bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia  private static final String RFC3966_ISDN_SUBADDRESS = ";isub=";
106372bff8dd464574d36737d47e495cad14346653cShaopeng Jia
10796a7214cdabf08f53f5b1a560304601c9f65e0b9Shaopeng Jia  // A map that contains characters that are essential when dialling. That means any of the
108203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia  // characters in this map must not be removed from a number when dialling, otherwise the call
109203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia  // will not reach the intended destination.
11096a7214cdabf08f53f5b1a560304601c9f65e0b9Shaopeng Jia  private static final Map<Character, Character> DIALLABLE_CHAR_MAPPINGS;
11196a7214cdabf08f53f5b1a560304601c9f65e0b9Shaopeng Jia
1121524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  // Only upper-case variants of alpha characters are stored.
113be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia  private static final Map<Character, Character> ALPHA_MAPPINGS;
1141524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
1151524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  // For performance reasons, amalgamate both into one map.
116d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia  private static final Map<Character, Character> ALPHA_PHONE_MAPPINGS;
117be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia
118372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  // Separate map of all symbols that we wish to retain when formatting alpha numbers. This
119372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  // includes digits, ASCII letters and number grouping symbols such as "-" and " ".
120372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  private static final Map<Character, Character> ALL_PLUS_NUMBER_GROUPING_SYMBOLS;
121372bff8dd464574d36737d47e495cad14346653cShaopeng Jia
122be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia  static {
123f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia    HashMap<Integer, String> mobileTokenMap = new HashMap<Integer, String>();
124f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia    mobileTokenMap.put(52, "1");
125f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia    mobileTokenMap.put(54, "9");
126f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia    MOBILE_TOKEN_MAPPINGS = Collections.unmodifiableMap(mobileTokenMap);
127f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia
128d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia    // Simple ASCII digits map used to populate ALPHA_PHONE_MAPPINGS and
129372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    // ALL_PLUS_NUMBER_GROUPING_SYMBOLS.
130372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    HashMap<Character, Character> asciiDigitMappings = new HashMap<Character, Character>();
131372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    asciiDigitMappings.put('0', '0');
132372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    asciiDigitMappings.put('1', '1');
133372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    asciiDigitMappings.put('2', '2');
134372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    asciiDigitMappings.put('3', '3');
135372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    asciiDigitMappings.put('4', '4');
136372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    asciiDigitMappings.put('5', '5');
137372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    asciiDigitMappings.put('6', '6');
138372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    asciiDigitMappings.put('7', '7');
139372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    asciiDigitMappings.put('8', '8');
140372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    asciiDigitMappings.put('9', '9');
141372bff8dd464574d36737d47e495cad14346653cShaopeng Jia
142be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    HashMap<Character, Character> alphaMap = new HashMap<Character, Character>(40);
143be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    alphaMap.put('A', '2');
144be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    alphaMap.put('B', '2');
145be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    alphaMap.put('C', '2');
146be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    alphaMap.put('D', '3');
147be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    alphaMap.put('E', '3');
148be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    alphaMap.put('F', '3');
149be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    alphaMap.put('G', '4');
150be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    alphaMap.put('H', '4');
151be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    alphaMap.put('I', '4');
152be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    alphaMap.put('J', '5');
153be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    alphaMap.put('K', '5');
154be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    alphaMap.put('L', '5');
155be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    alphaMap.put('M', '6');
156be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    alphaMap.put('N', '6');
157be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    alphaMap.put('O', '6');
158be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    alphaMap.put('P', '7');
159be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    alphaMap.put('Q', '7');
160be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    alphaMap.put('R', '7');
161be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    alphaMap.put('S', '7');
162be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    alphaMap.put('T', '8');
163be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    alphaMap.put('U', '8');
164be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    alphaMap.put('V', '8');
165be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    alphaMap.put('W', '9');
166be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    alphaMap.put('X', '9');
167be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    alphaMap.put('Y', '9');
168be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    alphaMap.put('Z', '9');
169be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    ALPHA_MAPPINGS = Collections.unmodifiableMap(alphaMap);
170be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia
171be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    HashMap<Character, Character> combinedMap = new HashMap<Character, Character>(100);
172d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia    combinedMap.putAll(ALPHA_MAPPINGS);
173d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia    combinedMap.putAll(asciiDigitMappings);
174d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia    ALPHA_PHONE_MAPPINGS = Collections.unmodifiableMap(combinedMap);
1751524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
17696a7214cdabf08f53f5b1a560304601c9f65e0b9Shaopeng Jia    HashMap<Character, Character> diallableCharMap = new HashMap<Character, Character>();
17796a7214cdabf08f53f5b1a560304601c9f65e0b9Shaopeng Jia    diallableCharMap.putAll(asciiDigitMappings);
178bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia    diallableCharMap.put(PLUS_SIGN, PLUS_SIGN);
17996a7214cdabf08f53f5b1a560304601c9f65e0b9Shaopeng Jia    diallableCharMap.put('*', '*');
18096a7214cdabf08f53f5b1a560304601c9f65e0b9Shaopeng Jia    DIALLABLE_CHAR_MAPPINGS = Collections.unmodifiableMap(diallableCharMap);
18196a7214cdabf08f53f5b1a560304601c9f65e0b9Shaopeng Jia
182372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    HashMap<Character, Character> allPlusNumberGroupings = new HashMap<Character, Character>();
183372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    // Put (lower letter -> upper letter) and (upper letter -> upper letter) mappings.
184372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    for (char c : ALPHA_MAPPINGS.keySet()) {
185372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      allPlusNumberGroupings.put(Character.toLowerCase(c), c);
186372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      allPlusNumberGroupings.put(c, c);
187372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    }
188372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    allPlusNumberGroupings.putAll(asciiDigitMappings);
189372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    // Put grouping symbols.
190372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    allPlusNumberGroupings.put('-', '-');
191372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    allPlusNumberGroupings.put('\uFF0D', '-');
192372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    allPlusNumberGroupings.put('\u2010', '-');
193372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    allPlusNumberGroupings.put('\u2011', '-');
194372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    allPlusNumberGroupings.put('\u2012', '-');
195372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    allPlusNumberGroupings.put('\u2013', '-');
196372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    allPlusNumberGroupings.put('\u2014', '-');
197372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    allPlusNumberGroupings.put('\u2015', '-');
198372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    allPlusNumberGroupings.put('\u2212', '-');
199372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    allPlusNumberGroupings.put('/', '/');
200372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    allPlusNumberGroupings.put('\uFF0F', '/');
201372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    allPlusNumberGroupings.put(' ', ' ');
202372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    allPlusNumberGroupings.put('\u3000', ' ');
203372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    allPlusNumberGroupings.put('\u2060', ' ');
204372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    allPlusNumberGroupings.put('.', '.');
205372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    allPlusNumberGroupings.put('\uFF0E', '.');
206372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    ALL_PLUS_NUMBER_GROUPING_SYMBOLS = Collections.unmodifiableMap(allPlusNumberGroupings);
207372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  }
208372bff8dd464574d36737d47e495cad14346653cShaopeng Jia
209372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  // Pattern that makes it easy to distinguish whether a region has a unique international dialing
210372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  // prefix or not. If a region has a unique international prefix (e.g. 011 in USA), it will be
2111524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  // represented as a string that contains a sequence of ASCII digits. If there are multiple
212372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  // available international prefixes in a region, they will be represented as a regex string that
2131524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  // always contains character(s) other than ASCII digits.
2141524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  // Note this regex also includes tilde, which signals waiting for the tone.
2151524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  private static final Pattern UNIQUE_INTERNATIONAL_PREFIX =
2167900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia      Pattern.compile("[\\d]+(?:[~\u2053\u223C\uFF5E][\\d]+)?");
2171524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
2181524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  // Regular expression of acceptable punctuation found in phone numbers. This excludes punctuation
2191524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  // found as a leading character only.
2201524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  // This consists of dash characters, white space characters, full stops, slashes,
2211524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  // square brackets, parentheses and tildes. It also includes the letter 'x' as that is found as a
222d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia  // placeholder for carrier information in some phone numbers. Full-width variants are also
223d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia  // present.
22474aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia  static final String VALID_PUNCTUATION = "-x\u2010-\u2015\u2212\u30FC\uFF0D-\uFF0F " +
225bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia      "\u00A0\u00AD\u200B\u2060\u3000()\uFF08\uFF09\uFF3B\uFF3D.\\[\\]/~\u2053\u223C\uFF5E";
2261524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
227d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia  private static final String DIGITS = "\\p{Nd}";
2281524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  // We accept alpha characters in phone numbers, ASCII only, upper and lower case.
2291524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  private static final String VALID_ALPHA =
23074aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia      Arrays.toString(ALPHA_MAPPINGS.keySet().toArray()).replaceAll("[, \\[\\]]", "") +
23174aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia      Arrays.toString(ALPHA_MAPPINGS.keySet().toArray()).toLowerCase().replaceAll("[, \\[\\]]", "");
23274aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia  static final String PLUS_CHARS = "+\uFF0B";
23316b56da4e787a614d16bedcd02b5086d40efbbdbShaopeng Jia  static final Pattern PLUS_CHARS_PATTERN = Pattern.compile("[" + PLUS_CHARS + "]+");
234372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  private static final Pattern SEPARATOR_PATTERN = Pattern.compile("[" + VALID_PUNCTUATION + "]+");
235d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia  private static final Pattern CAPTURING_DIGIT_PATTERN = Pattern.compile("(" + DIGITS + ")");
2361524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
2371524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  // Regular expression of acceptable characters that may start a phone number for the purposes of
2381524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  // parsing. This allows us to strip away meaningless prefixes to phone numbers that may be
2391524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  // mistakenly given to us. This consists of digits, the plus symbol and arabic-indic digits. This
2401524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  // does not contain alpha characters, although they may be used later in the number. It also does
2411524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  // not include other punctuation, as this will be stripped later during parsing and is of no
2421524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  // information value when parsing a number.
243d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia  private static final String VALID_START_CHAR = "[" + PLUS_CHARS + DIGITS + "]";
24416b56da4e787a614d16bedcd02b5086d40efbbdbShaopeng Jia  private static final Pattern VALID_START_CHAR_PATTERN = Pattern.compile(VALID_START_CHAR);
2451524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
2461524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  // Regular expression of characters typically used to start a second phone number for the purposes
2471524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  // of parsing. This allows us to strip off parts of the number that are actually the start of
2481524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  // another number, such as for: (530) 583-6985 x302/x2303 -> the second extension here makes this
2491524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  // actually two phone numbers, (530) 583-6985 x302 and (530) 583-6985 x2303. We remove the second
2501524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  // extension so that the first number is parsed correctly.
2511524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  private static final String SECOND_NUMBER_START = "[\\\\/] *x";
25274aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia  static final Pattern SECOND_NUMBER_START_PATTERN = Pattern.compile(SECOND_NUMBER_START);
2531524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
2547900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia  // Regular expression of trailing characters that we want to remove. We remove all characters that
2557900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia  // are not alpha or numerical characters. The hash character is retained here, as it may signify
2567900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia  // the previous block was an extension.
2577900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia  private static final String UNWANTED_END_CHARS = "[[\\P{N}&&\\P{L}]&&[^#]]+$";
258372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  static final Pattern UNWANTED_END_CHAR_PATTERN = Pattern.compile(UNWANTED_END_CHARS);
2597900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia
2607900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia  // We use this pattern to check if the phone number has at least three letters in it - if so, then
2617900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia  // we treat it as a number where some phone-number digits are represented by letters.
2627900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia  private static final Pattern VALID_ALPHA_PHONE_PATTERN = Pattern.compile("(?:.*?[A-Za-z]){3}.*");
2637900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia
2641524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  // Regular expression of viable phone numbers. This is location independent. Checks we have at
2651524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  // least three leading digits, and only valid punctuation, alpha characters and
2667900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia  // digits in the phone number. Does not include extension data.
2671524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  // The symbol 'x' is allowed here as valid punctuation since it is often used as a placeholder for
268256a5f71a05ffd182a0fda2cfed6f93345cc889fLara Rennie  // carrier codes, for example in Brazilian phone numbers. We also allow multiple "+" characters at
269256a5f71a05ffd182a0fda2cfed6f93345cc889fLara Rennie  // the start.
2701524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  // Corresponds to the following:
2714b867acb917b73e699a596df94445c634c916519Shaopeng Jia  // [digits]{minLengthNsn}|
272cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia  // plus_sign*(([punctuation]|[star])*[digits]){3,}([punctuation]|[star]|[digits]|[alpha])*
2734b867acb917b73e699a596df94445c634c916519Shaopeng Jia  //
2744b867acb917b73e699a596df94445c634c916519Shaopeng Jia  // The first reg-ex is to allow short numbers (two digits long) to be parsed if they are entered
2754b867acb917b73e699a596df94445c634c916519Shaopeng Jia  // as "15" etc, but only if there is no punctuation in them. The second expression restricts the
2764b867acb917b73e699a596df94445c634c916519Shaopeng Jia  // number of digits to three or more, but then allows them to be in international form, and to
2774b867acb917b73e699a596df94445c634c916519Shaopeng Jia  // have alpha-characters and punctuation.
2784b867acb917b73e699a596df94445c634c916519Shaopeng Jia  //
27974aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia  // Note VALID_PUNCTUATION starts with a -, so must be the first in the range.
2801524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  private static final String VALID_PHONE_NUMBER =
2814b867acb917b73e699a596df94445c634c916519Shaopeng Jia      DIGITS + "{" + MIN_LENGTH_FOR_NSN + "}" + "|" +
282b0e21c22b1ca6b9aeb1426924cdf42a221c3d416Shaopeng Jia      "[" + PLUS_CHARS + "]*+(?:[" + VALID_PUNCTUATION + STAR_SIGN + "]*" + DIGITS + "){3,}[" +
283cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia      VALID_PUNCTUATION + STAR_SIGN + VALID_ALPHA + DIGITS + "]*";
2841524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
2851524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  // Default extension prefix to use when formatting. This will be put in front of any extension
2861524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  // component of the number, after the main national number is formatted. For example, if you wish
2871524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  // the default extension formatting to be " extn: 3456", then you should specify " extn: " here
288372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  // as the default extension prefix. This can be overridden by region-specific preferences.
2891524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  private static final String DEFAULT_EXTN_PREFIX = " ext. ";
2901524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
291f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia  // Pattern to capture digits used in an extension. Places a maximum length of "7" for an
292f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia  // extension.
293f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia  private static final String CAPTURING_EXTN_DIGITS = "(" + DIGITS + "{1,7})";
2941524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  // Regexp of all possible ways to write extensions, for use when parsing. This will be run as a
295372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  // case-insensitive regexp match. Wide character versions are also provided after each ASCII
296f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia  // version.
297f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia  private static final String EXTN_PATTERNS_FOR_PARSING;
298f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia  static final String EXTN_PATTERNS_FOR_MATCHING;
299f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia  static {
300f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia    // One-character symbols that can be used to indicate an extension.
301f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia    String singleExtnSymbolsForMatching = "x\uFF58#\uFF03~\uFF5E";
302f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia    // For parsing, we are slightly more lenient in our interpretation than for matching. Here we
303f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia    // allow a "comma" as a possible extension indicator. When matching, this is hardly ever used to
304f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia    // indicate this.
305f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia    String singleExtnSymbolsForParsing = "," + singleExtnSymbolsForMatching;
306f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia
307f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia    EXTN_PATTERNS_FOR_PARSING = createExtnPattern(singleExtnSymbolsForParsing);
308f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia    EXTN_PATTERNS_FOR_MATCHING = createExtnPattern(singleExtnSymbolsForMatching);
309f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia  }
310f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia
311f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia  /**
312f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia   * Helper initialiser method to create the regular-expression pattern to match extensions,
313f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia   * allowing the one-char extension symbols provided by {@code singleExtnSymbols}.
314f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia   */
315f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia  private static String createExtnPattern(String singleExtnSymbols) {
316f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia    // There are three regular expressions here. The first covers RFC 3966 format, where the
317f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia    // extension is added using ";ext=". The second more generic one starts with optional white
318f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia    // space and ends with an optional full stop (.), followed by zero or more spaces/tabs and then
319f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia    // the numbers themselves. The other one covers the special case of American numbers where the
320f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia    // extension is written with a hash at the end, such as "- 503#".
321f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia    // Note that the only capturing groups should be around the digits that you want to capture as
322f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia    // part of the extension, or else parsing will fail!
323f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia    // Canonical-equivalence doesn't seem to be an option with Android java, so we allow two options
324f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia    // for representing the accented o - the character itself, and one in the unicode decomposed
325f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia    // form with the combining acute accent.
326f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia    return (RFC3966_EXTN_PREFIX + CAPTURING_EXTN_DIGITS + "|" + "[ \u00A0\\t,]*" +
327528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia            "(?:e?xt(?:ensi(?:o\u0301?|\u00F3))?n?|\uFF45?\uFF58\uFF54\uFF4E?|" +
328f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia            "[" + singleExtnSymbols + "]|int|anexo|\uFF49\uFF4E\uFF54)" +
329f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia            "[:\\.\uFF0E]?[ \u00A0\\t,-]*" + CAPTURING_EXTN_DIGITS + "#?|" +
330f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia            "[- ]+(" + DIGITS + "{1,5})#");
331f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia  }
3321524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
333372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  // Regexp of all known extension prefixes used by different regions followed by 1 or more valid
3341524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  // digits, for use when parsing.
3351524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  private static final Pattern EXTN_PATTERN =
336f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia      Pattern.compile("(?:" + EXTN_PATTERNS_FOR_PARSING + ")$", REGEX_FLAGS);
3371524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
3381524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  // We append optionally the extension pattern to the end here, as a valid phone number may
3391524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  // have an extension prefix appended, followed by 1 or more digits.
3401524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  private static final Pattern VALID_PHONE_NUMBER_PATTERN =
341f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia      Pattern.compile(VALID_PHONE_NUMBER + "(?:" + EXTN_PATTERNS_FOR_PARSING + ")?", REGEX_FLAGS);
3421524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
343b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia  static final Pattern NON_DIGITS_PATTERN = Pattern.compile("(\\D+)");
344372bff8dd464574d36737d47e495cad14346653cShaopeng Jia
345372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  // The FIRST_GROUP_PATTERN was originally set to $1 but there are some countries for which the
346372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  // first group is not used in the national pattern (e.g. Argentina) so the $1 group does not match
347372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  // correctly.  Therefore, we use \d, so that the first group actually used in the pattern will be
348372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  // matched.
349372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  private static final Pattern FIRST_GROUP_PATTERN = Pattern.compile("(\\$\\d)");
350be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia  private static final Pattern NP_PATTERN = Pattern.compile("\\$NP");
351be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia  private static final Pattern FG_PATTERN = Pattern.compile("\\$FG");
3524b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia  private static final Pattern CC_PATTERN = Pattern.compile("\\$CC");
353be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia
354203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia  // A pattern that is used to determine if the national prefix formatting rule has the first group
355203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia  // only, i.e., does not start with the national prefix. Note that the pattern explicitly allows
356203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia  // for unbalanced parentheses.
357203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia  private static final Pattern FIRST_GROUP_ONLY_PREFIX_PATTERN = Pattern.compile("\\(?\\$1\\)?");
358203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia
3591524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  private static PhoneNumberUtil instance = null;
3601524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
361528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia  public static final String REGION_CODE_FOR_NON_GEO_ENTITY = "001";
362528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia
3631524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
3641524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * INTERNATIONAL and NATIONAL formats are consistent with the definition in ITU-T Recommendation
365d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   * E123. For example, the number of the Google Switzerland office will be written as
3661524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * "+41 44 668 1800" in INTERNATIONAL format, and as "044 668 1800" in NATIONAL format.
367b0e21c22b1ca6b9aeb1426924cdf42a221c3d416Shaopeng Jia   * E164 format is as per INTERNATIONAL format but with no formatting applied, e.g.
368b0e21c22b1ca6b9aeb1426924cdf42a221c3d416Shaopeng Jia   * "+41446681800". RFC3966 is as per INTERNATIONAL format, but with all spaces and other
369b0e21c22b1ca6b9aeb1426924cdf42a221c3d416Shaopeng Jia   * separating symbols replaced with a hyphen, and with any phone number extension appended with
370b0e21c22b1ca6b9aeb1426924cdf42a221c3d416Shaopeng Jia   * ";ext=". It also will have a prefix of "tel:" added, e.g. "tel:+41-44-668-1800".
3711524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *
3721524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * Note: If you are considering storing the number in a neutral format, you are highly advised to
373372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * use the PhoneNumber class.
3741524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
3751524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  public enum PhoneNumberFormat {
3761524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    E164,
3771524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    INTERNATIONAL,
378372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    NATIONAL,
379372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    RFC3966
3801524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
3811524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
3821524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
3831524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * Type of phone numbers.
3841524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
3851524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  public enum PhoneNumberType {
3861524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    FIXED_LINE,
3871524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    MOBILE,
388372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    // In some regions (e.g. the USA), it is impossible to distinguish between fixed-line and
3891524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    // mobile numbers by looking at the phone number itself.
3901524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    FIXED_LINE_OR_MOBILE,
3911524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    // Freephone lines
3921524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    TOLL_FREE,
3931524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    PREMIUM_RATE,
3941524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    // The cost of this call is shared between the caller and the recipient, and is hence typically
3951524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    // less than PREMIUM_RATE calls. See // http://en.wikipedia.org/wiki/Shared_Cost_Service for
3961524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    // more information.
3971524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    SHARED_COST,
3981524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    // Voice over IP numbers. This includes TSoIP (Telephony Service over IP).
3991524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    VOIP,
4001524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    // A personal number is associated with a particular person, and may be routed to either a
4011524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    // MOBILE or FIXED_LINE number. Some more information can be found here:
4021524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    // http://en.wikipedia.org/wiki/Personal_Numbers
4031524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    PERSONAL_NUMBER,
404b2697412130f6d087dde01fb1a978f7e5840a5faShaopeng Jia    PAGER,
40574aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia    // Used for "Universal Access Numbers" or "Company Numbers". They may be further routed to
40674aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia    // specific offices, but allow one number to be used for a company.
40774aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia    UAN,
408528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    // Used for "Voice Mail Access Numbers".
409528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    VOICEMAIL,
4101524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    // A phone number is of type UNKNOWN when it does not fit any of the known patterns for a
411372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    // specific region.
4121524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    UNKNOWN
4131524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
4141524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
4151524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
4161524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * Types of phone number matches. See detailed description beside the isNumberMatch() method.
4171524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
4181524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  public enum MatchType {
41974aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia    NOT_A_NUMBER,
4201524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    NO_MATCH,
4211524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    SHORT_NSN_MATCH,
4221524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    NSN_MATCH,
4231524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    EXACT_MATCH,
4241524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
4251524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
4261524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
4271524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * Possible outcomes when testing if a PhoneNumber is possible.
4281524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
4291524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  public enum ValidationResult {
4301524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    IS_POSSIBLE,
4311524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    INVALID_COUNTRY_CODE,
4321524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    TOO_SHORT,
4331524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    TOO_LONG,
4341524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
4351524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
4361524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
43752699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia   * Leniency when {@linkplain PhoneNumberUtil#findNumbers finding} potential phone numbers in text
438f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia   * segments. The levels here are ordered in increasing strictness.
43952699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia   */
44052699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia  public enum Leniency {
44152699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia    /**
44296a7214cdabf08f53f5b1a560304601c9f65e0b9Shaopeng Jia     * Phone numbers accepted are {@linkplain PhoneNumberUtil#isPossibleNumber(PhoneNumber)
44396a7214cdabf08f53f5b1a560304601c9f65e0b9Shaopeng Jia     * possible}, but not necessarily {@linkplain PhoneNumberUtil#isValidNumber(PhoneNumber) valid}.
44452699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia     */
44552699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia    POSSIBLE {
44652699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia      @Override
447f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia      boolean verify(PhoneNumber number, String candidate, PhoneNumberUtil util) {
44852699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia        return util.isPossibleNumber(number);
44952699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia      }
45052699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia    },
45152699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia    /**
45296a7214cdabf08f53f5b1a560304601c9f65e0b9Shaopeng Jia     * Phone numbers accepted are {@linkplain PhoneNumberUtil#isPossibleNumber(PhoneNumber)
45396a7214cdabf08f53f5b1a560304601c9f65e0b9Shaopeng Jia     * possible} and {@linkplain PhoneNumberUtil#isValidNumber(PhoneNumber) valid}. Numbers written
454a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia     * in national format must have their national-prefix present if it is usually written for a
455a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia     * number of this type.
45652699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia     */
45752699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia    VALID {
45852699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia      @Override
459f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia      boolean verify(PhoneNumber number, String candidate, PhoneNumberUtil util) {
460a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia        if (!util.isValidNumber(number) ||
461b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia            !PhoneNumberMatcher.containsOnlyValidXChars(number, candidate, util)) {
462f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia          return false;
463f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia        }
464b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia        return PhoneNumberMatcher.isNationalPrefixPresentIfRequired(number, util);
465f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia      }
466f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia    },
467f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia    /**
468f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia     * Phone numbers accepted are {@linkplain PhoneNumberUtil#isValidNumber(PhoneNumber) valid} and
469f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia     * are grouped in a possible way for this locale. For example, a US number written as
470f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia     * "65 02 53 00 00" and "650253 0000" are not accepted at this leniency level, whereas
471f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia     * "650 253 0000", "650 2530000" or "6502530000" are.
472bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia     * Numbers with more than one '/' symbol in the national significant number are also dropped at
473bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia     * this level.
474f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia     * <p>
475f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia     * Warning: This level might result in lower coverage especially for regions outside of country
476f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia     * code "+1". If you are not sure about which level to use, email the discussion group
477f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia     * libphonenumber-discuss@googlegroups.com.
478f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia     */
479f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia    STRICT_GROUPING {
480f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia      @Override
481f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia      boolean verify(PhoneNumber number, String candidate, PhoneNumberUtil util) {
482f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia        if (!util.isValidNumber(number) ||
483b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia            !PhoneNumberMatcher.containsOnlyValidXChars(number, candidate, util) ||
484bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia            PhoneNumberMatcher.containsMoreThanOneSlashInNationalNumber(number, candidate) ||
485b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia            !PhoneNumberMatcher.isNationalPrefixPresentIfRequired(number, util)) {
486f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia          return false;
487f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia        }
488b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia        return PhoneNumberMatcher.checkNumberGroupingIsValid(
489b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia            number, candidate, util, new PhoneNumberMatcher.NumberGroupingChecker() {
490b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia              public boolean checkGroups(PhoneNumberUtil util, PhoneNumber number,
491b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia                                         StringBuilder normalizedCandidate,
492b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia                                         String[] expectedNumberGroups) {
493b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia                return PhoneNumberMatcher.allNumberGroupsRemainGrouped(
494b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia                    util, number, normalizedCandidate, expectedNumberGroups);
495b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia              }
496b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia            });
497f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia      }
498f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia    },
499f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia    /**
500f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia     * Phone numbers accepted are {@linkplain PhoneNumberUtil#isValidNumber(PhoneNumber) valid} and
501f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia     * are grouped in the same way that we would have formatted it, or as a single block. For
502f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia     * example, a US number written as "650 2530000" is not accepted at this leniency level, whereas
503f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia     * "650 253 0000" or "6502530000" are.
504f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia     * Numbers with more than one '/' symbol are also dropped at this level.
505f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia     * <p>
506f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia     * Warning: This level might result in lower coverage especially for regions outside of country
507f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia     * code "+1". If you are not sure about which level to use, email the discussion group
508f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia     * libphonenumber-discuss@googlegroups.com.
509f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia     */
510f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia    EXACT_GROUPING {
511f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia      @Override
512f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia      boolean verify(PhoneNumber number, String candidate, PhoneNumberUtil util) {
513f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia        if (!util.isValidNumber(number) ||
514b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia            !PhoneNumberMatcher.containsOnlyValidXChars(number, candidate, util) ||
515bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia            PhoneNumberMatcher.containsMoreThanOneSlashInNationalNumber(number, candidate) ||
516b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia            !PhoneNumberMatcher.isNationalPrefixPresentIfRequired(number, util)) {
517f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia          return false;
518f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia        }
519b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia        return PhoneNumberMatcher.checkNumberGroupingIsValid(
520b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia            number, candidate, util, new PhoneNumberMatcher.NumberGroupingChecker() {
521b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia              public boolean checkGroups(PhoneNumberUtil util, PhoneNumber number,
522b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia                                         StringBuilder normalizedCandidate,
523b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia                                         String[] expectedNumberGroups) {
524b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia                return PhoneNumberMatcher.allNumberGroupsAreExactlyPresent(
525b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia                    util, number, normalizedCandidate, expectedNumberGroups);
526b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia              }
527b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia            });
52852699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia      }
52952699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia    };
53052699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia
53152699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia    /** Returns true if {@code number} is a verified number according to this leniency. */
532f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia    abstract boolean verify(PhoneNumber number, String candidate, PhoneNumberUtil util);
53352699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia  }
53452699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia
5353396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia  // A mapping from a country calling code to the region codes which denote the region represented
5363396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia  // by that country calling code. In the case of multiple regions sharing a calling code, such as
5373396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia  // the NANPA regions, the one indicated with "isMainCountryForCode" in the metadata should be
5383396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia  // first.
5393396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia  private final Map<Integer, List<String>> countryCallingCodeToRegionCodeMap;
5403396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia
5413396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia  // The set of regions that share country calling code 1.
5428777f1913d34c3ecf72164ea85292e978e265eddShaopeng Jia  // There are roughly 26 regions.
5438777f1913d34c3ecf72164ea85292e978e265eddShaopeng Jia  // We set the initial capacity of the HashSet to 35 to offer a load factor of roughly 0.75.
5443396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia  private final Set<String> nanpaRegions = new HashSet<String>(35);
5453396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia
5463396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia  // A mapping from a region code to the PhoneMetadata for that region.
5473396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia  // Note: Synchronization, though only needed for the Android version of the library, is used in
5483396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia  // all versions for consistency.
5493396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia  private final Map<String, PhoneMetadata> regionToMetadataMap =
5503396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia      Collections.synchronizedMap(new HashMap<String, PhoneMetadata>());
5513396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia
5523396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia  // A mapping from a country calling code for a non-geographical entity to the PhoneMetadata for
5533396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia  // that country calling code. Examples of the country calling codes include 800 (International
5543396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia  // Toll Free Service) and 808 (International Shared Cost Service).
5553396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia  // Note: Synchronization, though only needed for the Android version of the library, is used in
5563396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia  // all versions for consistency.
5573396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia  private final Map<Integer, PhoneMetadata> countryCodeToNonGeographicalMetadataMap =
5583396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia      Collections.synchronizedMap(new HashMap<Integer, PhoneMetadata>());
5593396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia
5603396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia  // A cache for frequently used region-specific regular expressions.
5613396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia  // The initial capacity is set to 100 as this seems to be an optimal value for Android, based on
5623396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia  // performance measurements.
5633396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia  private final RegexCache regexCache = new RegexCache(100);
5643396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia
5653396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia  // The set of regions the library supports.
5663396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia  // There are roughly 240 of them and we set the initial capacity of the HashSet to 320 to offer a
5673396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia  // load factor of roughly 0.75.
5683396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia  private final Set<String> supportedRegions = new HashSet<String>(320);
5693396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia
5703396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia  // The set of county calling codes that map to the non-geo entity region ("001"). This set
5713396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia  // currently contains < 12 elements so the default capacity of 16 (load factor=0.75) is fine.
5723396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia  private final Set<Integer> countryCodesForNonGeographicalRegion = new HashSet<Integer>();
5733396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia
5743396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia  // The prefix of the metadata files from which region data is loaded.
5753396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia  private final String currentFilePrefix;
5769ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia  // The metadata loader used to inject alternative metadata sources.
5779ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia  private final MetadataLoader metadataLoader;
5783396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia
57952699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia  /**
5808777f1913d34c3ecf72164ea85292e978e265eddShaopeng Jia   * This class implements a singleton, the constructor is only visible to facilitate testing.
5811524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
5829ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia  // @VisibleForTesting
5839ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia  PhoneNumberUtil(String filePrefix, MetadataLoader metadataLoader,
5843396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia      Map<Integer, List<String>> countryCallingCodeToRegionCodeMap) {
5853396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia    this.currentFilePrefix = filePrefix;
5869ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia    this.metadataLoader = metadataLoader;
5873396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia    this.countryCallingCodeToRegionCodeMap = countryCallingCodeToRegionCodeMap;
588203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    for (Map.Entry<Integer, List<String>> entry : countryCallingCodeToRegionCodeMap.entrySet()) {
589203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia      List<String> regionCodes = entry.getValue();
590203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia      // We can assume that if the county calling code maps to the non-geo entity region code then
591203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia      // that's the only region code it maps to.
592203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia      if (regionCodes.size() == 1 && REGION_CODE_FOR_NON_GEO_ENTITY.equals(regionCodes.get(0))) {
593203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia        // This is the subset of all country codes that map to the non-geo entity region code.
594203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia        countryCodesForNonGeographicalRegion.add(entry.getKey());
595203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia      } else {
596203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia        // The supported regions set does not include the "001" non-geo entity region code.
597203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia        supportedRegions.addAll(regionCodes);
598203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia      }
599203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    }
600203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    // If the non-geo entity still got added to the set of supported regions it must be because
601203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    // there are entries that list the non-geo entity alongside normal regions (which is wrong).
602203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    // If we discover this, remove the non-geo entity from the set of supported regions and log.
603203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    if (supportedRegions.remove(REGION_CODE_FOR_NON_GEO_ENTITY)) {
604bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia      logger.log(Level.WARNING, "invalid metadata " +
605203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia          "(country calling code was mapped to the non-geo entity as well as specific region(s))");
606fa42140081949568565af7dc8c22f0600ad90a8aShaopeng Jia    }
607372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    nanpaRegions.addAll(countryCallingCodeToRegionCodeMap.get(NANPA_COUNTRY_CODE));
608fa42140081949568565af7dc8c22f0600ad90a8aShaopeng Jia  }
609fa42140081949568565af7dc8c22f0600ad90a8aShaopeng Jia
610203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia  // @VisibleForTesting
6119ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia  void loadMetadataFromFile(String filePrefix, String regionCode, int countryCallingCode,
6129ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia      MetadataLoader metadataLoader) {
613528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    boolean isNonGeoRegion = REGION_CODE_FOR_NON_GEO_ENTITY.equals(regionCode);
614203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    String fileName = filePrefix + "_" +
615203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia        (isNonGeoRegion ? String.valueOf(countryCallingCode) : regionCode);
6169ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia    InputStream source = metadataLoader.loadMetadata(fileName);
617203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    if (source == null) {
618bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia      logger.log(Level.SEVERE, "missing metadata: " + fileName);
6193396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia      throw new IllegalStateException("missing metadata: " + fileName);
620203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    }
621507cdd3f40be5346cfd0681239b5dc81abc57d9bShaopeng Jia    ObjectInputStream in = null;
6221524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    try {
623fa42140081949568565af7dc8c22f0600ad90a8aShaopeng Jia      in = new ObjectInputStream(source);
624f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia      PhoneMetadataCollection metadataCollection = loadMetadataAndCloseInput(in);
625203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia      List<PhoneMetadata> metadataList = metadataCollection.getMetadataList();
626203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia      if (metadataList.isEmpty()) {
627bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia        logger.log(Level.SEVERE, "empty metadata: " + fileName);
6283396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia        throw new IllegalStateException("empty metadata: " + fileName);
629203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia      }
630203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia      if (metadataList.size() > 1) {
631bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia        logger.log(Level.WARNING, "invalid metadata (too many entries): " + fileName);
632203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia      }
633203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia      PhoneMetadata metadata = metadataList.get(0);
634203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia      if (isNonGeoRegion) {
635203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia        countryCodeToNonGeographicalMetadataMap.put(countryCallingCode, metadata);
636203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia      } else {
637203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia        regionToMetadataMap.put(regionCode, metadata);
6381524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      }
6391524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    } catch (IOException e) {
640bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia      logger.log(Level.SEVERE, "cannot load/parse metadata: " + fileName, e);
641203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia      throw new RuntimeException("cannot load/parse metadata: " + fileName, e);
642507cdd3f40be5346cfd0681239b5dc81abc57d9bShaopeng Jia    }
643507cdd3f40be5346cfd0681239b5dc81abc57d9bShaopeng Jia  }
644507cdd3f40be5346cfd0681239b5dc81abc57d9bShaopeng Jia
645f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia  /**
646f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia   * Loads the metadata protocol buffer from the given stream and closes the stream afterwards. Any
647f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia   * exceptions that occur while reading the stream are propagated (though exceptions that occur
648f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia   * when the stream is closed will be ignored).
649f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia   *
650f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia   * @param source  the non-null stream from which metadata is to be read.
651f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia   * @return        the loaded metadata protocol buffer.
652f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia   */
6539ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia  private static PhoneMetadataCollection loadMetadataAndCloseInput(ObjectInputStream source) {
654f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia    PhoneMetadataCollection metadataCollection = new PhoneMetadataCollection();
655f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia    try {
656f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia      metadataCollection.readExternal(source);
657f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia    } catch (IOException e) {
658f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia      logger.log(Level.WARNING, "error reading input (ignored)", e);
659f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia    } finally {
660507cdd3f40be5346cfd0681239b5dc81abc57d9bShaopeng Jia      try {
661f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia        source.close();
662507cdd3f40be5346cfd0681239b5dc81abc57d9bShaopeng Jia      } catch (IOException e) {
663bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia        logger.log(Level.WARNING, "error closing input stream (ignored)", e);
664f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia      } finally {
665f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia        return metadataCollection;
666507cdd3f40be5346cfd0681239b5dc81abc57d9bShaopeng Jia      }
6671524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
6681524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
6691524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
6701524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
6711524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * Attempts to extract a possible number from the string passed in. This currently strips all
672372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * leading characters that cannot be used to start a phone number. Characters that can be used to
673372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * start a phone number are defined in the VALID_START_CHAR_PATTERN. If none of these characters
674372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * are found in the number passed in, an empty string is returned. This function also attempts to
675372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * strip off any alternative extensions or endings if two or more are present, such as in the case
676372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * of: (530) 583-6985 x302/x2303. The second extension here makes this actually two phone numbers,
677372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * (530) 583-6985 x302 and (530) 583-6985 x2303. We remove the second extension so that the first
678372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * number is parsed correctly.
6791524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *
6801524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @param number  the string that might contain a phone number
6811524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @return        the number, stripped of any non-phone-number prefix (such as "Tel:") or an empty
6821524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *                string if no character used to start phone numbers (such as + or any digit) is
6831524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *                found in the number
6841524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
6851524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  static String extractPossibleNumber(String number) {
6861524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    Matcher m = VALID_START_CHAR_PATTERN.matcher(number);
6871524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    if (m.find()) {
6881524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      number = number.substring(m.start());
6894b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia      // Remove trailing non-alpha non-numerical characters.
6904b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia      Matcher trailingCharsMatcher = UNWANTED_END_CHAR_PATTERN.matcher(number);
6914b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia      if (trailingCharsMatcher.find()) {
6924b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia        number = number.substring(0, trailingCharsMatcher.start());
693bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia        logger.log(Level.FINER, "Stripped trailing characters: " + number);
6944b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia      }
6951524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      // Check for extra numbers at the end.
6961524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      Matcher secondNumber = SECOND_NUMBER_START_PATTERN.matcher(number);
6971524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      if (secondNumber.find()) {
6981524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia        number = number.substring(0, secondNumber.start());
6991524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      }
7001524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      return number;
7011524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    } else {
7021524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      return "";
7031524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
7041524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
7051524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
7061524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
7071524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * Checks to see if the string of characters could possibly be a phone number at all. At the
708bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia   * moment, checks to see that the string begins with at least 2 digits, ignoring any punctuation
7091524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * commonly found in phone numbers.
7101524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * This method does not require the number to be normalized in advance - but does assume that
7111524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * leading non-number symbols have been removed, such as by the method extractPossibleNumber.
7121524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *
7131524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @param number  string to be checked for viability as a phone number
7141524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @return        true if the number could be a phone number of some sort, otherwise false
7151524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
716ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia  // @VisibleForTesting
7171524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  static boolean isViablePhoneNumber(String number) {
7181524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    if (number.length() < MIN_LENGTH_FOR_NSN) {
7191524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      return false;
7201524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
7211524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    Matcher m = VALID_PHONE_NUMBER_PATTERN.matcher(number);
7221524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    return m.matches();
7231524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
7241524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
7251524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
7261524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * Normalizes a string of characters representing a phone number. This performs the following
7271524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * conversions:
728d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   *   Punctuation is stripped.
729d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   *   For ALPHA/VANITY numbers:
7301524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *   Letters are converted to their numeric representation on a telephone keypad. The keypad
7311524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *       used here is the one defined in ITU Recommendation E.161. This is only done if there are
732d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   *       3 or more letters in the number, to lessen the risk that such letters are typos.
733d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   *   For other numbers:
734d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   *   Wide-ascii digits are converted to normal ASCII (European) digits.
7351524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *   Arabic-Indic numerals are converted to European numerals.
736d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   *   Spurious alpha characters are stripped.
7371524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *
7381524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @param number  a string of characters representing a phone number
7391524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @return        the normalized string version of the phone number
7401524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
7411524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  static String normalize(String number) {
7427900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia    Matcher m = VALID_ALPHA_PHONE_PATTERN.matcher(number);
7437900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia    if (m.matches()) {
744d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia      return normalizeHelper(number, ALPHA_PHONE_MAPPINGS, true);
7451524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    } else {
746d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia      return normalizeDigitsOnly(number);
7471524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
7481524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
7491524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
7501524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
7511524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * Normalizes a string of characters representing a phone number. This is a wrapper for
752372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * normalize(String number) but does in-place normalization of the StringBuilder provided.
7531524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *
754372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * @param number  a StringBuilder of characters representing a phone number that will be
755372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *     normalized in place
7561524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
757372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  static void normalize(StringBuilder number) {
7581524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    String normalizedNumber = normalize(number.toString());
7591524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    number.replace(0, number.length(), normalizedNumber);
7601524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
7611524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
7621524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
7631524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * Normalizes a string of characters representing a phone number. This converts wide-ascii and
7647900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia   * arabic-indic numerals to European numerals, and strips punctuation and alpha characters.
7651524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *
7661524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @param number  a string of characters representing a phone number
7671524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @return        the normalized string version of the phone number
7681524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
7691524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  public static String normalizeDigitsOnly(String number) {
770f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia    return normalizeDigits(number, false /* strip non-digits */).toString();
771f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia  }
772f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia
773b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia  static StringBuilder normalizeDigits(String number, boolean keepNonDigits) {
774f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia    StringBuilder normalizedDigits = new StringBuilder(number.length());
775f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia    for (char c : number.toCharArray()) {
776f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia      int digit = Character.digit(c, 10);
777f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia      if (digit != -1) {
778f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia        normalizedDigits.append(digit);
779f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia      } else if (keepNonDigits) {
780f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia        normalizedDigits.append(c);
781d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia      }
782d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia    }
783f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia    return normalizedDigits;
7841524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
7851524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
7861524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
787bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia   * Normalizes a string of characters representing a phone number. This strips all characters which
788bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia   * are not diallable on a mobile phone keypad (including all non-ASCII digits).
789bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia   *
790bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia   * @param number  a string of characters representing a phone number
791bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia   * @return        the normalized string version of the phone number
792bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia   */
793bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia  static String normalizeDiallableCharsOnly(String number) {
794bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia    return normalizeHelper(number, DIALLABLE_CHAR_MAPPINGS, true /* remove non matches */);
795bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia  }
796bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia
797bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia  /**
7981524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * Converts all alpha characters in a number to their respective digits on a keypad, but retains
799d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   * existing formatting.
8001524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
8011524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  public static String convertAlphaCharactersInNumber(String number) {
802d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia    return normalizeHelper(number, ALPHA_PHONE_MAPPINGS, false);
8031524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
8041524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
8051524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
8068777f1913d34c3ecf72164ea85292e978e265eddShaopeng Jia   * Gets the length of the geographical area code from the
8078777f1913d34c3ecf72164ea85292e978e265eddShaopeng Jia   * PhoneNumber object passed in, so that clients could use it
8088777f1913d34c3ecf72164ea85292e978e265eddShaopeng Jia   * to split a national significant number into geographical area code and subscriber number. It
8098777f1913d34c3ecf72164ea85292e978e265eddShaopeng Jia   * works in such a way that the resultant subscriber number should be diallable, at least on some
8108777f1913d34c3ecf72164ea85292e978e265eddShaopeng Jia   * devices. An example of how this could be used:
8115c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia   *
812372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * <pre>
813df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia   * PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
814b2697412130f6d087dde01fb1a978f7e5840a5faShaopeng Jia   * PhoneNumber number = phoneUtil.parse("16502530000", "US");
815372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * String nationalSignificantNumber = phoneUtil.getNationalSignificantNumber(number);
8165c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia   * String areaCode;
8175c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia   * String subscriberNumber;
8185c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia   *
8195c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia   * int areaCodeLength = phoneUtil.getLengthOfGeographicalAreaCode(number);
8205c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia   * if (areaCodeLength > 0) {
8215c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia   *   areaCode = nationalSignificantNumber.substring(0, areaCodeLength);
8225c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia   *   subscriberNumber = nationalSignificantNumber.substring(areaCodeLength);
8235c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia   * } else {
8245c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia   *   areaCode = "";
8255c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia   *   subscriberNumber = nationalSignificantNumber;
8265c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia   * }
827372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * </pre>
8285c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia   *
8295c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia   * N.B.: area code is a very ambiguous concept, so the I18N team generally recommends against
830d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   * using it for most purposes, but recommends using the more general {@code national_number}
831d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   * instead. Read the following carefully before deciding to use this method:
832d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   * <ul>
833d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   *  <li> geographical area codes change over time, and this method honors those changes;
834d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   *    therefore, it doesn't guarantee the stability of the result it produces.
835d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   *  <li> subscriber numbers may not be diallable from all devices (notably mobile devices, which
836d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   *    typically requires the full national_number to be dialled in most regions).
837528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia   *  <li> most non-geographical numbers have no area codes, including numbers from non-geographical
838528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia   *    entities
839d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   *  <li> some geographical numbers have no area codes.
840d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   * </ul>
8418777f1913d34c3ecf72164ea85292e978e265eddShaopeng Jia   * @param number  the PhoneNumber object for which clients
8428777f1913d34c3ecf72164ea85292e978e265eddShaopeng Jia   *     want to know the length of the area code.
8438777f1913d34c3ecf72164ea85292e978e265eddShaopeng Jia   * @return  the length of area code of the PhoneNumber object
8448777f1913d34c3ecf72164ea85292e978e265eddShaopeng Jia   *     passed in.
8455c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia   */
8465c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia  public int getLengthOfGeographicalAreaCode(PhoneNumber number) {
847203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    PhoneMetadata metadata = getMetadataForRegion(getRegionCodeForNumber(number));
848203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    if (metadata == null) {
8495c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia      return 0;
8505c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia    }
851b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia    // If a country doesn't use a national prefix, and this number doesn't have an Italian leading
852b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia    // zero, we assume it is a closed dialling plan with no area codes.
853b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia    if (!metadata.hasNationalPrefix() && !number.isItalianLeadingZero()) {
8545c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia      return 0;
8555c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia    }
8565c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia
857203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    if (!isNumberGeographical(number)) {
8585c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia      return 0;
8595c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia    }
8605c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia
86174aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia    return getLengthOfNationalDestinationCode(number);
86274aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia  }
86374aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia
86474aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia  /**
8658777f1913d34c3ecf72164ea85292e978e265eddShaopeng Jia   * Gets the length of the national destination code (NDC) from the
8668777f1913d34c3ecf72164ea85292e978e265eddShaopeng Jia   * PhoneNumber object passed in, so that clients could use it
8678777f1913d34c3ecf72164ea85292e978e265eddShaopeng Jia   * to split a national significant number into NDC and subscriber number. The NDC of a phone
8688777f1913d34c3ecf72164ea85292e978e265eddShaopeng Jia   * number is normally the first group of digit(s) right after the country calling code when the
8698777f1913d34c3ecf72164ea85292e978e265eddShaopeng Jia   * number is formatted in the international format, if there is a subscriber number part that
8708777f1913d34c3ecf72164ea85292e978e265eddShaopeng Jia   * follows. An example of how this could be used:
87174aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia   *
872372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * <pre>
87374aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia   * PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
87474aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia   * PhoneNumber number = phoneUtil.parse("18002530000", "US");
875372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * String nationalSignificantNumber = phoneUtil.getNationalSignificantNumber(number);
87674aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia   * String nationalDestinationCode;
87774aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia   * String subscriberNumber;
87874aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia   *
87974aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia   * int nationalDestinationCodeLength = phoneUtil.getLengthOfNationalDestinationCode(number);
88074aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia   * if (nationalDestinationCodeLength > 0) {
88174aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia   *   nationalDestinationCode = nationalSignificantNumber.substring(0,
88274aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia   *       nationalDestinationCodeLength);
88374aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia   *   subscriberNumber = nationalSignificantNumber.substring(nationalDestinationCodeLength);
88474aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia   * } else {
88574aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia   *   nationalDestinationCode = "";
88674aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia   *   subscriberNumber = nationalSignificantNumber;
88774aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia   * }
888372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * </pre>
88974aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia   *
89074aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia   * Refer to the unittests to see the difference between this function and
891d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   * {@link #getLengthOfGeographicalAreaCode}.
89274aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia   *
8938777f1913d34c3ecf72164ea85292e978e265eddShaopeng Jia   * @param number  the PhoneNumber object for which clients
8948777f1913d34c3ecf72164ea85292e978e265eddShaopeng Jia   *     want to know the length of the NDC.
8958777f1913d34c3ecf72164ea85292e978e265eddShaopeng Jia   * @return  the length of NDC of the PhoneNumber object
8968777f1913d34c3ecf72164ea85292e978e265eddShaopeng Jia   *     passed in.
89774aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia   */
89874aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia  public int getLengthOfNationalDestinationCode(PhoneNumber number) {
8995c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia    PhoneNumber copiedProto;
9005c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia    if (number.hasExtension()) {
9015c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia      // We don't want to alter the proto given to us, but we don't want to include the extension
9025c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia      // when we format it, so we copy it and clear the extension here.
90376f6569af0619d12afd19991d8ff69a9bea4c142Shaopeng Jia      copiedProto = new PhoneNumber();
90476f6569af0619d12afd19991d8ff69a9bea4c142Shaopeng Jia      copiedProto.mergeFrom(number);
90576f6569af0619d12afd19991d8ff69a9bea4c142Shaopeng Jia      copiedProto.clearExtension();
9065c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia    } else {
9075c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia      copiedProto = number;
9085c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia    }
9095c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia
9105c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia    String nationalSignificantNumber = format(copiedProto,
9115c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia                                              PhoneNumberUtil.PhoneNumberFormat.INTERNATIONAL);
912f59ccfca9dd02c4e3cf3e06b5cf184a8d0e67626Shaopeng Jia    String[] numberGroups = NON_DIGITS_PATTERN.split(nationalSignificantNumber);
9135c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia    // The pattern will start with "+COUNTRY_CODE " so the first group will always be the empty
914372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    // string (before the + symbol) and the second group will be the country calling code. The third
915372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    // group will be area code if it is not the last group.
9165c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia    if (numberGroups.length <= 3) {
9175c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia      return 0;
9185c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia    }
91974aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia
920f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia    if (getNumberType(number) == PhoneNumberType.MOBILE) {
921f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia      // For example Argentinian mobile numbers, when formatted in the international format, are in
922f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia      // the form of +54 9 NDC XXXX.... As a result, we take the length of the third group (NDC) and
923f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia      // add the length of the second group (which is the mobile token), which also forms part of
924f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia      // the national significant number. This assumes that the mobile token is always formatted
925f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia      // separately from the rest of the phone number.
926f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia      String mobileToken = getCountryMobileToken(number.getCountryCode());
927f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia      if (!mobileToken.equals("")) {
928f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia        return numberGroups[2].length() + numberGroups[3].length();
929f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia      }
93074aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia    }
9315c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia    return numberGroups[2].length();
932df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia  }
9335c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia
9345c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia  /**
935f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia   * Returns the mobile token for the provided country calling code if it has one, otherwise
936f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia   * returns an empty string. A mobile token is a number inserted before the area code when dialing
937f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia   * a mobile number from that country from abroad.
938f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia   *
939f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia   * @param countryCallingCode  the country calling code for which we want the mobile token
940f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia   * @return  the mobile token, as a string, for the given country calling code
941f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia   */
942f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia  public static String getCountryMobileToken(int countryCallingCode) {
943f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia    if (MOBILE_TOKEN_MAPPINGS.containsKey(countryCallingCode)) {
944f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia      return MOBILE_TOKEN_MAPPINGS.get(countryCallingCode);
945f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia    }
946f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia    return "";
947f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia  }
948f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia
949f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia  /**
9501524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * Normalizes a string of characters representing a phone number by replacing all characters found
9511524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * in the accompanying map with the values therein, and stripping all other characters if
9521524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * removeNonMatches is true.
9531524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *
9541524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @param number                     a string of characters representing a phone number
9551524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @param normalizationReplacements  a mapping of characters to what they should be replaced by in
9561524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *                                   the normalized version of the phone number
9571524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @param removeNonMatches           indicates whether characters that are not able to be replaced
9581524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *                                   should be stripped from the number. If this is false, they
9591524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *                                   will be left unchanged in the number.
9605c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia   * @return  the normalized string version of the phone number
9611524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
962f59ccfca9dd02c4e3cf3e06b5cf184a8d0e67626Shaopeng Jia  private static String normalizeHelper(String number,
963f59ccfca9dd02c4e3cf3e06b5cf184a8d0e67626Shaopeng Jia                                        Map<Character, Character> normalizationReplacements,
964f59ccfca9dd02c4e3cf3e06b5cf184a8d0e67626Shaopeng Jia                                        boolean removeNonMatches) {
965372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    StringBuilder normalizedNumber = new StringBuilder(number.length());
966203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    for (int i = 0; i < number.length(); i++) {
967203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia      char character = number.charAt(i);
9681524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      Character newDigit = normalizationReplacements.get(Character.toUpperCase(character));
9691524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      if (newDigit != null) {
9701524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia        normalizedNumber.append(newDigit);
9711524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      } else if (!removeNonMatches) {
9721524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia        normalizedNumber.append(character);
9731524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      }
9741524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      // If neither of the above are true, we remove this character.
9751524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
9761524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    return normalizedNumber.toString();
9771524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
9781524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
9793396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia  /**
9809ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia   * Sets or resets the PhoneNumberUtil singleton instance. If set to null, the next call to
9819ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia   * {@code getInstance()} will load (and return) the default instance.
9823396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia   */
983cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia  // @VisibleForTesting
9849ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia  static synchronized void setInstance(PhoneNumberUtil util) {
9859ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia    instance = util;
9861524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
9871524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
9881524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
989ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia   * Convenience method to get a list of what regions the library has metadata for.
9901524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
991372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  public Set<String> getSupportedRegions() {
992203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    return Collections.unmodifiableSet(supportedRegions);
9931524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
9941524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
9951524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
996cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia   * Convenience method to get a list of what global network calling codes the library has metadata
997cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia   * for.
998cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia   */
999cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia  public Set<Integer> getSupportedGlobalNetworkCallingCodes() {
1000203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    return Collections.unmodifiableSet(countryCodesForNonGeographicalRegion);
1001cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia  }
1002cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia
1003cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia  /**
1004372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * Gets a {@link PhoneNumberUtil} instance to carry out international phone number formatting,
1005372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * parsing, or validation. The instance is loaded with phone number metadata for a number of most
1006372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * commonly used regions.
10071524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *
1008372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * <p>The {@link PhoneNumberUtil} is implemented as a singleton. Therefore, calling getInstance
1009372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * multiple times will only result in one instance being created.
10101524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *
10111524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @return a PhoneNumberUtil instance
10121524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
10131524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  public static synchronized PhoneNumberUtil getInstance() {
10141524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    if (instance == null) {
10159ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia      setInstance(createInstance(DEFAULT_METADATA_LOADER));
10161524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
10171524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    return instance;
10181524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
10191524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
10201524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
10219ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia   * Create a new {@link PhoneNumberUtil} instance to carry out international phone number
10229ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia   * formatting, parsing, or validation. The instance is loaded with all metadata by
10239ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia   * using the metadataLoader specified.
10249ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia   *
10259ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia   * This method should only be used in the rare case in which you want to manage your own
10269ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia   * metadata loading. Calling this method multiple times is very expensive, as each time
10279ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia   * a new instance is created from scratch. When in doubt, use {@link #getInstance}.
10289ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia   *
10299ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia   * @param metadataLoader Customized metadata loader. If null, default metadata loader will
10309ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia   *     be used. This should not be null.
10319ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia   * @return a PhoneNumberUtil instance
10329ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia   */
10339ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia  public static PhoneNumberUtil createInstance(MetadataLoader metadataLoader) {
10349ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia    if (metadataLoader == null) {
10359ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia      throw new IllegalArgumentException("metadataLoader could not be null.");
10369ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia    }
10379ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia    return new PhoneNumberUtil(META_DATA_FILE_PREFIX, metadataLoader,
10389ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia        CountryCodeToRegionCodeMap.getCountryCodeToRegionCodeMap());
10399ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia  }
10409ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia
10419ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia  /**
1042203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia   * Helper function to check if the national prefix formatting rule has the first group only, i.e.,
1043203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia   * does not start with the national prefix.
1044203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia   */
1045203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia  static boolean formattingRuleHasFirstGroupOnly(String nationalPrefixFormattingRule) {
10463396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia    return nationalPrefixFormattingRule.length() == 0 ||
10473396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia        FIRST_GROUP_ONLY_PREFIX_PATTERN.matcher(nationalPrefixFormattingRule).matches();
1048203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia  }
1049203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia
1050203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia  /**
1051203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia   * Tests whether a phone number has a geographical association. It checks if the number is
1052203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia   * associated to a certain region in the country where it belongs to. Note that this doesn't
1053203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia   * verify if the number is actually in use.
10548777f1913d34c3ecf72164ea85292e978e265eddShaopeng Jia   *
10558777f1913d34c3ecf72164ea85292e978e265eddShaopeng Jia   * A similar method is implemented as PhoneNumberOfflineGeocoder.canBeGeocoded, which performs a
10568777f1913d34c3ecf72164ea85292e978e265eddShaopeng Jia   * looser check, since it only prevents cases where prefixes overlap for geocodable and
10578777f1913d34c3ecf72164ea85292e978e265eddShaopeng Jia   * non-geocodable numbers. Also, if new phone number types were added, we should check if this
10588777f1913d34c3ecf72164ea85292e978e265eddShaopeng Jia   * other method should be updated too.
1059203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia   */
1060203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia  boolean isNumberGeographical(PhoneNumber phoneNumber) {
1061203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    PhoneNumberType numberType = getNumberType(phoneNumber);
1062203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    // TODO: Include mobile phone numbers from countries like Indonesia, which has some
1063203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    // mobile numbers that are geographical.
1064203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    return numberType == PhoneNumberType.FIXED_LINE ||
1065203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia        numberType == PhoneNumberType.FIXED_LINE_OR_MOBILE;
1066203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia  }
1067203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia
1068203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia  /**
1069be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia   * Helper function to check region code is not unknown or null.
10701524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
1071be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia  private boolean isValidRegionCode(String regionCode) {
1072d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia    return regionCode != null && supportedRegions.contains(regionCode);
1073372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  }
1074372bff8dd464574d36737d47e495cad14346653cShaopeng Jia
1075372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  /**
1076528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia   * Helper function to check the country calling code is valid.
1077372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   */
1078528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia  private boolean hasValidCountryCallingCode(int countryCallingCode) {
1079528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    return countryCallingCodeToRegionCodeMap.containsKey(countryCallingCode);
10801524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
10811524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
10821524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
10831524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * Formats a phone number in the specified format using default rules. Note that this does not
10841524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * promise to produce a phone number that the user can dial from where they are - although we do
10851524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * format in either 'national' or 'international' format depending on what the client asks for, we
10861524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * do not currently support a more abbreviated format, such as for users in the same "area" who
10871524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * could potentially dial the number without area code. Note that if the phone number has a
1088372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * country calling code of 0 or an otherwise invalid country calling code, we cannot work out
1089372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * which formatting rules to apply so we return the national significant number with no formatting
1090372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * 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
10945c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia   * @return  the formatted phone number
10951524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
10961524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  public String format(PhoneNumber number, PhoneNumberFormat numberFormat) {
1097082e1e80b0bcb2911de5d26981b592f2c2b9d3f6Shaopeng Jia    if (number.getNationalNumber() == 0 && number.hasRawInput()) {
1098203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia      // Unparseable numbers that kept their raw input just use that.
1099203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia      // This is the only case where a number can be formatted as E164 without a
1100203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia      // leading '+' symbol (but the original number wasn't parseable anyway).
1101203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia      // TODO: Consider removing the 'if' above so that unparseable
1102203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia      // strings without raw input format to the empty string instead of "+00"
1103082e1e80b0bcb2911de5d26981b592f2c2b9d3f6Shaopeng Jia      String rawInput = number.getRawInput();
1104082e1e80b0bcb2911de5d26981b592f2c2b9d3f6Shaopeng Jia      if (rawInput.length() > 0) {
1105082e1e80b0bcb2911de5d26981b592f2c2b9d3f6Shaopeng Jia        return rawInput;
1106082e1e80b0bcb2911de5d26981b592f2c2b9d3f6Shaopeng Jia      }
1107082e1e80b0bcb2911de5d26981b592f2c2b9d3f6Shaopeng Jia    }
1108372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    StringBuilder formattedNumber = new StringBuilder(20);
110976f6569af0619d12afd19991d8ff69a9bea4c142Shaopeng Jia    format(number, numberFormat, formattedNumber);
1110be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    return formattedNumber.toString();
1111be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia  }
1112be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia
1113d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia  /**
111496a7214cdabf08f53f5b1a560304601c9f65e0b9Shaopeng Jia   * Same as {@link #format(PhoneNumber, PhoneNumberFormat)}, but accepts a mutable StringBuilder as
111596a7214cdabf08f53f5b1a560304601c9f65e0b9Shaopeng Jia   * a parameter to decrease object creation when invoked many times.
1116d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   */
111776f6569af0619d12afd19991d8ff69a9bea4c142Shaopeng Jia  public void format(PhoneNumber number, PhoneNumberFormat numberFormat,
1118372bff8dd464574d36737d47e495cad14346653cShaopeng Jia                     StringBuilder formattedNumber) {
1119372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    // Clear the StringBuilder first.
1120be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    formattedNumber.setLength(0);
1121d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia    int countryCallingCode = number.getCountryCode();
11225c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia    String nationalSignificantNumber = getNationalSignificantNumber(number);
11238777f1913d34c3ecf72164ea85292e978e265eddShaopeng Jia
11241524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    if (numberFormat == PhoneNumberFormat.E164) {
1125203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia      // Early exit for E164 case (even if the country calling code is invalid) since no formatting
1126203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia      // of the national number needs to be applied. Extensions are not formatted.
1127be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia      formattedNumber.append(nationalSignificantNumber);
1128cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia      prefixNumberWithCountryCallingCode(countryCallingCode, PhoneNumberFormat.E164,
1129cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia                                         formattedNumber);
1130be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia      return;
11311524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
1132cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia    if (!hasValidCountryCallingCode(countryCallingCode)) {
1133be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia      formattedNumber.append(nationalSignificantNumber);
1134be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia      return;
11351524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
1136203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    // Note getRegionCodeForCountryCode() is used because formatting information for regions which
1137203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    // share a country calling code is contained by only one region for performance reasons. For
1138203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    // example, for NANPA regions it will be contained in the metadata for US.
1139203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    String regionCode = getRegionCodeForCountryCode(countryCallingCode);
1140203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    // Metadata cannot be null because the country calling code is valid (which means that the
1141203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    // region code cannot be ZZ and must be one of our supported region codes).
1142528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    PhoneMetadata metadata =
1143528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        getMetadataForRegionOrCallingCode(countryCallingCode, regionCode);
1144cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia    formattedNumber.append(formatNsn(nationalSignificantNumber, metadata, numberFormat));
1145cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia    maybeAppendFormattedExtension(number, metadata, numberFormat, formattedNumber);
1146cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia    prefixNumberWithCountryCallingCode(countryCallingCode, numberFormat, formattedNumber);
11471524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
11481524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
11491524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
11501524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * Formats a phone number in the specified format using client-defined formatting rules. Note that
1151372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * if the phone number has a country calling code of zero or an otherwise invalid country calling
1152372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * code, we cannot work out things like whether there should be a national prefix applied, or how
1153372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * to format extensions, so we return the national significant number with no formatting applied.
11541524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *
11551524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @param number                        the phone number to be formatted
11561524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @param numberFormat                  the format the phone number should be formatted into
11571524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @param userDefinedFormats            formatting rules specified by clients
11585c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia   * @return  the formatted phone number
11591524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
11601524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  public String formatByPattern(PhoneNumber number,
11611524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia                                PhoneNumberFormat numberFormat,
11621524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia                                List<NumberFormat> userDefinedFormats) {
1163372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    int countryCallingCode = number.getCountryCode();
11644b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia    String nationalSignificantNumber = getNationalSignificantNumber(number);
1165203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    if (!hasValidCountryCallingCode(countryCallingCode)) {
1166203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia      return nationalSignificantNumber;
1167203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    }
1168372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    // Note getRegionCodeForCountryCode() is used because formatting information for regions which
1169372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    // share a country calling code is contained by only one region for performance reasons. For
1170372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    // example, for NANPA regions it will be contained in the metadata for US.
1171372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    String regionCode = getRegionCodeForCountryCode(countryCallingCode);
1172203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    // Metadata cannot be null because the country calling code is valid
1173528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    PhoneMetadata metadata =
1174528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        getMetadataForRegionOrCallingCode(countryCallingCode, regionCode);
1175cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia
1176cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia    StringBuilder formattedNumber = new StringBuilder(20);
1177cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia
1178cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia    NumberFormat formattingPattern =
1179cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia        chooseFormattingPatternForNumber(userDefinedFormats, nationalSignificantNumber);
1180cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia    if (formattingPattern == null) {
1181cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia      // If no pattern above is matched, we format the number as a whole.
1182cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia      formattedNumber.append(nationalSignificantNumber);
1183cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia    } else {
1184cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia      NumberFormat numFormatCopy = new NumberFormat();
1185cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia      // Before we do a replacement of the national prefix pattern $NP with the national prefix, we
1186cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia      // need to copy the rule so that subsequent replacements for different numbers have the
1187cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia      // appropriate national prefix.
1188cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia      numFormatCopy.mergeFrom(formattingPattern);
1189cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia      String nationalPrefixFormattingRule = formattingPattern.getNationalPrefixFormattingRule();
11901524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      if (nationalPrefixFormattingRule.length() > 0) {
1191528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        String nationalPrefix = metadata.getNationalPrefix();
1192f59ccfca9dd02c4e3cf3e06b5cf184a8d0e67626Shaopeng Jia        if (nationalPrefix.length() > 0) {
1193df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia          // Replace $NP with national prefix and $FG with the first group ($1).
1194df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia          nationalPrefixFormattingRule =
1195df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia              NP_PATTERN.matcher(nationalPrefixFormattingRule).replaceFirst(nationalPrefix);
1196df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia          nationalPrefixFormattingRule =
1197df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia              FG_PATTERN.matcher(nationalPrefixFormattingRule).replaceFirst("\\$1");
1198df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia          numFormatCopy.setNationalPrefixFormattingRule(nationalPrefixFormattingRule);
1199df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia        } else {
1200df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia          // We don't want to have a rule for how to format the national prefix if there isn't one.
1201df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia          numFormatCopy.clearNationalPrefixFormattingRule();
1202df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia        }
12031524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      }
1204cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia      formattedNumber.append(
1205cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia          formatNsnUsingPattern(nationalSignificantNumber, numFormatCopy, numberFormat));
12061524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
1207cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia    maybeAppendFormattedExtension(number, metadata, numberFormat, formattedNumber);
1208cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia    prefixNumberWithCountryCallingCode(countryCallingCode, numberFormat, formattedNumber);
1209be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    return formattedNumber.toString();
12101524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
12111524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
121252699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia  /**
121352699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia   * Formats a phone number in national format for dialing using the carrier as specified in the
1214372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * {@code carrierCode}. The {@code carrierCode} will always be used regardless of whether the
1215372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * phone number already has a preferred domestic carrier code stored. If {@code carrierCode}
1216372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * contains an empty string, returns the number in national format without any carrier code.
121752699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia   *
121852699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia   * @param number  the phone number to be formatted
121952699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia   * @param carrierCode  the carrier selection code to be used
122052699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia   * @return  the formatted phone number in national format for dialing using the carrier as
1221372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *          specified in the {@code carrierCode}
122252699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia   */
12234b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia  public String formatNationalNumberWithCarrierCode(PhoneNumber number, String carrierCode) {
1224372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    int countryCallingCode = number.getCountryCode();
12254b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia    String nationalSignificantNumber = getNationalSignificantNumber(number);
1226203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    if (!hasValidCountryCallingCode(countryCallingCode)) {
1227203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia      return nationalSignificantNumber;
1228203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    }
1229203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia
1230372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    // Note getRegionCodeForCountryCode() is used because formatting information for regions which
1231372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    // share a country calling code is contained by only one region for performance reasons. For
1232372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    // example, for NANPA regions it will be contained in the metadata for US.
1233372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    String regionCode = getRegionCodeForCountryCode(countryCallingCode);
1234203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    // Metadata cannot be null because the country calling code is valid.
1235203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    PhoneMetadata metadata = getMetadataForRegionOrCallingCode(countryCallingCode, regionCode);
12364b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia
1237372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    StringBuilder formattedNumber = new StringBuilder(20);
1238cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia    formattedNumber.append(formatNsn(nationalSignificantNumber, metadata,
1239cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia                                     PhoneNumberFormat.NATIONAL, carrierCode));
1240cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia    maybeAppendFormattedExtension(number, metadata, PhoneNumberFormat.NATIONAL, formattedNumber);
1241cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia    prefixNumberWithCountryCallingCode(countryCallingCode, PhoneNumberFormat.NATIONAL,
1242cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia                                       formattedNumber);
12434b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia    return formattedNumber.toString();
12444b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia  }
12454b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia
1246528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia  private PhoneMetadata getMetadataForRegionOrCallingCode(
1247528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia      int countryCallingCode, String regionCode) {
1248528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    return REGION_CODE_FOR_NON_GEO_ENTITY.equals(regionCode)
1249528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        ? getMetadataForNonGeographicalRegion(countryCallingCode)
1250528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        : getMetadataForRegion(regionCode);
1251528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia  }
1252528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia
12531524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
125452699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia   * Formats a phone number in national format for dialing using the carrier as specified in the
1255372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * preferredDomesticCarrierCode field of the PhoneNumber object passed in. If that is missing,
1256372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * use the {@code fallbackCarrierCode} passed in instead. If there is no
1257372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * {@code preferredDomesticCarrierCode}, and the {@code fallbackCarrierCode} contains an empty
1258372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * string, return the number in national format without any carrier code.
125952699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia   *
1260372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * <p>Use {@link #formatNationalNumberWithCarrierCode} instead if the carrier code passed in
1261372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * should take precedence over the number's {@code preferredDomesticCarrierCode} when formatting.
126252699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia   *
126352699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia   * @param number  the phone number to be formatted
126452699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia   * @param fallbackCarrierCode  the carrier selection code to be used, if none is found in the
1265372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *     phone number itself
126652699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia   * @return  the formatted phone number in national format for dialing using the number's
1267372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *     {@code preferredDomesticCarrierCode}, or the {@code fallbackCarrierCode} passed in if
1268372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *     none is found
126952699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia   */
127052699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia  public String formatNationalNumberWithPreferredCarrierCode(PhoneNumber number,
127152699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia                                                             String fallbackCarrierCode) {
127252699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia    return formatNationalNumberWithCarrierCode(number, number.hasPreferredDomesticCarrierCode()
127352699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia                                                       ? number.getPreferredDomesticCarrierCode()
127452699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia                                                       : fallbackCarrierCode);
127552699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia  }
127652699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia
127752699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia  /**
1278ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia   * Returns a number formatted in such a way that it can be dialed from a mobile phone in a
1279ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia   * specific region. If the number cannot be reached from the region (e.g. some countries block
1280ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia   * toll-free numbers from being called outside of the country), the method returns an empty
1281ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia   * string.
1282ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia   *
1283ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia   * @param number  the phone number to be formatted
1284ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia   * @param regionCallingFrom  the region where the call is being placed
1285ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia   * @param withFormatting  whether the number should be returned with formatting symbols, such as
1286ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia   *     spaces and dashes.
1287ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia   * @return  the formatted phone number
1288ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia   */
1289ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia  public String formatNumberForMobileDialing(PhoneNumber number, String regionCallingFrom,
1290ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia                                             boolean withFormatting) {
1291528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    int countryCallingCode = number.getCountryCode();
1292528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    if (!hasValidCountryCallingCode(countryCallingCode)) {
1293ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia      return number.hasRawInput() ? number.getRawInput() : "";
1294ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia    }
1295ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia
1296485e6d5c6e48a1fc43cc0a090e687c723dac056cShaopeng Jia    String formattedNumber = "";
1297ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia    // Clear the extension, as that part cannot normally be dialed together with the main number.
1298ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia    PhoneNumber numberNoExt = new PhoneNumber().mergeFrom(number).clearExtension();
1299528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    String regionCode = getRegionCodeForCountryCode(countryCallingCode);
1300f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia    PhoneNumberType numberType = getNumberType(numberNoExt);
1301f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia    boolean isValidNumber = (numberType != PhoneNumberType.UNKNOWN);
1302485e6d5c6e48a1fc43cc0a090e687c723dac056cShaopeng Jia    if (regionCallingFrom.equals(regionCode)) {
1303485e6d5c6e48a1fc43cc0a090e687c723dac056cShaopeng Jia      boolean isFixedLineOrMobile =
1304485e6d5c6e48a1fc43cc0a090e687c723dac056cShaopeng Jia          (numberType == PhoneNumberType.FIXED_LINE) || (numberType == PhoneNumberType.MOBILE) ||
1305485e6d5c6e48a1fc43cc0a090e687c723dac056cShaopeng Jia          (numberType == PhoneNumberType.FIXED_LINE_OR_MOBILE);
1306485e6d5c6e48a1fc43cc0a090e687c723dac056cShaopeng Jia      // Carrier codes may be needed in some countries. We handle this here.
1307485e6d5c6e48a1fc43cc0a090e687c723dac056cShaopeng Jia      if (regionCode.equals("CO") && numberType == PhoneNumberType.FIXED_LINE) {
130896a7214cdabf08f53f5b1a560304601c9f65e0b9Shaopeng Jia        formattedNumber =
130996a7214cdabf08f53f5b1a560304601c9f65e0b9Shaopeng Jia            formatNationalNumberWithCarrierCode(numberNoExt, COLOMBIA_MOBILE_TO_FIXED_LINE_PREFIX);
1310485e6d5c6e48a1fc43cc0a090e687c723dac056cShaopeng Jia      } else if (regionCode.equals("BR") && isFixedLineOrMobile) {
1311485e6d5c6e48a1fc43cc0a090e687c723dac056cShaopeng Jia        formattedNumber = numberNoExt.hasPreferredDomesticCarrierCode()
1312485e6d5c6e48a1fc43cc0a090e687c723dac056cShaopeng Jia            ? formattedNumber = formatNationalNumberWithPreferredCarrierCode(numberNoExt, "")
1313485e6d5c6e48a1fc43cc0a090e687c723dac056cShaopeng Jia            // Brazilian fixed line and mobile numbers need to be dialed with a carrier code when
1314485e6d5c6e48a1fc43cc0a090e687c723dac056cShaopeng Jia            // called within Brazil. Without that, most of the carriers won't connect the call.
1315485e6d5c6e48a1fc43cc0a090e687c723dac056cShaopeng Jia            // Because of that, we return an empty string here.
1316485e6d5c6e48a1fc43cc0a090e687c723dac056cShaopeng Jia            : "";
1317f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia      } else if (isValidNumber && regionCode.equals("HU")) {
13183396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia        // The national format for HU numbers doesn't contain the national prefix, because that is
13193396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia        // how numbers are normally written down. However, the national prefix is obligatory when
1320f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia        // dialing from a mobile phone, except for short numbers. As a result, we add it back here
1321f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia        // if it is a valid regular length phone number.
13223396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia        formattedNumber =
13233396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia            getNddPrefixForRegion(regionCode, true /* strip non-digits */) +
13243396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia            " " + format(numberNoExt, PhoneNumberFormat.NATIONAL);
1325f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia      } else if (countryCallingCode == NANPA_COUNTRY_CODE) {
1326f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia        // For NANPA countries, we output international format for numbers that can be dialed
1327f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia        // internationally, since that always works, except for numbers which might potentially be
1328f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia        // short numbers, which are always dialled in national format.
1329f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia        PhoneMetadata regionMetadata = getMetadataForRegion(regionCallingFrom);
1330f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia        if (canBeInternationallyDialled(numberNoExt) &&
1331f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia            !isShorterThanPossibleNormalNumber(regionMetadata,
1332f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia                getNationalSignificantNumber(numberNoExt))) {
1333f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia          formattedNumber = format(numberNoExt, PhoneNumberFormat.INTERNATIONAL);
1334f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia        } else {
1335f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia          formattedNumber = format(numberNoExt, PhoneNumberFormat.NATIONAL);
1336f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia        }
133796a7214cdabf08f53f5b1a560304601c9f65e0b9Shaopeng Jia      } else {
1338f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia        // For non-geographical countries, and Mexican and Chilean fixed line and mobile numbers, we
1339f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia        // output international format for numbers that can be dialed internationally as that always
1340f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia        // works.
1341f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia        if ((regionCode.equals(REGION_CODE_FOR_NON_GEO_ENTITY) ||
1342485e6d5c6e48a1fc43cc0a090e687c723dac056cShaopeng Jia            // MX fixed line and mobile numbers should always be formatted in international format,
1343485e6d5c6e48a1fc43cc0a090e687c723dac056cShaopeng Jia            // even when dialed within MX. For national format to work, a carrier code needs to be
1344485e6d5c6e48a1fc43cc0a090e687c723dac056cShaopeng Jia            // used, and the correct carrier code depends on if the caller and callee are from the
1345485e6d5c6e48a1fc43cc0a090e687c723dac056cShaopeng Jia            // same local area. It is trickier to get that to work correctly than using
1346485e6d5c6e48a1fc43cc0a090e687c723dac056cShaopeng Jia            // international format, which is tested to work fine on all carriers.
13473396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia            // CL fixed line numbers need the national prefix when dialing in the national format,
13483396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia            // but don't have it when used for display. The reverse is true for mobile numbers.
13493396e51bc9ea60ecdebdfa76a7f7a6f37466e3b3Shaopeng Jia            // As a result, we output them in the international format to make it work.
13508777f1913d34c3ecf72164ea85292e978e265eddShaopeng Jia            ((regionCode.equals("MX") || regionCode.equals("CL")) &&
13518777f1913d34c3ecf72164ea85292e978e265eddShaopeng Jia             isFixedLineOrMobile)) &&
1352485e6d5c6e48a1fc43cc0a090e687c723dac056cShaopeng Jia            canBeInternationallyDialled(numberNoExt)) {
1353485e6d5c6e48a1fc43cc0a090e687c723dac056cShaopeng Jia          formattedNumber = format(numberNoExt, PhoneNumberFormat.INTERNATIONAL);
1354485e6d5c6e48a1fc43cc0a090e687c723dac056cShaopeng Jia        } else {
1355485e6d5c6e48a1fc43cc0a090e687c723dac056cShaopeng Jia          formattedNumber = format(numberNoExt, PhoneNumberFormat.NATIONAL);
1356485e6d5c6e48a1fc43cc0a090e687c723dac056cShaopeng Jia        }
135796a7214cdabf08f53f5b1a560304601c9f65e0b9Shaopeng Jia      }
1358f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia    } else if (isValidNumber && canBeInternationallyDialled(numberNoExt)) {
1359f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia      // We assume that short numbers are not diallable from outside their region, so if a number
1360f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia      // is not a valid regular length phone number, we treat it as if it cannot be internationally
1361f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia      // dialled.
1362ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia      return withFormatting ? format(numberNoExt, PhoneNumberFormat.INTERNATIONAL)
1363ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia                            : format(numberNoExt, PhoneNumberFormat.E164);
1364ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia    }
136596a7214cdabf08f53f5b1a560304601c9f65e0b9Shaopeng Jia    return withFormatting ? formattedNumber
1366bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia                          : normalizeDiallableCharsOnly(formattedNumber);
1367ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia  }
1368ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia
1369ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia  /**
1370372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * Formats a phone number for out-of-country dialing purposes. If no regionCallingFrom is
1371372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * supplied, we format the number in its INTERNATIONAL format. If the country calling code is the
1372d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   * same as that of the region where the number is from, then NATIONAL formatting will be applied.
13731524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *
1374372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * <p>If the number itself has a country calling code of zero or an otherwise invalid country
1375372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * calling code, then we return the number with no formatting applied.
13761524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *
1377372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * <p>Note this function takes care of the case for calling inside of NANPA and between Russia and
1378372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * Kazakhstan (who share the same country calling code). In those cases, no international prefix
1379372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * is used. For regions which have multiple international prefixes, the number in its
1380372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * INTERNATIONAL format will be returned instead.
13811524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *
13821524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @param number               the phone number to be formatted
1383d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   * @param regionCallingFrom    the region where the call is being placed
13845c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia   * @return  the formatted phone number
13851524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
1386d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia  public String formatOutOfCountryCallingNumber(PhoneNumber number,
1387d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia                                                String regionCallingFrom) {
1388372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    if (!isValidRegionCode(regionCallingFrom)) {
1389bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia      logger.log(Level.WARNING,
1390cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia                 "Trying to format number from invalid region "
1391cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia                 + regionCallingFrom
1392cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia                 + ". International formatting applied.");
13931524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      return format(number, PhoneNumberFormat.INTERNATIONAL);
13941524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
1395372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    int countryCallingCode = number.getCountryCode();
13965c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia    String nationalSignificantNumber = getNationalSignificantNumber(number);
1397528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    if (!hasValidCountryCallingCode(countryCallingCode)) {
13981524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      return nationalSignificantNumber;
13991524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
1400372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    if (countryCallingCode == NANPA_COUNTRY_CODE) {
1401372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      if (isNANPACountry(regionCallingFrom)) {
1402372bff8dd464574d36737d47e495cad14346653cShaopeng Jia        // For NANPA regions, return the national format for these regions but prefix it with the
1403372bff8dd464574d36737d47e495cad14346653cShaopeng Jia        // country calling code.
1404372bff8dd464574d36737d47e495cad14346653cShaopeng Jia        return countryCallingCode + " " + format(number, PhoneNumberFormat.NATIONAL);
14054b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia      }
1406cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia    } else if (countryCallingCode == getCountryCodeForValidRegion(regionCallingFrom)) {
140777aadd284847681bd66af639636c2fa43e418c2bShaopeng Jia      // If regions share a country calling code, the country calling code need not be dialled.
140877aadd284847681bd66af639636c2fa43e418c2bShaopeng Jia      // This also applies when dialling within a region, so this if clause covers both these cases.
140977aadd284847681bd66af639636c2fa43e418c2bShaopeng Jia      // Technically this is the case for dialling from La Reunion to other overseas departments of
141077aadd284847681bd66af639636c2fa43e418c2bShaopeng Jia      // France (French Guiana, Martinique, Guadeloupe), but not vice versa - so we don't cover this
141177aadd284847681bd66af639636c2fa43e418c2bShaopeng Jia      // edge case for now and for those cases return the version including country calling code.
141277aadd284847681bd66af639636c2fa43e418c2bShaopeng Jia      // Details here: http://www.petitfute.com/voyage/225-info-pratiques-reunion
14131524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      return format(number, PhoneNumberFormat.NATIONAL);
14141524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
1415203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    // Metadata cannot be null because we checked 'isValidRegionCode()' above.
1416528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    PhoneMetadata metadataForRegionCallingFrom = getMetadataForRegion(regionCallingFrom);
1417528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    String internationalPrefix = metadataForRegionCallingFrom.getInternationalPrefix();
1418be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia
1419372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    // For regions that have multiple international prefixes, the international format of the
14201524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    // number is returned, unless there is a preferred international prefix.
14211524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    String internationalPrefixForFormatting = "";
14221524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    if (UNIQUE_INTERNATIONAL_PREFIX.matcher(internationalPrefix).matches()) {
14231524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      internationalPrefixForFormatting = internationalPrefix;
1424528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    } else if (metadataForRegionCallingFrom.hasPreferredInternationalPrefix()) {
1425528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia      internationalPrefixForFormatting =
1426528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia          metadataForRegionCallingFrom.getPreferredInternationalPrefix();
14271524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
1428be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia
1429528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    String regionCode = getRegionCodeForCountryCode(countryCallingCode);
1430203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    // Metadata cannot be null because the country calling code is valid.
1431528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    PhoneMetadata metadataForRegion =
1432528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        getMetadataForRegionOrCallingCode(countryCallingCode, regionCode);
1433528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    String formattedNationalNumber =
1434cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia        formatNsn(nationalSignificantNumber, metadataForRegion, PhoneNumberFormat.INTERNATIONAL);
1435372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    StringBuilder formattedNumber = new StringBuilder(formattedNationalNumber);
1436cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia    maybeAppendFormattedExtension(number, metadataForRegion, PhoneNumberFormat.INTERNATIONAL,
1437cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia                                  formattedNumber);
1438be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    if (internationalPrefixForFormatting.length() > 0) {
1439372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      formattedNumber.insert(0, " ").insert(0, countryCallingCode).insert(0, " ")
1440be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia          .insert(0, internationalPrefixForFormatting);
1441be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    } else {
1442cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia      prefixNumberWithCountryCallingCode(countryCallingCode,
1443cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia                                         PhoneNumberFormat.INTERNATIONAL,
1444cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia                                         formattedNumber);
1445be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    }
1446be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    return formattedNumber.toString();
14471524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
14481524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
144954923fc72f0faeb11fe58a545c0314f6051b14aaShaopeng Jia  /**
145054923fc72f0faeb11fe58a545c0314f6051b14aaShaopeng Jia   * Formats a phone number using the original phone number format that the number is parsed from.
145154923fc72f0faeb11fe58a545c0314f6051b14aaShaopeng Jia   * The original format is embedded in the country_code_source field of the PhoneNumber object
145254923fc72f0faeb11fe58a545c0314f6051b14aaShaopeng Jia   * passed in. If such information is missing, the number will be formatted into the NATIONAL
1453528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia   * format by default. When the number contains a leading zero and this is unexpected for this
1454528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia   * country, or we don't have a formatting pattern for the number, the method returns the raw input
1455528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia   * when it is available.
145654923fc72f0faeb11fe58a545c0314f6051b14aaShaopeng Jia   *
1457528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia   * Note this method guarantees no digit will be inserted, removed or modified as a result of
1458528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia   * formatting.
1459cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia   *
1460372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * @param number  the phone number that needs to be formatted in its original number format
1461372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * @param regionCallingFrom  the region whose IDD needs to be prefixed if the original number
14624b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia   *     has one
14634b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia   * @return  the formatted phone number in its original number format
146454923fc72f0faeb11fe58a545c0314f6051b14aaShaopeng Jia   */
1465372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  public String formatInOriginalFormat(PhoneNumber number, String regionCallingFrom) {
14665cd062f9cba053c771bcea181fec210279ec030bShaopeng Jia    if (number.hasRawInput() &&
1467528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        (hasUnexpectedItalianLeadingZero(number) || !hasFormattingPatternForNumber(number))) {
14685cd062f9cba053c771bcea181fec210279ec030bShaopeng Jia      // We check if we have the formatting pattern because without that, we might format the number
1469528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia      // as a group without national prefix.
14701940212be2ff2ac5bf7d91eabbdb34e10d9b8e2eShaopeng Jia      return number.getRawInput();
14711940212be2ff2ac5bf7d91eabbdb34e10d9b8e2eShaopeng Jia    }
14724b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia    if (!number.hasCountryCodeSource()) {
147354923fc72f0faeb11fe58a545c0314f6051b14aaShaopeng Jia      return format(number, PhoneNumberFormat.NATIONAL);
147454923fc72f0faeb11fe58a545c0314f6051b14aaShaopeng Jia    }
1475d470984844c388d6766c3de6ac64e93e00480fc9Flavio Lerda    String formattedNumber;
147654923fc72f0faeb11fe58a545c0314f6051b14aaShaopeng Jia    switch (number.getCountryCodeSource()) {
147754923fc72f0faeb11fe58a545c0314f6051b14aaShaopeng Jia      case FROM_NUMBER_WITH_PLUS_SIGN:
1478d470984844c388d6766c3de6ac64e93e00480fc9Flavio Lerda        formattedNumber = format(number, PhoneNumberFormat.INTERNATIONAL);
1479d470984844c388d6766c3de6ac64e93e00480fc9Flavio Lerda        break;
148054923fc72f0faeb11fe58a545c0314f6051b14aaShaopeng Jia      case FROM_NUMBER_WITH_IDD:
1481d470984844c388d6766c3de6ac64e93e00480fc9Flavio Lerda        formattedNumber = formatOutOfCountryCallingNumber(number, regionCallingFrom);
1482d470984844c388d6766c3de6ac64e93e00480fc9Flavio Lerda        break;
148354923fc72f0faeb11fe58a545c0314f6051b14aaShaopeng Jia      case FROM_NUMBER_WITHOUT_PLUS_SIGN:
1484d470984844c388d6766c3de6ac64e93e00480fc9Flavio Lerda        formattedNumber = format(number, PhoneNumberFormat.INTERNATIONAL).substring(1);
1485d470984844c388d6766c3de6ac64e93e00480fc9Flavio Lerda        break;
14864b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia      case FROM_DEFAULT_COUNTRY:
1487528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        // Fall-through to default case.
148854923fc72f0faeb11fe58a545c0314f6051b14aaShaopeng Jia      default:
1489528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        String regionCode = getRegionCodeForCountryCode(number.getCountryCode());
1490528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        // We strip non-digits from the NDD here, and from the raw input later, so that we can
1491528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        // compare them easily.
1492528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        String nationalPrefix = getNddPrefixForRegion(regionCode, true /* strip non-digits */);
1493528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        String nationalFormat = format(number, PhoneNumberFormat.NATIONAL);
1494528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        if (nationalPrefix == null || nationalPrefix.length() == 0) {
1495528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia          // If the region doesn't have a national prefix at all, we can safely return the national
1496528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia          // format without worrying about a national prefix being added.
1497528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia          formattedNumber = nationalFormat;
1498528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia          break;
1499528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        }
1500528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        // Otherwise, we check if the original number was entered with a national prefix.
1501528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        if (rawInputContainsNationalPrefix(
1502528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia            number.getRawInput(), nationalPrefix, regionCode)) {
1503528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia          // If so, we can safely return the national format.
1504528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia          formattedNumber = nationalFormat;
1505528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia          break;
1506528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        }
1507203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia        // Metadata cannot be null here because getNddPrefixForRegion() (above) returns null if
1508203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia        // there is no metadata for the region.
1509528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        PhoneMetadata metadata = getMetadataForRegion(regionCode);
1510528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        String nationalNumber = getNationalSignificantNumber(number);
1511528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        NumberFormat formatRule =
1512528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia            chooseFormattingPatternForNumber(metadata.numberFormats(), nationalNumber);
1513203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia        // The format rule could still be null here if the national number was 0 and there was no
1514203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia        // raw input (this should not be possible for numbers generated by the phonenumber library
1515203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia        // as they would also not have a country calling code and we would have exited earlier).
1516203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia        if (formatRule == null) {
1517203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia          formattedNumber = nationalFormat;
1518203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia          break;
1519203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia        }
1520528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        // When the format we apply to this number doesn't contain national prefix, we can just
1521528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        // return the national format.
15228777f1913d34c3ecf72164ea85292e978e265eddShaopeng Jia        // TODO: Refactor the code below with the code in
15238777f1913d34c3ecf72164ea85292e978e265eddShaopeng Jia        // isNationalPrefixPresentIfRequired.
1524528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        String candidateNationalPrefixRule = formatRule.getNationalPrefixFormattingRule();
1525528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        // We assume that the first-group symbol will never be _before_ the national prefix.
1526528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        int indexOfFirstGroup = candidateNationalPrefixRule.indexOf("$1");
1527528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        if (indexOfFirstGroup <= 0) {
1528528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia          formattedNumber = nationalFormat;
1529528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia          break;
1530528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        }
1531528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        candidateNationalPrefixRule =
1532528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia            candidateNationalPrefixRule.substring(0, indexOfFirstGroup);
1533528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        candidateNationalPrefixRule = normalizeDigitsOnly(candidateNationalPrefixRule);
1534528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        if (candidateNationalPrefixRule.length() == 0) {
1535528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia          // National prefix not used when formatting this number.
1536528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia          formattedNumber = nationalFormat;
1537528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia          break;
1538528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        }
1539528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        // Otherwise, we need to remove the national prefix from our output.
1540528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        NumberFormat numFormatCopy = new NumberFormat();
1541528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        numFormatCopy.mergeFrom(formatRule);
1542528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        numFormatCopy.clearNationalPrefixFormattingRule();
1543528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        List<NumberFormat> numberFormats = new ArrayList<NumberFormat>(1);
1544528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        numberFormats.add(numFormatCopy);
1545528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        formattedNumber = formatByPattern(number, PhoneNumberFormat.NATIONAL, numberFormats);
1546d470984844c388d6766c3de6ac64e93e00480fc9Flavio Lerda        break;
154754923fc72f0faeb11fe58a545c0314f6051b14aaShaopeng Jia    }
1548d470984844c388d6766c3de6ac64e93e00480fc9Flavio Lerda    String rawInput = number.getRawInput();
1549d470984844c388d6766c3de6ac64e93e00480fc9Flavio Lerda    // If no digit is inserted/removed/modified as a result of our formatting, we return the
1550d470984844c388d6766c3de6ac64e93e00480fc9Flavio Lerda    // formatted phone number; otherwise we return the raw input the user entered.
1551203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    if (formattedNumber != null && rawInput.length() > 0) {
1552bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia      String normalizedFormattedNumber = normalizeDiallableCharsOnly(formattedNumber);
1553bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia      String normalizedRawInput = normalizeDiallableCharsOnly(rawInput);
1554203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia      if (!normalizedFormattedNumber.equals(normalizedRawInput)) {
1555203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia        formattedNumber = rawInput;
1556203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia      }
1557203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    }
1558203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    return formattedNumber;
155954923fc72f0faeb11fe58a545c0314f6051b14aaShaopeng Jia  }
156054923fc72f0faeb11fe58a545c0314f6051b14aaShaopeng Jia
1561528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia  // Check if rawInput, which is assumed to be in the national format, has a national prefix. The
1562528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia  // national prefix is assumed to be in digits-only form.
1563528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia  private boolean rawInputContainsNationalPrefix(String rawInput, String nationalPrefix,
1564528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia      String regionCode) {
1565528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    String normalizedNationalNumber = normalizeDigitsOnly(rawInput);
1566528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    if (normalizedNationalNumber.startsWith(nationalPrefix)) {
1567528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia      try {
1568528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        // Some Japanese numbers (e.g. 00777123) might be mistaken to contain the national prefix
1569528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        // when written without it (e.g. 0777123) if we just do prefix matching. To tackle that, we
1570528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        // check the validity of the number if the assumed national prefix is removed (777123 won't
1571528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        // be valid in Japan).
1572528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        return isValidNumber(
1573528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia            parse(normalizedNationalNumber.substring(nationalPrefix.length()), regionCode));
1574528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia      } catch (NumberParseException e) {
1575528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        return false;
1576528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia      }
1577528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    }
1578528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    return false;
1579528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia  }
1580528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia
1581528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia  /**
1582528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia   * Returns true if a number is from a region whose national significant number couldn't contain a
1583528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia   * leading zero, but has the italian_leading_zero field set to true.
1584528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia   */
1585528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia  private boolean hasUnexpectedItalianLeadingZero(PhoneNumber number) {
1586528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    return number.isItalianLeadingZero() && !isLeadingZeroPossible(number.getCountryCode());
1587528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia  }
1588528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia
15895cd062f9cba053c771bcea181fec210279ec030bShaopeng Jia  private boolean hasFormattingPatternForNumber(PhoneNumber number) {
1590528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    int countryCallingCode = number.getCountryCode();
1591528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    String phoneNumberRegion = getRegionCodeForCountryCode(countryCallingCode);
1592528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    PhoneMetadata metadata =
1593528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        getMetadataForRegionOrCallingCode(countryCallingCode, phoneNumberRegion);
15945cd062f9cba053c771bcea181fec210279ec030bShaopeng Jia    if (metadata == null) {
15955cd062f9cba053c771bcea181fec210279ec030bShaopeng Jia      return false;
15965cd062f9cba053c771bcea181fec210279ec030bShaopeng Jia    }
15975cd062f9cba053c771bcea181fec210279ec030bShaopeng Jia    String nationalNumber = getNationalSignificantNumber(number);
15985cd062f9cba053c771bcea181fec210279ec030bShaopeng Jia    NumberFormat formatRule =
15995cd062f9cba053c771bcea181fec210279ec030bShaopeng Jia        chooseFormattingPatternForNumber(metadata.numberFormats(), nationalNumber);
16005cd062f9cba053c771bcea181fec210279ec030bShaopeng Jia    return formatRule != null;
16015cd062f9cba053c771bcea181fec210279ec030bShaopeng Jia  }
16025cd062f9cba053c771bcea181fec210279ec030bShaopeng Jia
16035c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia  /**
1604372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * Formats a phone number for out-of-country dialing purposes.
1605372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *
1606372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * Note that in this version, if the number was entered originally using alpha characters and
1607372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * this version of the number is stored in raw_input, this representation of the number will be
1608372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * used rather than the digit representation. Grouping information, as specified by characters
1609372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * such as "-" and " ", will be retained.
1610372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *
1611372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * <p><b>Caveats:</b></p>
1612372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * <ul>
1613372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *  <li> This will not produce good results if the country calling code is both present in the raw
1614372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *       input _and_ is the start of the national number. This is not a problem in the regions
1615372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *       which typically use alpha numbers.
1616372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *  <li> This will also not produce good results if the raw input has any grouping information
1617372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *       within the first three digits of the national number, and if the function needs to strip
1618372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *       preceding digits/words in the raw input before these digits. Normally people group the
1619372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *       first three digits together so this is not a huge problem - and will be fixed if it
1620372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *       proves to be so.
1621372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * </ul>
1622372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *
1623372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * @param number  the phone number that needs to be formatted
1624372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * @param regionCallingFrom  the region where the call is being placed
1625372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * @return  the formatted phone number
1626372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   */
1627d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia  public String formatOutOfCountryKeepingAlphaChars(PhoneNumber number,
1628d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia                                                    String regionCallingFrom) {
1629372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    String rawInput = number.getRawInput();
1630372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    // If there is no raw input, then we can't keep alpha characters because there aren't any.
1631372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    // In this case, we return formatOutOfCountryCallingNumber.
1632372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    if (rawInput.length() == 0) {
1633372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      return formatOutOfCountryCallingNumber(number, regionCallingFrom);
1634372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    }
1635372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    int countryCode = number.getCountryCode();
1636528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    if (!hasValidCountryCallingCode(countryCode)) {
1637372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      return rawInput;
1638372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    }
1639372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    // Strip any prefix such as country calling code, IDD, that was present. We do this by comparing
1640372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    // the number in raw_input with the parsed number.
1641372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    // To do this, first we normalize punctuation. We retain number grouping symbols such as " "
1642372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    // only.
1643372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    rawInput = normalizeHelper(rawInput, ALL_PLUS_NUMBER_GROUPING_SYMBOLS, true);
1644372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    // Now we trim everything before the first three digits in the parsed number. We choose three
1645372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    // because all valid alpha numbers have 3 digits at the start - if it does not, then we don't
1646372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    // trim anything at all. Similarly, if the national number was less than three digits, we don't
1647372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    // trim anything at all.
1648372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    String nationalNumber = getNationalSignificantNumber(number);
1649372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    if (nationalNumber.length() > 3) {
1650372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      int firstNationalNumberDigit = rawInput.indexOf(nationalNumber.substring(0, 3));
1651372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      if (firstNationalNumberDigit != -1) {
1652372bff8dd464574d36737d47e495cad14346653cShaopeng Jia        rawInput = rawInput.substring(firstNationalNumberDigit);
1653372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      }
1654372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    }
1655528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    PhoneMetadata metadataForRegionCallingFrom = getMetadataForRegion(regionCallingFrom);
1656372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    if (countryCode == NANPA_COUNTRY_CODE) {
1657372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      if (isNANPACountry(regionCallingFrom)) {
1658372bff8dd464574d36737d47e495cad14346653cShaopeng Jia        return countryCode + " " + rawInput;
1659372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      }
1660203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    } else if (metadataForRegionCallingFrom != null &&
1661cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia               countryCode == getCountryCodeForValidRegion(regionCallingFrom)) {
1662cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia      NumberFormat formattingPattern =
1663cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia          chooseFormattingPatternForNumber(metadataForRegionCallingFrom.numberFormats(),
1664cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia                                           nationalNumber);
1665cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia      if (formattingPattern == null) {
1666cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia        // If no pattern above is matched, we format the original input.
1667cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia        return rawInput;
1668372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      }
1669cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia      NumberFormat newFormat = new NumberFormat();
1670cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia      newFormat.mergeFrom(formattingPattern);
1671cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia      // The first group is the first group of digits that the user wrote together.
1672cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia      newFormat.setPattern("(\\d+)(.*)");
1673cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia      // Here we just concatenate them back together after the national prefix has been fixed.
1674cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia      newFormat.setFormat("$1$2");
1675cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia      // Now we format using this pattern instead of the default pattern, but with the national
1676cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia      // prefix prefixed if necessary.
1677372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      // This will not work in the cases where the pattern (and not the leading digits) decide
1678372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      // whether a national prefix needs to be used, since we have overridden the pattern to match
1679372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      // anything, but that is not the case in the metadata to date.
1680cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia      return formatNsnUsingPattern(rawInput, newFormat, PhoneNumberFormat.NATIONAL);
1681372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    }
1682528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    String internationalPrefixForFormatting = "";
1683528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    // If an unsupported region-calling-from is entered, or a country with multiple international
1684528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    // prefixes, the international format of the number is returned, unless there is a preferred
1685528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    // international prefix.
1686528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    if (metadataForRegionCallingFrom != null) {
1687528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia      String internationalPrefix = metadataForRegionCallingFrom.getInternationalPrefix();
1688528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia      internationalPrefixForFormatting =
1689528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia          UNIQUE_INTERNATIONAL_PREFIX.matcher(internationalPrefix).matches()
1690528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia          ? internationalPrefix
1691528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia          : metadataForRegionCallingFrom.getPreferredInternationalPrefix();
1692528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    }
1693372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    StringBuilder formattedNumber = new StringBuilder(rawInput);
1694528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    String regionCode = getRegionCodeForCountryCode(countryCode);
1695203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    // Metadata cannot be null because the country calling code is valid.
1696528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    PhoneMetadata metadataForRegion = getMetadataForRegionOrCallingCode(countryCode, regionCode);
1697cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia    maybeAppendFormattedExtension(number, metadataForRegion,
1698cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia                                  PhoneNumberFormat.INTERNATIONAL, formattedNumber);
1699372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    if (internationalPrefixForFormatting.length() > 0) {
1700372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      formattedNumber.insert(0, " ").insert(0, countryCode).insert(0, " ")
1701372bff8dd464574d36737d47e495cad14346653cShaopeng Jia          .insert(0, internationalPrefixForFormatting);
1702372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    } else {
1703528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia      // Invalid region entered as country-calling-from (so no metadata was found for it) or the
1704528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia      // region chosen has multiple international dialling prefixes.
1705bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia      logger.log(Level.WARNING,
1706b0e21c22b1ca6b9aeb1426924cdf42a221c3d416Shaopeng Jia                 "Trying to format number from invalid region "
1707b0e21c22b1ca6b9aeb1426924cdf42a221c3d416Shaopeng Jia                 + regionCallingFrom
1708b0e21c22b1ca6b9aeb1426924cdf42a221c3d416Shaopeng Jia                 + ". International formatting applied.");
1709cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia      prefixNumberWithCountryCallingCode(countryCode,
1710b0e21c22b1ca6b9aeb1426924cdf42a221c3d416Shaopeng Jia                                         PhoneNumberFormat.INTERNATIONAL,
1711b0e21c22b1ca6b9aeb1426924cdf42a221c3d416Shaopeng Jia                                         formattedNumber);
1712372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    }
1713372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    return formattedNumber.toString();
1714372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  }
1715372bff8dd464574d36737d47e495cad14346653cShaopeng Jia
1716372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  /**
17175c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia   * Gets the national significant number of the a phone number. Note a national significant number
17185c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia   * doesn't contain a national prefix or any formatting.
17195c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia   *
1720d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   * @param number  the phone number for which the national significant number is needed
17215c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia   * @return  the national significant number of the PhoneNumber object passed in
17225c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia   */
1723372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  public String getNationalSignificantNumber(PhoneNumber number) {
1724f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia    // If leading zero(s) have been set, we prefix this now. Note this is not a national prefix.
1725f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia    StringBuilder nationalNumber = new StringBuilder();
1726f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia    if (number.isItalianLeadingZero()) {
1727f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia      char[] zeros = new char[number.getNumberOfLeadingZeros()];
1728f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia      Arrays.fill(zeros, '0');
1729f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia      nationalNumber.append(new String(zeros));
1730f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia    }
17311524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    nationalNumber.append(number.getNationalNumber());
17321524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    return nationalNumber.toString();
17331524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
17341524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
17351524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
17361524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * A helper function that is used by format and formatByPattern.
17371524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
1738cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia  private void prefixNumberWithCountryCallingCode(int countryCallingCode,
1739cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia                                                  PhoneNumberFormat numberFormat,
1740cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia                                                  StringBuilder formattedNumber) {
17411524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    switch (numberFormat) {
17421524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      case E164:
1743372bff8dd464574d36737d47e495cad14346653cShaopeng Jia        formattedNumber.insert(0, countryCallingCode).insert(0, PLUS_SIGN);
1744be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia        return;
17451524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      case INTERNATIONAL:
1746372bff8dd464574d36737d47e495cad14346653cShaopeng Jia        formattedNumber.insert(0, " ").insert(0, countryCallingCode).insert(0, PLUS_SIGN);
1747372bff8dd464574d36737d47e495cad14346653cShaopeng Jia        return;
1748372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      case RFC3966:
1749b0e21c22b1ca6b9aeb1426924cdf42a221c3d416Shaopeng Jia        formattedNumber.insert(0, "-").insert(0, countryCallingCode).insert(0, PLUS_SIGN)
1750b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia            .insert(0, RFC3966_PREFIX);
1751be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia        return;
17521524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      case NATIONAL:
17531524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      default:
1754be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia        return;
17551524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
17561524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
17571524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
1758cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia  // Simple wrapper of formatNsn for the common case of no carrier code.
1759cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia  private String formatNsn(String number, PhoneMetadata metadata, PhoneNumberFormat numberFormat) {
1760cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia    return formatNsn(number, metadata, numberFormat, null);
1761df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia  }
17624b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia
1763372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  // Note in some regions, the national number can be written in two completely different ways
17641524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  // depending on whether it forms part of the NATIONAL format or INTERNATIONAL format. The
17654b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia  // numberFormat parameter here is used to specify which format to use for those cases. If a
17664b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia  // carrierCode is specified, this will be inserted into the formatted string to replace $CC.
1767cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia  private String formatNsn(String number,
1768cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia                           PhoneMetadata metadata,
1769cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia                           PhoneNumberFormat numberFormat,
1770cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia                           String carrierCode) {
1771372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    List<NumberFormat> intlNumberFormats = metadata.intlNumberFormats();
17721524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    // When the intlNumberFormats exists, we use that to format national number for the
17731524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    // INTERNATIONAL format instead of using the numberDesc.numberFormats.
17741524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    List<NumberFormat> availableFormats =
17751524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia        (intlNumberFormats.size() == 0 || numberFormat == PhoneNumberFormat.NATIONAL)
1776372bff8dd464574d36737d47e495cad14346653cShaopeng Jia        ? metadata.numberFormats()
1777372bff8dd464574d36737d47e495cad14346653cShaopeng Jia        : metadata.intlNumberFormats();
1778cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia    NumberFormat formattingPattern = chooseFormattingPatternForNumber(availableFormats, number);
1779cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia    return (formattingPattern == null)
1780cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia        ? number
1781cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia        : formatNsnUsingPattern(number, formattingPattern, numberFormat, carrierCode);
17821524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
17831524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
1784b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia  NumberFormat chooseFormattingPatternForNumber(List<NumberFormat> availableFormats,
1785b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia                                                String nationalNumber) {
1786a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia    for (NumberFormat numFormat : availableFormats) {
1787a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia      int size = numFormat.leadingDigitsPatternSize();
1788a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia      if (size == 0 || regexCache.getPatternForRegex(
1789a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia              // We always use the last leading_digits_pattern, as it is the most detailed.
1790a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia              numFormat.getLeadingDigitsPattern(size - 1)).matcher(nationalNumber).lookingAt()) {
1791a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia        Matcher m = regexCache.getPatternForRegex(numFormat.getPattern()).matcher(nationalNumber);
1792a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia        if (m.matches()) {
1793a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia          return numFormat;
1794a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia        }
1795a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia      }
1796a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia    }
1797a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia    return null;
1798a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia  }
1799a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia
1800cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia  // Simple wrapper of formatNsnUsingPattern for the common case of no carrier code.
1801b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia  String formatNsnUsingPattern(String nationalNumber,
1802b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia                               NumberFormat formattingPattern,
1803b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia                               PhoneNumberFormat numberFormat) {
1804cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia    return formatNsnUsingPattern(nationalNumber, formattingPattern, numberFormat, null);
18054b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia  }
18064b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia
1807203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia  // Note that carrierCode is optional - if null or an empty string, no carrier code replacement
180852699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia  // will take place.
1809cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia  private String formatNsnUsingPattern(String nationalNumber,
1810cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia                                       NumberFormat formattingPattern,
1811cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia                                       PhoneNumberFormat numberFormat,
1812cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia                                       String carrierCode) {
1813cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia    String numberFormatRule = formattingPattern.getFormat();
1814cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia    Matcher m =
1815cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia        regexCache.getPatternForRegex(formattingPattern.getPattern()).matcher(nationalNumber);
1816cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia    String formattedNationalNumber = "";
1817a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia    if (numberFormat == PhoneNumberFormat.NATIONAL &&
1818a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia        carrierCode != null && carrierCode.length() > 0 &&
1819cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia        formattingPattern.getDomesticCarrierCodeFormattingRule().length() > 0) {
1820a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia      // Replace the $CC in the formatting rule with the desired carrier code.
1821cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia      String carrierCodeFormattingRule = formattingPattern.getDomesticCarrierCodeFormattingRule();
1822a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia      carrierCodeFormattingRule =
1823a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia          CC_PATTERN.matcher(carrierCodeFormattingRule).replaceFirst(carrierCode);
1824a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia      // Now replace the $FG in the formatting rule with the first group and the carrier code
1825a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia      // combined in the appropriate way.
1826a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia      numberFormatRule = FIRST_GROUP_PATTERN.matcher(numberFormatRule)
1827a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia          .replaceFirst(carrierCodeFormattingRule);
1828cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia      formattedNationalNumber = m.replaceAll(numberFormatRule);
1829a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia    } else {
1830a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia      // Use the national prefix formatting rule instead.
1831cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia      String nationalPrefixFormattingRule = formattingPattern.getNationalPrefixFormattingRule();
1832a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia      if (numberFormat == PhoneNumberFormat.NATIONAL &&
1833a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia          nationalPrefixFormattingRule != null &&
1834a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia          nationalPrefixFormattingRule.length() > 0) {
1835a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia        Matcher firstGroupMatcher = FIRST_GROUP_PATTERN.matcher(numberFormatRule);
1836cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia        formattedNationalNumber =
1837cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia            m.replaceAll(firstGroupMatcher.replaceFirst(nationalPrefixFormattingRule));
1838a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia      } else {
1839cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia        formattedNationalNumber = m.replaceAll(numberFormatRule);
18401524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      }
18411524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
1842cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia    if (numberFormat == PhoneNumberFormat.RFC3966) {
1843cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia      // Strip any leading punctuation.
1844cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia      Matcher matcher = SEPARATOR_PATTERN.matcher(formattedNationalNumber);
1845cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia      if (matcher.lookingAt()) {
1846cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia        formattedNationalNumber = matcher.replaceFirst("");
1847cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia      }
1848cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia      // Replace the rest with a dash between each number group.
1849cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia      formattedNationalNumber = matcher.reset(formattedNationalNumber).replaceAll("-");
1850cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia    }
1851cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia    return formattedNationalNumber;
18521524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
18531524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
18541524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
1855372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * Gets a valid number for the specified region.
18561524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *
1857d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   * @param regionCode  the region for which an example number is needed
1858372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * @return  a valid fixed-line number for the specified region. Returns null when the metadata
1859528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia   *    does not contain such information, or the region 001 is passed in. For 001 (representing
1860528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia   *    non-geographical numbers), call {@link #getExampleNumberForNonGeoEntity} instead.
18611524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
18621524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  public PhoneNumber getExampleNumber(String regionCode) {
18631524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    return getExampleNumberForType(regionCode, PhoneNumberType.FIXED_LINE);
18641524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
18651524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
18661524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
1867372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * Gets a valid number for the specified region and number type.
18681524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *
1869d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   * @param regionCode  the region for which an example number is needed
18701524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @param type  the type of number that is needed
1871372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * @return  a valid number for the specified region and type. Returns null when the metadata
1872528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia   *     does not contain such information or if an invalid region or region 001 was entered.
1873528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia   *     For 001 (representing non-geographical numbers), call
1874528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia   *     {@link #getExampleNumberForNonGeoEntity} instead.
18751524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
18761524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  public PhoneNumber getExampleNumberForType(String regionCode, PhoneNumberType type) {
1877372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    // Check the region code is valid.
1878372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    if (!isValidRegionCode(regionCode)) {
1879bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia      logger.log(Level.WARNING, "Invalid or unknown region code provided: " + regionCode);
1880372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      return null;
1881372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    }
18821524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    PhoneNumberDesc desc = getNumberDescByType(getMetadataForRegion(regionCode), type);
18831524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    try {
18841524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      if (desc.hasExampleNumber()) {
18851524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia        return parse(desc.getExampleNumber(), regionCode);
18861524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      }
18871524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    } catch (NumberParseException e) {
1888bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia      logger.log(Level.SEVERE, e.toString());
18891524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
18901524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    return null;
18911524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
18921524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
18931524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
1894528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia   * Gets a valid number for the specified country calling code for a non-geographical entity.
1895528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia   *
1896528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia   * @param countryCallingCode  the country calling code for a non-geographical entity
1897528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia   * @return  a valid number for the non-geographical entity. Returns null when the metadata
1898528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia   *    does not contain such information, or the country calling code passed in does not belong
1899528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia   *    to a non-geographical entity.
1900528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia   */
1901528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia  public PhoneNumber getExampleNumberForNonGeoEntity(int countryCallingCode) {
1902528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    PhoneMetadata metadata = getMetadataForNonGeographicalRegion(countryCallingCode);
1903528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    if (metadata != null) {
1904528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia      PhoneNumberDesc desc = metadata.getGeneralDesc();
1905528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia      try {
1906528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        if (desc.hasExampleNumber()) {
1907528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia          return parse("+" + countryCallingCode + desc.getExampleNumber(), "ZZ");
1908528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        }
1909528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia      } catch (NumberParseException e) {
1910bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia        logger.log(Level.SEVERE, e.toString());
1911528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia      }
1912cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia    } else {
1913bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia      logger.log(Level.WARNING,
1914cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia                 "Invalid or unknown country calling code provided: " + countryCallingCode);
1915528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    }
1916528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    return null;
1917528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia  }
1918528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia
1919528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia  /**
1920be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia   * Appends the formatted extension of a phone number to formattedNumber, if the phone number had
1921be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia   * an extension specified.
19221524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
1923cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia  private void maybeAppendFormattedExtension(PhoneNumber number, PhoneMetadata metadata,
1924cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia                                             PhoneNumberFormat numberFormat,
1925cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia                                             StringBuilder formattedNumber) {
1926372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    if (number.hasExtension() && number.getExtension().length() > 0) {
1927372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      if (numberFormat == PhoneNumberFormat.RFC3966) {
1928372bff8dd464574d36737d47e495cad14346653cShaopeng Jia        formattedNumber.append(RFC3966_EXTN_PREFIX).append(number.getExtension());
1929be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia      } else {
1930cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia        if (metadata.hasPreferredExtnPrefix()) {
1931cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia          formattedNumber.append(metadata.getPreferredExtnPrefix()).append(number.getExtension());
1932cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia        } else {
1933cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia          formattedNumber.append(DEFAULT_EXTN_PREFIX).append(number.getExtension());
1934cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia        }
1935be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia      }
1936372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    }
1937372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  }
1938372bff8dd464574d36737d47e495cad14346653cShaopeng Jia
19391524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  PhoneNumberDesc getNumberDescByType(PhoneMetadata metadata, PhoneNumberType type) {
19401524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    switch (type) {
19411524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      case PREMIUM_RATE:
19421524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia        return metadata.getPremiumRate();
19431524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      case TOLL_FREE:
19441524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia        return metadata.getTollFree();
19451524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      case MOBILE:
19461524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia        return metadata.getMobile();
19471524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      case FIXED_LINE:
19481524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      case FIXED_LINE_OR_MOBILE:
19491524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia        return metadata.getFixedLine();
19501524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      case SHARED_COST:
19511524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia        return metadata.getSharedCost();
19521524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      case VOIP:
19531524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia        return metadata.getVoip();
19541524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      case PERSONAL_NUMBER:
19551524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia        return metadata.getPersonalNumber();
1956b2697412130f6d087dde01fb1a978f7e5840a5faShaopeng Jia      case PAGER:
1957b2697412130f6d087dde01fb1a978f7e5840a5faShaopeng Jia        return metadata.getPager();
195874aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia      case UAN:
195974aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia        return metadata.getUan();
1960528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia      case VOICEMAIL:
1961528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        return metadata.getVoicemail();
19621524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      default:
19631524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia        return metadata.getGeneralDesc();
19641524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
19651524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
19661524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
19671524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
19681524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * Gets the type of a phone number.
19691524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *
19701524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @param number  the phone number that we want to know the type
19711524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @return  the type of the phone number
19721524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
19731524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  public PhoneNumberType getNumberType(PhoneNumber number) {
19741524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    String regionCode = getRegionCodeForNumber(number);
1975203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    PhoneMetadata metadata = getMetadataForRegionOrCallingCode(number.getCountryCode(), regionCode);
1976203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    if (metadata == null) {
19771524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      return PhoneNumberType.UNKNOWN;
19781524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
1979be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    String nationalSignificantNumber = getNationalSignificantNumber(number);
1980528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    return getNumberTypeHelper(nationalSignificantNumber, metadata);
19811524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
19821524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
19831524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  private PhoneNumberType getNumberTypeHelper(String nationalNumber, PhoneMetadata metadata) {
19841524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    PhoneNumberDesc generalNumberDesc = metadata.getGeneralDesc();
19851524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    if (!generalNumberDesc.hasNationalNumberPattern() ||
19861524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia        !isNumberMatchingDesc(nationalNumber, generalNumberDesc)) {
19871524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      return PhoneNumberType.UNKNOWN;
19881524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
19891524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
19901524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    if (isNumberMatchingDesc(nationalNumber, metadata.getPremiumRate())) {
19911524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      return PhoneNumberType.PREMIUM_RATE;
19921524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
19931524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    if (isNumberMatchingDesc(nationalNumber, metadata.getTollFree())) {
19941524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      return PhoneNumberType.TOLL_FREE;
19951524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
19961524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    if (isNumberMatchingDesc(nationalNumber, metadata.getSharedCost())) {
19971524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      return PhoneNumberType.SHARED_COST;
19981524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
19991524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    if (isNumberMatchingDesc(nationalNumber, metadata.getVoip())) {
20001524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      return PhoneNumberType.VOIP;
20011524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
20021524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    if (isNumberMatchingDesc(nationalNumber, metadata.getPersonalNumber())) {
20031524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      return PhoneNumberType.PERSONAL_NUMBER;
20041524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
2005b2697412130f6d087dde01fb1a978f7e5840a5faShaopeng Jia    if (isNumberMatchingDesc(nationalNumber, metadata.getPager())) {
2006b2697412130f6d087dde01fb1a978f7e5840a5faShaopeng Jia      return PhoneNumberType.PAGER;
2007b2697412130f6d087dde01fb1a978f7e5840a5faShaopeng Jia    }
200874aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia    if (isNumberMatchingDesc(nationalNumber, metadata.getUan())) {
200974aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia      return PhoneNumberType.UAN;
201074aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia    }
2011528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    if (isNumberMatchingDesc(nationalNumber, metadata.getVoicemail())) {
2012528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia      return PhoneNumberType.VOICEMAIL;
2013528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    }
20141524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
20151524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    boolean isFixedLine = isNumberMatchingDesc(nationalNumber, metadata.getFixedLine());
20161524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    if (isFixedLine) {
2017d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia      if (metadata.isSameMobileAndFixedLinePattern()) {
20181524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia        return PhoneNumberType.FIXED_LINE_OR_MOBILE;
20191524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      } else if (isNumberMatchingDesc(nationalNumber, metadata.getMobile())) {
20201524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia        return PhoneNumberType.FIXED_LINE_OR_MOBILE;
20211524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      }
20221524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      return PhoneNumberType.FIXED_LINE;
20231524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
20241524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    // Otherwise, test to see if the number is mobile. Only do this if certain that the patterns for
20251524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    // mobile and fixed line aren't the same.
2026d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia    if (!metadata.isSameMobileAndFixedLinePattern() &&
20271524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia        isNumberMatchingDesc(nationalNumber, metadata.getMobile())) {
20281524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      return PhoneNumberType.MOBILE;
20291524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
20301524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    return PhoneNumberType.UNKNOWN;
20311524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
20321524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
2033203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia  /**
2034203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia   * Returns the metadata for the given region code or {@code null} if the region code is invalid
2035203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia   * or unknown.
2036203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia   */
20371524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  PhoneMetadata getMetadataForRegion(String regionCode) {
2038fa42140081949568565af7dc8c22f0600ad90a8aShaopeng Jia    if (!isValidRegionCode(regionCode)) {
20391524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      return null;
20401524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
2041a1d3a5ed3af9cee85acdad939042a851a629f18cShaopeng Jia    synchronized (regionToMetadataMap) {
2042a1d3a5ed3af9cee85acdad939042a851a629f18cShaopeng Jia      if (!regionToMetadataMap.containsKey(regionCode)) {
2043528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        // The regionCode here will be valid and won't be '001', so we don't need to worry about
2044528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        // what to pass in for the country calling code.
20459ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia        loadMetadataFromFile(currentFilePrefix, regionCode, 0, metadataLoader);
2046a1d3a5ed3af9cee85acdad939042a851a629f18cShaopeng Jia      }
2047fa42140081949568565af7dc8c22f0600ad90a8aShaopeng Jia    }
2048372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    return regionToMetadataMap.get(regionCode);
20491524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
20501524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
2051528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia  PhoneMetadata getMetadataForNonGeographicalRegion(int countryCallingCode) {
2052528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    synchronized (countryCodeToNonGeographicalMetadataMap) {
2053528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia      if (!countryCallingCodeToRegionCodeMap.containsKey(countryCallingCode)) {
2054528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        return null;
2055528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia      }
2056528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia      if (!countryCodeToNonGeographicalMetadataMap.containsKey(countryCallingCode)) {
20579ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia        loadMetadataFromFile(
20589ecee8b74bf330f20a902e4b974eddb7abedd627Shaopeng Jia            currentFilePrefix, REGION_CODE_FOR_NON_GEO_ENTITY, countryCallingCode, metadataLoader);
2059528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia      }
2060528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    }
2061528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    return countryCodeToNonGeographicalMetadataMap.get(countryCallingCode);
2062528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia  }
2063528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia
2064bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia  boolean isNumberPossibleForDesc(String nationalNumber, PhoneNumberDesc numberDesc) {
2065be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    Matcher possibleNumberPatternMatcher =
2066be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia        regexCache.getPatternForRegex(numberDesc.getPossibleNumberPattern())
2067be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia            .matcher(nationalNumber);
2068bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia    return possibleNumberPatternMatcher.matches();
2069bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia  }
2070bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia
2071bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia  boolean isNumberMatchingDesc(String nationalNumber, PhoneNumberDesc numberDesc) {
2072be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    Matcher nationalNumberPatternMatcher =
2073be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia        regexCache.getPatternForRegex(numberDesc.getNationalNumberPattern())
2074be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia            .matcher(nationalNumber);
2075bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia    return isNumberPossibleForDesc(nationalNumber, numberDesc) &&
2076bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia        nationalNumberPatternMatcher.matches();
20771524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
20781524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
20791524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
20801524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * Tests whether a phone number matches a valid pattern. Note this doesn't verify the number
20811524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * is actually in use, which is impossible to tell by just looking at a number itself.
20821524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *
20831524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @param number       the phone number that we want to validate
20841524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @return  a boolean that indicates whether the number is of a valid pattern
20851524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
20861524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  public boolean isValidNumber(PhoneNumber number) {
20871524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    String regionCode = getRegionCodeForNumber(number);
2088528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    return isValidNumberForRegion(number, regionCode);
20891524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
20901524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
20911524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
20921524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * Tests whether a phone number is valid for a certain region. Note this doesn't verify the number
20931524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * is actually in use, which is impossible to tell by just looking at a number itself. If the
2094372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * country calling code is not the same as the country calling code for the region, this
2095372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * immediately exits with false. After this, the specific number pattern rules for the region are
2096372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * examined. This is useful for determining for example whether a particular number is valid for
2097372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * Canada, rather than just a valid NANPA number.
2098203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia   * Warning: In most cases, you want to use {@link #isValidNumber} instead. For example, this
2099203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia   * method will mark numbers from British Crown dependencies such as the Isle of Man as invalid for
2100203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia   * the region "GB" (United Kingdom), since it has its own region code, "IM", which may be
2101203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia   * undesirable.
21021524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *
21031524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @param number       the phone number that we want to validate
2104d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   * @param regionCode   the region that we want to validate the phone number for
21051524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @return  a boolean that indicates whether the number is of a valid pattern
21061524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
21071524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  public boolean isValidNumberForRegion(PhoneNumber number, String regionCode) {
2108528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    int countryCode = number.getCountryCode();
2109cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia    PhoneMetadata metadata = getMetadataForRegionOrCallingCode(countryCode, regionCode);
2110cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia    if ((metadata == null) ||
2111528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        (!REGION_CODE_FOR_NON_GEO_ENTITY.equals(regionCode) &&
2112cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia         countryCode != getCountryCodeForValidRegion(regionCode))) {
2113cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia      // Either the region code was invalid, or the country calling code for this number does not
2114cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia      // match that of the region code.
21151524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      return false;
21161524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
21171524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    PhoneNumberDesc generalNumDesc = metadata.getGeneralDesc();
21185c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia    String nationalSignificantNumber = getNationalSignificantNumber(number);
21191524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
2120372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    // For regions where we don't have metadata for PhoneNumberDesc, we treat any number passed in
2121372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    // as a valid number if its national significant number is between the minimum and maximum
21221524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    // lengths defined by ITU for a national significant number.
21231524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    if (!generalNumDesc.hasNationalNumberPattern()) {
21241524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      int numberLength = nationalSignificantNumber.length();
21251524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      return numberLength > MIN_LENGTH_FOR_NSN && numberLength <= MAX_LENGTH_FOR_NSN;
21261524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
212709104d6c45e3cfae9264367232dd17890e0e8675Shaopeng Jia    return getNumberTypeHelper(nationalSignificantNumber, metadata) != PhoneNumberType.UNKNOWN;
21281524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
21291524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
21301524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
2131372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * Returns the region where a phone number is from. This could be used for geocoding at the region
2132372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * level.
21331524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *
21341524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @param number  the phone number whose origin we want to know
2135372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * @return  the region where the phone number is from, or null if no region matches this calling
2136372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *     code
21371524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
21381524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  public String getRegionCodeForNumber(PhoneNumber number) {
21391524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    int countryCode = number.getCountryCode();
2140372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    List<String> regions = countryCallingCodeToRegionCodeMap.get(countryCode);
21414b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia    if (regions == null) {
2142528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia      String numberString = getNationalSignificantNumber(number);
2143bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia      logger.log(Level.WARNING,
2144528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia                 "Missing/invalid country_code (" + countryCode + ") for number " + numberString);
21454b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia      return null;
21464b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia    }
21474b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia    if (regions.size() == 1) {
21484b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia      return regions.get(0);
21494b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia    } else {
21504b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia      return getRegionCodeForNumberFromRegionList(number, regions);
21511524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
21521524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
21531524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
21541524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  private String getRegionCodeForNumberFromRegionList(PhoneNumber number,
21554b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia                                                      List<String> regionCodes) {
2156372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    String nationalNumber = getNationalSignificantNumber(number);
21571524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    for (String regionCode : regionCodes) {
21584b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia      // If leadingDigits is present, use this. Otherwise, do full validation.
2159203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia      // Metadata cannot be null because the region codes come from the country calling code map.
21604b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia      PhoneMetadata metadata = getMetadataForRegion(regionCode);
21614b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia      if (metadata.hasLeadingDigits()) {
21624b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia        if (regexCache.getPatternForRegex(metadata.getLeadingDigits())
21634b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia                .matcher(nationalNumber).lookingAt()) {
21644b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia          return regionCode;
21654b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia        }
21664b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia      } else if (getNumberTypeHelper(nationalNumber, metadata) != PhoneNumberType.UNKNOWN) {
21671524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia        return regionCode;
21681524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      }
21691524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
21701524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    return null;
21711524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
21721524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
21731524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
2174372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * Returns the region code that matches the specific country calling code. In the case of no
2175372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * region code being found, ZZ will be returned. In the case of multiple regions, the one
2176f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia   * designated in the metadata as the "main" region for this calling code will be returned. If the
2177f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia   * countryCallingCode entered is valid but doesn't match a specific region (such as in the case of
2178f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia   * non-geographical calling codes like 800) the value "001" will be returned (corresponding to
2179f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia   * the value for World in the UN M.49 schema).
21801524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
2181372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  public String getRegionCodeForCountryCode(int countryCallingCode) {
2182372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    List<String> regionCodes = countryCallingCodeToRegionCodeMap.get(countryCallingCode);
218374aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia    return regionCodes == null ? UNKNOWN_REGION : regionCodes.get(0);
21841524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
21851524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
21861524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
2187203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia   * Returns a list with the region codes that match the specific country calling code. For
2188203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia   * non-geographical country calling codes, the region code 001 is returned. Also, in the case
2189203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia   * of no region code being found, an empty list is returned.
2190203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia   */
2191203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia  public List<String> getRegionCodesForCountryCode(int countryCallingCode) {
2192203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    List<String> regionCodes = countryCallingCodeToRegionCodeMap.get(countryCallingCode);
2193203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    return Collections.unmodifiableList(regionCodes == null ? new ArrayList<String>(0)
2194203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia                                                            : regionCodes);
2195203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia  }
2196203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia
2197203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia  /**
21981524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * Returns the country calling code for a specific region. For example, this would be 1 for the
21991524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * United States, and 64 for New Zealand.
22001524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *
2201d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   * @param regionCode  the region that we want to get the country calling code for
2202372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * @return  the country calling code for the region denoted by regionCode
22031524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
22041524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  public int getCountryCodeForRegion(String regionCode) {
2205be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    if (!isValidRegionCode(regionCode)) {
2206bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia      logger.log(Level.WARNING,
2207528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia                 "Invalid or missing region code ("
2208528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia                  + ((regionCode == null) ? "null" : regionCode)
2209528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia                  + ") provided.");
22101524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      return 0;
22111524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
2212cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia    return getCountryCodeForValidRegion(regionCode);
2213cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia  }
2214cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia
2215cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia  /**
2216cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia   * Returns the country calling code for a specific region. For example, this would be 1 for the
2217cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia   * United States, and 64 for New Zealand. Assumes the region is already valid.
2218cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia   *
2219cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia   * @param regionCode  the region that we want to get the country calling code for
2220cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia   * @return  the country calling code for the region denoted by regionCode
2221203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia   * @throws IllegalArgumentException if the region is invalid
2222cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia   */
2223cc0ae7326023c5da91dd9a84035c3dc3f6cc372fShaopeng Jia  private int getCountryCodeForValidRegion(String regionCode) {
2224be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    PhoneMetadata metadata = getMetadataForRegion(regionCode);
2225203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    if (metadata == null) {
2226203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia      throw new IllegalArgumentException("Invalid region code: " + regionCode);
2227203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    }
22281524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    return metadata.getCountryCode();
22291524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
22301524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
22311524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
2232f59ccfca9dd02c4e3cf3e06b5cf184a8d0e67626Shaopeng Jia   * Returns the national dialling prefix for a specific region. For example, this would be 1 for
2233f59ccfca9dd02c4e3cf3e06b5cf184a8d0e67626Shaopeng Jia   * the United States, and 0 for New Zealand. Set stripNonDigits to true to strip symbols like "~"
2234f59ccfca9dd02c4e3cf3e06b5cf184a8d0e67626Shaopeng Jia   * (which indicates a wait for a dialling tone) from the prefix returned. If no national prefix is
2235f59ccfca9dd02c4e3cf3e06b5cf184a8d0e67626Shaopeng Jia   * present, we return null.
2236f59ccfca9dd02c4e3cf3e06b5cf184a8d0e67626Shaopeng Jia   *
2237372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * <p>Warning: Do not use this method for do-your-own formatting - for some regions, the
2238372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * national dialling prefix is used only for certain types of numbers. Use the library's
2239372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * formatting functions to prefix the national prefix when required.
2240f59ccfca9dd02c4e3cf3e06b5cf184a8d0e67626Shaopeng Jia   *
2241d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   * @param regionCode  the region that we want to get the dialling prefix for
2242f59ccfca9dd02c4e3cf3e06b5cf184a8d0e67626Shaopeng Jia   * @param stripNonDigits  true to strip non-digits from the national dialling prefix
2243372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * @return  the dialling prefix for the region denoted by regionCode
2244f59ccfca9dd02c4e3cf3e06b5cf184a8d0e67626Shaopeng Jia   */
2245f59ccfca9dd02c4e3cf3e06b5cf184a8d0e67626Shaopeng Jia  public String getNddPrefixForRegion(String regionCode, boolean stripNonDigits) {
2246203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    PhoneMetadata metadata = getMetadataForRegion(regionCode);
2247203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    if (metadata == null) {
2248bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia      logger.log(Level.WARNING,
2249528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia                 "Invalid or missing region code ("
2250528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia                  + ((regionCode == null) ? "null" : regionCode)
2251528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia                  + ") provided.");
2252f59ccfca9dd02c4e3cf3e06b5cf184a8d0e67626Shaopeng Jia      return null;
2253f59ccfca9dd02c4e3cf3e06b5cf184a8d0e67626Shaopeng Jia    }
2254f59ccfca9dd02c4e3cf3e06b5cf184a8d0e67626Shaopeng Jia    String nationalPrefix = metadata.getNationalPrefix();
2255f59ccfca9dd02c4e3cf3e06b5cf184a8d0e67626Shaopeng Jia    // If no national prefix was found, we return null.
2256f59ccfca9dd02c4e3cf3e06b5cf184a8d0e67626Shaopeng Jia    if (nationalPrefix.length() == 0) {
2257f59ccfca9dd02c4e3cf3e06b5cf184a8d0e67626Shaopeng Jia      return null;
2258f59ccfca9dd02c4e3cf3e06b5cf184a8d0e67626Shaopeng Jia    }
2259f59ccfca9dd02c4e3cf3e06b5cf184a8d0e67626Shaopeng Jia    if (stripNonDigits) {
2260f59ccfca9dd02c4e3cf3e06b5cf184a8d0e67626Shaopeng Jia      // Note: if any other non-numeric symbols are ever used in national prefixes, these would have
2261f59ccfca9dd02c4e3cf3e06b5cf184a8d0e67626Shaopeng Jia      // to be removed here as well.
2262f59ccfca9dd02c4e3cf3e06b5cf184a8d0e67626Shaopeng Jia      nationalPrefix = nationalPrefix.replace("~", "");
2263f59ccfca9dd02c4e3cf3e06b5cf184a8d0e67626Shaopeng Jia    }
2264f59ccfca9dd02c4e3cf3e06b5cf184a8d0e67626Shaopeng Jia    return nationalPrefix;
2265f59ccfca9dd02c4e3cf3e06b5cf184a8d0e67626Shaopeng Jia  }
2266f59ccfca9dd02c4e3cf3e06b5cf184a8d0e67626Shaopeng Jia
2267f59ccfca9dd02c4e3cf3e06b5cf184a8d0e67626Shaopeng Jia  /**
2268372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * Checks if this is a region under the North American Numbering Plan Administration (NANPA).
22691524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *
2270372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * @return  true if regionCode is one of the regions under NANPA
22711524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
22727900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia  public boolean isNANPACountry(String regionCode) {
2273f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia    return nanpaRegions.contains(regionCode);
2274372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  }
2275372bff8dd464574d36737d47e495cad14346653cShaopeng Jia
2276372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  /**
22779651f4d6f2740017c0c4ea9c1c340af6f644d609Shaopeng Jia   * Checks whether the country calling code is from a region whose national significant number
22789651f4d6f2740017c0c4ea9c1c340af6f644d609Shaopeng Jia   * could contain a leading zero. An example of such a region is Italy. Returns false if no
22799651f4d6f2740017c0c4ea9c1c340af6f644d609Shaopeng Jia   * metadata for the country is found.
2280372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   */
2281f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia  boolean isLeadingZeroPossible(int countryCallingCode) {
2282203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    PhoneMetadata mainMetadataForCallingCode =
2283203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia        getMetadataForRegionOrCallingCode(countryCallingCode,
2284203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia                                          getRegionCodeForCountryCode(countryCallingCode));
2285372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    if (mainMetadataForCallingCode == null) {
2286372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      return false;
2287372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    }
2288372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    return mainMetadataForCallingCode.isLeadingZeroPossible();
22891524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
22901524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
22911524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
2292372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * Checks if the number is a valid vanity (alpha) number such as 800 MICROSOFT. A valid vanity
2293372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * number will start with at least 3 digits and will have three or more alpha characters. This
2294372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * does not do region-specific checks - to work out if this number is actually valid for a region,
2295372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * it should be parsed and methods such as {@link #isPossibleNumberWithReason} and
2296372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * {@link #isValidNumber} should be used.
2297372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *
2298372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * @param number  the number that needs to be checked
2299372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * @return  true if the number is a valid vanity number
2300f59ccfca9dd02c4e3cf3e06b5cf184a8d0e67626Shaopeng Jia   */
2301372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  public boolean isAlphaNumber(String number) {
2302372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    if (!isViablePhoneNumber(number)) {
2303372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      // Number is too short, or doesn't match the basic phone number pattern.
2304372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      return false;
2305372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    }
2306372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    StringBuilder strippedNumber = new StringBuilder(number);
2307372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    maybeStripExtension(strippedNumber);
2308372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    return VALID_ALPHA_PHONE_PATTERN.matcher(strippedNumber).matches();
2309f59ccfca9dd02c4e3cf3e06b5cf184a8d0e67626Shaopeng Jia  }
2310f59ccfca9dd02c4e3cf3e06b5cf184a8d0e67626Shaopeng Jia
2311f59ccfca9dd02c4e3cf3e06b5cf184a8d0e67626Shaopeng Jia  /**
2312372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * Convenience wrapper around {@link #isPossibleNumberWithReason}. Instead of returning the reason
2313372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * for failure, this method returns a boolean value.
23141524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @param number  the number that needs to be checked
23151524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @return  true if the number is possible
23161524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
23171524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  public boolean isPossibleNumber(PhoneNumber number) {
23181524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    return isPossibleNumberWithReason(number) == ValidationResult.IS_POSSIBLE;
23191524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
23201524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
23211524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
2322372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * Helper method to check a number against a particular pattern and determine whether it matches,
2323372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * or is too short or too long. Currently, if a number pattern suggests that numbers of length 7
2324372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * and 10 are possible, and a number in between these possible lengths is entered, such as of
2325372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * length 8, this will return TOO_LONG.
2326372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   */
2327372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  private ValidationResult testNumberLengthAgainstPattern(Pattern numberPattern, String number) {
2328372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    Matcher numberMatcher = numberPattern.matcher(number);
2329372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    if (numberMatcher.matches()) {
2330372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      return ValidationResult.IS_POSSIBLE;
2331372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    }
2332372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    if (numberMatcher.lookingAt()) {
2333372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      return ValidationResult.TOO_LONG;
2334372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    } else {
2335372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      return ValidationResult.TOO_SHORT;
2336372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    }
2337372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  }
2338372bff8dd464574d36737d47e495cad14346653cShaopeng Jia
2339372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  /**
2340f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia   * Helper method to check whether a number is too short to be a regular length phone number in a
2341f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia   * region.
2342f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia   */
2343f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia  private boolean isShorterThanPossibleNormalNumber(PhoneMetadata regionMetadata, String number) {
2344f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia    Pattern possibleNumberPattern = regexCache.getPatternForRegex(
2345f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia        regionMetadata.getGeneralDesc().getPossibleNumberPattern());
2346f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia    return testNumberLengthAgainstPattern(possibleNumberPattern, number) ==
2347f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia        ValidationResult.TOO_SHORT;
2348f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia  }
2349f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia
2350f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia  /**
23511524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * Check whether a phone number is a possible number. It provides a more lenient check than
2352372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * {@link #isValidNumber} in the following sense:
2353372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *<ol>
2354372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * <li> It only checks the length of phone numbers. In particular, it doesn't check starting
23551524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *      digits of the number.
2356372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * <li> It doesn't attempt to figure out the type of the number, but uses general rules which
2357372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *      applies to all types of phone numbers in a region. Therefore, it is much faster than
23581524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *      isValidNumber.
2359372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * <li> For fixed line numbers, many regions have the concept of area code, which together with
23601524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *      subscriber number constitute the national significant number. It is sometimes okay to dial
23611524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *      the subscriber number only when dialing in the same area. This function will return
23621524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *      true if the subscriber-number-only version is passed in. On the other hand, because
23631524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *      isValidNumber validates using information on both starting digits (for fixed line
23641524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *      numbers, that would most likely be area codes) and length (obviously includes the
23651524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *      length of area codes for fixed line numbers), it will return false for the
23661524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *      subscriber-number-only version.
2367203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia   * </ol>
23681524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @param number  the number that needs to be checked
23691524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @return  a ValidationResult object which indicates whether the number is possible
23701524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
23711524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  public ValidationResult isPossibleNumberWithReason(PhoneNumber number) {
2372372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    String nationalNumber = getNationalSignificantNumber(number);
23731524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    int countryCode = number.getCountryCode();
23741524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    // Note: For Russian Fed and NANPA numbers, we just use the rules from the default region (US or
23751524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    // Russia) since the getRegionCodeForNumber will not work if the number is possible but not
23761524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    // valid. This would need to be revisited if the possible number pattern ever differed between
2377372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    // various regions within those plans.
2378528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    if (!hasValidCountryCallingCode(countryCode)) {
23791524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      return ValidationResult.INVALID_COUNTRY_CODE;
23801524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
2381528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    String regionCode = getRegionCodeForCountryCode(countryCode);
2382203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    // Metadata cannot be null because the country calling code is valid.
2383528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    PhoneMetadata metadata = getMetadataForRegionOrCallingCode(countryCode, regionCode);
2384528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    PhoneNumberDesc generalNumDesc = metadata.getGeneralDesc();
23854b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia    // Handling case of numbers with no metadata.
23864b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia    if (!generalNumDesc.hasNationalNumberPattern()) {
2387bb78ce92eae2d5de9aa06b27ed3b87bc496c79eeShaopeng Jia      logger.log(Level.FINER, "Checking if number is possible with incomplete metadata.");
23884b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia      int numberLength = nationalNumber.length();
23894b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia      if (numberLength < MIN_LENGTH_FOR_NSN) {
23904b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia        return ValidationResult.TOO_SHORT;
23914b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia      } else if (numberLength > MAX_LENGTH_FOR_NSN) {
23924b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia        return ValidationResult.TOO_LONG;
23934b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia      } else {
23944b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia        return ValidationResult.IS_POSSIBLE;
23954b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia      }
23964b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia    }
2397372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    Pattern possibleNumberPattern =
2398372bff8dd464574d36737d47e495cad14346653cShaopeng Jia        regexCache.getPatternForRegex(generalNumDesc.getPossibleNumberPattern());
2399372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    return testNumberLengthAgainstPattern(possibleNumberPattern, nationalNumber);
24001524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
24011524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
24021524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
24031524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * Check whether a phone number is a possible number given a number in the form of a string, and
2404372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * the region where the number could be dialed from. It provides a more lenient check than
240596a7214cdabf08f53f5b1a560304601c9f65e0b9Shaopeng Jia   * {@link #isValidNumber}. See {@link #isPossibleNumber(PhoneNumber)} for details.
24061524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *
240796a7214cdabf08f53f5b1a560304601c9f65e0b9Shaopeng Jia   * <p>This method first parses the number, then invokes {@link #isPossibleNumber(PhoneNumber)}
240896a7214cdabf08f53f5b1a560304601c9f65e0b9Shaopeng Jia   * with the resultant PhoneNumber object.
24091524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *
24101524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @param number  the number that needs to be checked, in the form of a string
2411d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   * @param regionDialingFrom  the region that we are expecting the number to be dialed from.
2412372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *     Note this is different from the region where the number belongs.  For example, the number
2413372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *     +1 650 253 0000 is a number that belongs to US. When written in this form, it can be
2414372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *     dialed from any region. When it is written as 00 1 650 253 0000, it can be dialed from any
2415372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *     region which uses an international dialling prefix of 00. When it is written as
2416372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *     650 253 0000, it can only be dialed from within the US, and when written as 253 0000, it
2417372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *     can only be dialed from within a smaller area in the US (Mountain View, CA, to be more
241874aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia   *     specific).
24191524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @return  true if the number is possible
24201524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
2421372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  public boolean isPossibleNumber(String number, String regionDialingFrom) {
24221524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    try {
2423372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      return isPossibleNumber(parse(number, regionDialingFrom));
24241524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    } catch (NumberParseException e) {
24251524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      return false;
24261524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
24271524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
24281524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
24291524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
2430df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia   * Attempts to extract a valid number from a phone number that is too long to be valid, and resets
2431df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia   * the PhoneNumber object passed in to that valid version. If no valid number could be extracted,
2432df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia   * the PhoneNumber object passed in will not be modified.
2433df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia   * @param number a PhoneNumber object which contains a number that is too long to be valid.
2434df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia   * @return  true if a valid phone number can be successfully extracted.
2435df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia   */
2436df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia  public boolean truncateTooLongNumber(PhoneNumber number) {
2437df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia    if (isValidNumber(number)) {
2438df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia      return true;
2439df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia    }
2440df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia    PhoneNumber numberCopy = new PhoneNumber();
2441df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia    numberCopy.mergeFrom(number);
2442df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia    long nationalNumber = number.getNationalNumber();
2443df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia    do {
2444df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia      nationalNumber /= 10;
2445df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia      numberCopy.setNationalNumber(nationalNumber);
2446df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia      if (isPossibleNumberWithReason(numberCopy) == ValidationResult.TOO_SHORT ||
2447df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia          nationalNumber == 0) {
2448df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia        return false;
2449df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia      }
2450df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia    } while (!isValidNumber(numberCopy));
2451df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia    number.setNationalNumber(nationalNumber);
2452df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia    return true;
2453df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia  }
2454df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia
2455df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia  /**
245693f6965c2c041ac707bf1b3bcf5a3f60e452f421Shaopeng Jia   * Gets an {@link com.android.i18n.phonenumbers.AsYouTypeFormatter} for the specific region.
24571524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *
2458d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   * @param regionCode  the region where the phone number is being entered
245993f6965c2c041ac707bf1b3bcf5a3f60e452f421Shaopeng Jia   * @return  an {@link com.android.i18n.phonenumbers.AsYouTypeFormatter} object, which can be used
2460372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *     to format phone numbers in the specific region "as you type"
24611524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
24621524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  public AsYouTypeFormatter getAsYouTypeFormatter(String regionCode) {
24631524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    return new AsYouTypeFormatter(regionCode);
24641524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
24651524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
2466372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  // Extracts country calling code from fullNumber, returns it and places the remaining number in
24671524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  // nationalNumber. It assumes that the leading plus sign or IDD has already been removed. Returns
2468372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  // 0 if fullNumber doesn't start with a valid country calling code, and leaves nationalNumber
2469372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  // unmodified.
2470372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  int extractCountryCode(StringBuilder fullNumber, StringBuilder nationalNumber) {
2471ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia    if ((fullNumber.length() == 0) || (fullNumber.charAt(0) == '0')) {
2472ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia      // Country codes do not begin with a '0'.
2473ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia      return 0;
2474ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia    }
24751524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    int potentialCountryCode;
2476df19cbfb8a1e8720bae76bb763ab29622e057c42Shaopeng Jia    int numberLength = fullNumber.length();
247774aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia    for (int i = 1; i <= MAX_LENGTH_COUNTRY_CODE && i <= numberLength; i++) {
24781524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      potentialCountryCode = Integer.parseInt(fullNumber.substring(0, i));
2479372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      if (countryCallingCodeToRegionCodeMap.containsKey(potentialCountryCode)) {
24801524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia        nationalNumber.append(fullNumber.substring(i));
24811524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia        return potentialCountryCode;
24821524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      }
24831524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
24841524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    return 0;
24851524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
24861524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
24871524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
2488372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * Tries to extract a country calling code from a number. This method will return zero if no
2489372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * country calling code is considered to be present. Country calling codes are extracted in the
2490372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * following ways:
2491372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * <ul>
2492372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *  <li> by stripping the international dialing prefix of the region the person is dialing from,
24931524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *       if this is present in the number, and looking at the next digits
2494372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *  <li> by stripping the '+' sign if present and then looking at the next digits
2495372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *  <li> by comparing the start of the number and the country calling code of the default region.
2496372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *       If the number is not considered possible for the numbering plan of the default region
2497372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *       initially, but starts with the country calling code of this region, validation will be
2498372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *       reattempted after stripping this country calling code. If this number is considered a
2499372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *       possible number, then the first digits will be considered the country calling code and
2500372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *       removed as such.
2501372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * </ul>
2502372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * It will throw a NumberParseException if the number starts with a '+' but the country calling
2503372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * code supplied after this does not match that of any known region.
25041524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *
2505372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * @param number  non-normalized telephone number that we wish to extract a country calling
25061524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *     code from - may begin with '+'
25071524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @param defaultRegionMetadata  metadata about the region this number may be from
25081524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @param nationalNumber  a string buffer to store the national significant number in, in the case
2509372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *     that a country calling code was extracted. The number is appended to any existing contents.
2510372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *     If no country calling code was extracted, this will be left unchanged.
251152699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia   * @param keepRawInput  true if the country_code_source and preferred_carrier_code fields of
251252699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia   *     phoneNumber should be populated.
2513372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * @param phoneNumber  the PhoneNumber object where the country_code and country_code_source need
2514372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *     to be populated. Note the country_code is always populated, whereas country_code_source is
2515372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *     only populated when keepCountryCodeSource is true.
2516372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * @return  the country calling code extracted or 0 if none could be extracted
25171524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
2518ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia  // @VisibleForTesting
25191524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  int maybeExtractCountryCode(String number, PhoneMetadata defaultRegionMetadata,
2520372bff8dd464574d36737d47e495cad14346653cShaopeng Jia                              StringBuilder nationalNumber, boolean keepRawInput,
252176f6569af0619d12afd19991d8ff69a9bea4c142Shaopeng Jia                              PhoneNumber phoneNumber)
25221524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      throws NumberParseException {
25235c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia    if (number.length() == 0) {
25245c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia      return 0;
25255c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia    }
2526372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    StringBuilder fullNumber = new StringBuilder(number);
25271524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    // Set the default prefix to be something that will never match.
25281524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    String possibleCountryIddPrefix = "NonMatch";
25291524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    if (defaultRegionMetadata != null) {
25301524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      possibleCountryIddPrefix = defaultRegionMetadata.getInternationalPrefix();
25311524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
25325c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia
25335c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia    CountryCodeSource countryCodeSource =
25345c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia        maybeStripInternationalPrefixAndNormalize(fullNumber, possibleCountryIddPrefix);
253552699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia    if (keepRawInput) {
25365c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia      phoneNumber.setCountryCodeSource(countryCodeSource);
25375c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia    }
25385c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia    if (countryCodeSource != CountryCodeSource.FROM_DEFAULT_COUNTRY) {
2539bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia      if (fullNumber.length() <= MIN_LENGTH_FOR_NSN) {
25401524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia        throw new NumberParseException(NumberParseException.ErrorType.TOO_SHORT_AFTER_IDD,
25411524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia                                       "Phone number had an IDD, but after this was not "
25421524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia                                       + "long enough to be a viable phone number.");
25431524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      }
25441524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      int potentialCountryCode = extractCountryCode(fullNumber, nationalNumber);
25451524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      if (potentialCountryCode != 0) {
25465c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia        phoneNumber.setCountryCode(potentialCountryCode);
25471524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia        return potentialCountryCode;
25481524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      }
25491524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
2550372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      // If this fails, they must be using a strange country calling code that we don't recognize,
2551372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      // or that doesn't exist.
25521524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      throw new NumberParseException(NumberParseException.ErrorType.INVALID_COUNTRY_CODE,
2553372bff8dd464574d36737d47e495cad14346653cShaopeng Jia                                     "Country calling code supplied was not recognised.");
25541524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    } else if (defaultRegionMetadata != null) {
2555372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      // Check to see if the number starts with the country calling code for the default region. If
2556372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      // so, we remove the country calling code, and do some checks on the validity of the number
2557372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      // before and after.
2558372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      int defaultCountryCode = defaultRegionMetadata.getCountryCode();
2559372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      String defaultCountryCodeString = String.valueOf(defaultCountryCode);
2560372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      String normalizedNumber = fullNumber.toString();
2561372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      if (normalizedNumber.startsWith(defaultCountryCodeString)) {
2562372bff8dd464574d36737d47e495cad14346653cShaopeng Jia        StringBuilder potentialNationalNumber =
2563372bff8dd464574d36737d47e495cad14346653cShaopeng Jia            new StringBuilder(normalizedNumber.substring(defaultCountryCodeString.length()));
2564372bff8dd464574d36737d47e495cad14346653cShaopeng Jia        PhoneNumberDesc generalDesc = defaultRegionMetadata.getGeneralDesc();
2565372bff8dd464574d36737d47e495cad14346653cShaopeng Jia        Pattern validNumberPattern =
2566372bff8dd464574d36737d47e495cad14346653cShaopeng Jia            regexCache.getPatternForRegex(generalDesc.getNationalNumberPattern());
2567a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia        maybeStripNationalPrefixAndCarrierCode(
2568a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia            potentialNationalNumber, defaultRegionMetadata, null /* Don't need the carrier code */);
2569372bff8dd464574d36737d47e495cad14346653cShaopeng Jia        Pattern possibleNumberPattern =
2570372bff8dd464574d36737d47e495cad14346653cShaopeng Jia            regexCache.getPatternForRegex(generalDesc.getPossibleNumberPattern());
2571372bff8dd464574d36737d47e495cad14346653cShaopeng Jia        // If the number was not valid before but is valid now, or if it was too long before, we
2572372bff8dd464574d36737d47e495cad14346653cShaopeng Jia        // consider the number with the country calling code stripped to be a better result and
2573372bff8dd464574d36737d47e495cad14346653cShaopeng Jia        // keep that instead.
2574372bff8dd464574d36737d47e495cad14346653cShaopeng Jia        if ((!validNumberPattern.matcher(fullNumber).matches() &&
2575372bff8dd464574d36737d47e495cad14346653cShaopeng Jia             validNumberPattern.matcher(potentialNationalNumber).matches()) ||
2576372bff8dd464574d36737d47e495cad14346653cShaopeng Jia             testNumberLengthAgainstPattern(possibleNumberPattern, fullNumber.toString())
2577372bff8dd464574d36737d47e495cad14346653cShaopeng Jia                  == ValidationResult.TOO_LONG) {
2578372bff8dd464574d36737d47e495cad14346653cShaopeng Jia          nationalNumber.append(potentialNationalNumber);
2579372bff8dd464574d36737d47e495cad14346653cShaopeng Jia          if (keepRawInput) {
2580372bff8dd464574d36737d47e495cad14346653cShaopeng Jia            phoneNumber.setCountryCodeSource(CountryCodeSource.FROM_NUMBER_WITHOUT_PLUS_SIGN);
25811524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia          }
2582372bff8dd464574d36737d47e495cad14346653cShaopeng Jia          phoneNumber.setCountryCode(defaultCountryCode);
2583372bff8dd464574d36737d47e495cad14346653cShaopeng Jia          return defaultCountryCode;
25841524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia        }
25851524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      }
25861524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
2587372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    // No country calling code present.
25885c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia    phoneNumber.setCountryCode(0);
25891524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    return 0;
25901524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
25911524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
25921524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
25931524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * Strips the IDD from the start of the number if present. Helper function used by
25941524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * maybeStripInternationalPrefixAndNormalize.
25951524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
2596372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  private boolean parsePrefixAsIdd(Pattern iddPattern, StringBuilder number) {
25971524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    Matcher m = iddPattern.matcher(number);
25981524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    if (m.lookingAt()) {
25991524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      int matchEnd = m.end();
2600372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      // Only strip this if the first digit after the match is not a 0, since country calling codes
2601372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      // cannot begin with 0.
26021524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      Matcher digitMatcher = CAPTURING_DIGIT_PATTERN.matcher(number.substring(matchEnd));
26031524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      if (digitMatcher.find()) {
2604d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia        String normalizedGroup = normalizeDigitsOnly(digitMatcher.group(1));
26051524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia        if (normalizedGroup.equals("0")) {
26061524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia          return false;
26071524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia        }
26081524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      }
26091524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      number.delete(0, matchEnd);
26101524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      return true;
26111524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
26121524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    return false;
26131524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
26141524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
26151524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
26161524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * Strips any international prefix (such as +, 00, 011) present in the number provided, normalizes
2617f59ccfca9dd02c4e3cf3e06b5cf184a8d0e67626Shaopeng Jia   * the resulting number, and indicates if an international prefix was present.
26181524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *
26191524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @param number  the non-normalized telephone number that we wish to strip any international
262074aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia   *     dialing prefix from.
2621372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * @param possibleIddPrefix  the international direct dialing prefix from the region we
26221524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *     think this number may be dialed in
26235c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia   * @return  the corresponding CountryCodeSource if an international dialing prefix could be
2624372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *     removed from the number, otherwise CountryCodeSource.FROM_DEFAULT_COUNTRY if the number did
2625372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *     not seem to be in international format.
26261524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
2627ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia  // @VisibleForTesting
26285c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia  CountryCodeSource maybeStripInternationalPrefixAndNormalize(
2629372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      StringBuilder number,
26305c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia      String possibleIddPrefix) {
26311524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    if (number.length() == 0) {
26325c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia      return CountryCodeSource.FROM_DEFAULT_COUNTRY;
26331524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
2634256a5f71a05ffd182a0fda2cfed6f93345cc889fLara Rennie    // Check to see if the number begins with one or more plus signs.
2635256a5f71a05ffd182a0fda2cfed6f93345cc889fLara Rennie    Matcher m = PLUS_CHARS_PATTERN.matcher(number);
2636256a5f71a05ffd182a0fda2cfed6f93345cc889fLara Rennie    if (m.lookingAt()) {
2637256a5f71a05ffd182a0fda2cfed6f93345cc889fLara Rennie      number.delete(0, m.end());
26381524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      // Can now normalize the rest of the number since we've consumed the "+" sign at the start.
26391524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      normalize(number);
26405c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia      return CountryCodeSource.FROM_NUMBER_WITH_PLUS_SIGN;
26411524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
26421524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    // Attempt to parse the first digits as an international prefix.
2643be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    Pattern iddPattern = regexCache.getPatternForRegex(possibleIddPrefix);
26441524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    normalize(number);
26455c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia    return parsePrefixAsIdd(iddPattern, number)
2646f59ccfca9dd02c4e3cf3e06b5cf184a8d0e67626Shaopeng Jia           ? CountryCodeSource.FROM_NUMBER_WITH_IDD
2647f59ccfca9dd02c4e3cf3e06b5cf184a8d0e67626Shaopeng Jia           : CountryCodeSource.FROM_DEFAULT_COUNTRY;
26481524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
26491524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
26501524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
26511524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * Strips any national prefix (such as 0, 1) present in the number provided.
26521524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *
26531524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @param number  the normalized telephone number that we wish to strip any national
26541524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *     dialing prefix from
2655372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * @param metadata  the metadata for the region that we think this number is from
2656a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia   * @param carrierCode  a place to insert the carrier code if one is extracted
2657a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia   * @return true if a national prefix or carrier code (or both) could be extracted.
26581524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
2659ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia  // @VisibleForTesting
2660a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia  boolean maybeStripNationalPrefixAndCarrierCode(
2661a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia      StringBuilder number, PhoneMetadata metadata, StringBuilder carrierCode) {
26621524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    int numberLength = number.length();
266352699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia    String possibleNationalPrefix = metadata.getNationalPrefixForParsing();
2664be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    if (numberLength == 0 || possibleNationalPrefix.length() == 0) {
26651524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      // Early return for numbers of zero length.
2666a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia      return false;
26671524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
26681524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    // Attempt to parse the first digits as a national prefix.
266952699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia    Matcher prefixMatcher = regexCache.getPatternForRegex(possibleNationalPrefix).matcher(number);
267052699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia    if (prefixMatcher.lookingAt()) {
267152699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia      Pattern nationalNumberRule =
267252699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia          regexCache.getPatternForRegex(metadata.getGeneralDesc().getNationalNumberPattern());
2673f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia      // Check if the original number is viable.
2674f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia      boolean isViableOriginalNumber = nationalNumberRule.matcher(number).matches();
267552699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia      // prefixMatcher.group(numOfGroups) == null implies nothing was captured by the capturing
267652699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia      // groups in possibleNationalPrefix; therefore, no transformation is necessary, and we just
267752699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia      // remove the national prefix.
267852699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia      int numOfGroups = prefixMatcher.groupCount();
267952699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia      String transformRule = metadata.getNationalPrefixTransformRule();
268052699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia      if (transformRule == null || transformRule.length() == 0 ||
268152699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia          prefixMatcher.group(numOfGroups) == null) {
2682f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia        // If the original number was viable, and the resultant number is not, we return.
2683f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia        if (isViableOriginalNumber &&
2684f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia            !nationalNumberRule.matcher(number.substring(prefixMatcher.end())).matches()) {
2685a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia          return false;
268652699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia        }
2687a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia        if (carrierCode != null && numOfGroups > 0 && prefixMatcher.group(numOfGroups) != null) {
2688a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia          carrierCode.append(prefixMatcher.group(1));
26891524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia        }
269052699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia        number.delete(0, prefixMatcher.end());
2691a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia        return true;
26921524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      } else {
2693f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia        // Check that the resultant number is still viable. If not, return. Check this by copying
2694f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia        // the string buffer and making the transformation on the copy first.
2695372bff8dd464574d36737d47e495cad14346653cShaopeng Jia        StringBuilder transformedNumber = new StringBuilder(number);
269652699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia        transformedNumber.replace(0, numberLength, prefixMatcher.replaceFirst(transformRule));
2697f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia        if (isViableOriginalNumber &&
2698f7e0224b862054893f28d2736b3f6804d9935886Shaopeng Jia            !nationalNumberRule.matcher(transformedNumber.toString()).matches()) {
2699a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia          return false;
270052699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia        }
2701a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia        if (carrierCode != null && numOfGroups > 1) {
2702a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia          carrierCode.append(prefixMatcher.group(1));
27031524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia        }
27041524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia        number.replace(0, number.length(), transformedNumber.toString());
2705a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia        return true;
27061524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      }
27071524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
2708a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia    return false;
27091524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
27101524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
27111524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
27121524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * Strips any extension (as in, the part of the number dialled after the call is connected,
27131524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * usually indicated with extn, ext, x or similar) from the end of the number, and returns it.
27141524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *
27151524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @param number  the non-normalized telephone number that we wish to strip the extension from
27161524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @return        the phone extension
27171524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
2718ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia  // @VisibleForTesting
2719372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  String maybeStripExtension(StringBuilder number) {
27201524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    Matcher m = EXTN_PATTERN.matcher(number);
27211524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    // If we find a potential extension, and the number preceding this is a viable number, we assume
27221524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    // it is an extension.
27231524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    if (m.find() && isViablePhoneNumber(number.substring(0, m.start()))) {
27241524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      // The numbers are captured into groups in the regular expression.
27254b7846722d1a5acb0577b07e98324f744f5e7942Shaopeng Jia      for (int i = 1, length = m.groupCount(); i <= length; i++) {
27261524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia        if (m.group(i) != null) {
27271524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia          // We go through the capturing groups until we find one that captured some digits. If none
27281524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia          // did, then we will return the empty string.
27291524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia          String extension = m.group(i);
27301524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia          number.delete(m.start(), number.length());
27311524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia          return extension;
27321524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia        }
27331524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      }
27341524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
27351524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    return "";
27361524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
27371524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
27381524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
273974aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia   * Checks to see that the region code used is valid, or if it is not valid, that the number to
2740372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * parse starts with a + symbol so that we can attempt to infer the region from the number.
274174aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia   * Returns false if it cannot use the region provided and the region cannot be inferred.
274274aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia   */
2743372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  private boolean checkRegionForParsing(String numberToParse, String defaultRegion) {
2744372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    if (!isValidRegionCode(defaultRegion)) {
2745372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      // If the number is null or empty, we can't infer the region.
27468777f1913d34c3ecf72164ea85292e978e265eddShaopeng Jia      if ((numberToParse == null) || (numberToParse.length() == 0) ||
274774aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia          !PLUS_CHARS_PATTERN.matcher(numberToParse).lookingAt()) {
274874aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia        return false;
274974aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia      }
275074aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia    }
275174aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia    return true;
275274aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia  }
275374aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia
275474aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia  /**
27551524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * Parses a string and returns it in proto buffer format. This method will throw a
275693f6965c2c041ac707bf1b3bcf5a3f60e452f421Shaopeng Jia   * {@link com.android.i18n.phonenumbers.NumberParseException} if the number is not considered to be
2757372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * a possible number. Note that validation of whether the number is actually a valid number for a
2758372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * particular region is not performed. This can be done separately with {@link #isValidNumber}.
27591524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *
27601524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @param numberToParse     number that we are attempting to parse. This can contain formatting
2761bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia   *                          such as +, ( and -, as well as a phone number extension. It can also
2762bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia   *                          be provided in RFC3966 format.
2763d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   * @param defaultRegion     region that we are expecting the number to be from. This is only used
2764d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   *                          if the number being parsed is not written in international format.
2765372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *                          The country_code for the number in this case would be stored as that
2766372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *                          of the default region supplied. If the number is guaranteed to
2767d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   *                          start with a '+' followed by the country calling code, then
2768d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   *                          "ZZ" or null can be supplied.
27691524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @return                  a phone number proto buffer filled with the parsed number
27701524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @throws NumberParseException  if the string is not considered to be a viable phone number or if
2771372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *                               no default region was supplied and the number is not in
2772f59ccfca9dd02c4e3cf3e06b5cf184a8d0e67626Shaopeng Jia   *                               international format (does not start with +)
27731524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
2774372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  public PhoneNumber parse(String numberToParse, String defaultRegion)
27751524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      throws NumberParseException {
277676f6569af0619d12afd19991d8ff69a9bea4c142Shaopeng Jia    PhoneNumber phoneNumber = new PhoneNumber();
2777372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    parse(numberToParse, defaultRegion, phoneNumber);
277876f6569af0619d12afd19991d8ff69a9bea4c142Shaopeng Jia    return phoneNumber;
2779be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia  }
2780be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia
2781d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia  /**
2782d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   * Same as {@link #parse(String, String)}, but accepts mutable PhoneNumber as a parameter to
2783d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   * decrease object creation when invoked many times.
2784d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   */
2785372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  public void parse(String numberToParse, String defaultRegion, PhoneNumber phoneNumber)
2786be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia      throws NumberParseException {
2787372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    parseHelper(numberToParse, defaultRegion, false, true, phoneNumber);
27887900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia  }
27897900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia
27907900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia  /**
2791372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * Parses a string and returns it in proto buffer format. This method differs from {@link #parse}
2792372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * in that it always populates the raw_input field of the protocol buffer with numberToParse as
2793372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * well as the country_code_source field.
27947900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia   *
27957900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia   * @param numberToParse     number that we are attempting to parse. This can contain formatting
27967900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia   *                          such as +, ( and -, as well as a phone number extension.
2797d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   * @param defaultRegion     region that we are expecting the number to be from. This is only used
2798d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   *                          if the number being parsed is not written in international format.
2799d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   *                          The country calling code for the number in this case would be stored
2800d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   *                          as that of the default region supplied.
28017900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia   * @return                  a phone number proto buffer filled with the parsed number
28027900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia   * @throws NumberParseException  if the string is not considered to be a viable phone number or if
2803372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *                               no default region was supplied
28047900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia   */
2805372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  public PhoneNumber parseAndKeepRawInput(String numberToParse, String defaultRegion)
28067900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia      throws NumberParseException {
280776f6569af0619d12afd19991d8ff69a9bea4c142Shaopeng Jia    PhoneNumber phoneNumber = new PhoneNumber();
2808372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    parseAndKeepRawInput(numberToParse, defaultRegion, phoneNumber);
280976f6569af0619d12afd19991d8ff69a9bea4c142Shaopeng Jia    return phoneNumber;
2810be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia  }
2811be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia
2812d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia  /**
2813d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   * Same as{@link #parseAndKeepRawInput(String, String)}, but accepts a mutable PhoneNumber as
2814d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   * a parameter to decrease object creation when invoked many times.
2815d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   */
2816372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  public void parseAndKeepRawInput(String numberToParse, String defaultRegion,
281776f6569af0619d12afd19991d8ff69a9bea4c142Shaopeng Jia                                   PhoneNumber phoneNumber)
2818be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia      throws NumberParseException {
2819372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    parseHelper(numberToParse, defaultRegion, true, true, phoneNumber);
28201524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
28211524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
28221524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
282352699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia   * Returns an iterable over all {@link PhoneNumberMatch PhoneNumberMatches} in {@code text}. This
282452699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia   * is a shortcut for {@link #findNumbers(CharSequence, String, Leniency, long)
2825372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * getMatcher(text, defaultRegion, Leniency.VALID, Long.MAX_VALUE)}.
282652699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia   *
282752699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia   * @param text              the text to search for phone numbers, null for no text
2828d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   * @param defaultRegion     region that we are expecting the number to be from. This is only used
2829d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   *                          if the number being parsed is not written in international format. The
2830d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   *                          country_code for the number in this case would be stored as that of
2831d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   *                          the default region supplied. May be null if only international
283252699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia   *                          numbers are expected.
283352699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia   */
2834372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  public Iterable<PhoneNumberMatch> findNumbers(CharSequence text, String defaultRegion) {
2835372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    return findNumbers(text, defaultRegion, Leniency.VALID, Long.MAX_VALUE);
283652699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia  }
283752699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia
283852699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia  /**
283952699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia   * Returns an iterable over all {@link PhoneNumberMatch PhoneNumberMatches} in {@code text}.
284052699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia   *
284152699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia   * @param text              the text to search for phone numbers, null for no text
2842d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   * @param defaultRegion     region that we are expecting the number to be from. This is only used
2843d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   *                          if the number being parsed is not written in international format. The
2844d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   *                          country_code for the number in this case would be stored as that of
2845d1db4c508088ac27cb0815a222cf2600f16ad5b9Shaopeng Jia   *                          the default region supplied. May be null if only international
284652699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia   *                          numbers are expected.
284752699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia   * @param leniency          the leniency to use when evaluating candidate phone numbers
284852699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia   * @param maxTries          the maximum number of invalid numbers to try before giving up on the
284952699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia   *                          text. This is to cover degenerate cases where the text has a lot of
285052699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia   *                          false positives in it. Must be {@code >= 0}.
285152699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia   */
285252699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia  public Iterable<PhoneNumberMatch> findNumbers(
2853372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      final CharSequence text, final String defaultRegion, final Leniency leniency,
285452699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia      final long maxTries) {
285552699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia
285652699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia    return new Iterable<PhoneNumberMatch>() {
285752699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia      public Iterator<PhoneNumberMatch> iterator() {
285852699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia        return new PhoneNumberMatcher(
2859372bff8dd464574d36737d47e495cad14346653cShaopeng Jia            PhoneNumberUtil.this, text, defaultRegion, leniency, maxTries);
286052699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia      }
286152699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia    };
286252699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia  }
286352699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia
286452699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia  /**
2865f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia   * A helper function to set the values related to leading zeros in a PhoneNumber.
2866f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia   */
2867f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia  static void setItalianLeadingZerosForPhoneNumber(String nationalNumber, PhoneNumber phoneNumber) {
2868f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia    if (nationalNumber.length() > 1 && nationalNumber.charAt(0) == '0') {
2869f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia      phoneNumber.setItalianLeadingZero(true);
2870f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia      int numberOfLeadingZeros = 1;
2871f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia      // Note that if the national number is all "0"s, the last "0" is not counted as a leading
2872f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia      // zero.
2873f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia      while (numberOfLeadingZeros < nationalNumber.length() - 1 &&
2874f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia             nationalNumber.charAt(numberOfLeadingZeros) == '0') {
2875f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia        numberOfLeadingZeros++;
2876f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia      }
2877f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia      if (numberOfLeadingZeros != 1) {
2878f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia        phoneNumber.setNumberOfLeadingZeros(numberOfLeadingZeros);
2879f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia      }
2880f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia    }
2881f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia  }
2882f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia
2883f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia  /**
2884be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia   * Parses a string and fills up the phoneNumber. This method is the same as the public
2885372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * parse() method, with the exception that it allows the default region to be null, for use by
2886372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * isNumberMatch(). checkRegion should be set to false if it is permitted for the default region
288774aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia   * to be null or unknown ("ZZ").
28881524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
2889372bff8dd464574d36737d47e495cad14346653cShaopeng Jia  private void parseHelper(String numberToParse, String defaultRegion, boolean keepRawInput,
289074aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia                           boolean checkRegion, PhoneNumber phoneNumber)
28911524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      throws NumberParseException {
289274aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia    if (numberToParse == null) {
289374aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia      throw new NumberParseException(NumberParseException.ErrorType.NOT_A_NUMBER,
289474aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia                                     "The phone number supplied was null.");
2895b0e21c22b1ca6b9aeb1426924cdf42a221c3d416Shaopeng Jia    } else if (numberToParse.length() > MAX_INPUT_STRING_LENGTH) {
2896b0e21c22b1ca6b9aeb1426924cdf42a221c3d416Shaopeng Jia      throw new NumberParseException(NumberParseException.ErrorType.TOO_LONG,
2897b0e21c22b1ca6b9aeb1426924cdf42a221c3d416Shaopeng Jia                                     "The string supplied was too long to parse.");
289874aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia    }
2899b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia
2900b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia    StringBuilder nationalNumber = new StringBuilder();
2901bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia    buildNationalNumberForParsing(numberToParse, nationalNumber);
2902b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia
2903b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia    if (!isViablePhoneNumber(nationalNumber.toString())) {
29041524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      throw new NumberParseException(NumberParseException.ErrorType.NOT_A_NUMBER,
29051524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia                                     "The string supplied did not seem to be a phone number.");
29061524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
29071524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
2908372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    // Check the region supplied is valid, or that the extracted number starts with some sort of +
290974aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia    // sign so the number's region can be determined.
2910b210e301245cb5dc90aa3142f378632bd41cb172Shaopeng Jia    if (checkRegion && !checkRegionForParsing(nationalNumber.toString(), defaultRegion)) {
291174aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia      throw new NumberParseException(NumberParseException.ErrorType.INVALID_COUNTRY_CODE,
2912372bff8dd464574d36737d47e495cad14346653cShaopeng Jia                                     "Missing or invalid default region.");
291374aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia    }
291474aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia
29157900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia    if (keepRawInput) {
29167900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia      phoneNumber.setRawInput(numberToParse);
29177900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia    }
2918372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    // Attempt to parse extension first, since it doesn't require region-specific data and we want
29191524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    // to have the non-normalised number here.
29201524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    String extension = maybeStripExtension(nationalNumber);
2921be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    if (extension.length() > 0) {
29221524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      phoneNumber.setExtension(extension);
29231524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
29241524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
2925372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    PhoneMetadata regionMetadata = getMetadataForRegion(defaultRegion);
29261524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    // Check to see if the number is given in international format so we know whether this number is
2927372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    // from the default region or not.
2928372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    StringBuilder normalizedNationalNumber = new StringBuilder();
2929ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia    int countryCode = 0;
2930ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia    try {
2931ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia      // TODO: This method should really just take in the string buffer that has already
2932ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia      // been created, and just remove the prefix, rather than taking in a string and then
2933ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia      // outputting a string buffer.
2934ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia      countryCode = maybeExtractCountryCode(nationalNumber.toString(), regionMetadata,
2935ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia                                            normalizedNationalNumber, keepRawInput, phoneNumber);
2936ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia    } catch (NumberParseException e) {
2937ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia      Matcher matcher = PLUS_CHARS_PATTERN.matcher(nationalNumber.toString());
2938ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia      if (e.getErrorType() == NumberParseException.ErrorType.INVALID_COUNTRY_CODE &&
2939ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia          matcher.lookingAt()) {
2940ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia        // Strip the plus-char, and try again.
2941ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia        countryCode = maybeExtractCountryCode(nationalNumber.substring(matcher.end()),
2942ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia                                              regionMetadata, normalizedNationalNumber,
2943ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia                                              keepRawInput, phoneNumber);
2944ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia        if (countryCode == 0) {
2945ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia          throw new NumberParseException(NumberParseException.ErrorType.INVALID_COUNTRY_CODE,
2946ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia                                         "Could not interpret numbers after plus-sign.");
2947ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia        }
2948ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia      } else {
2949ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia        throw new NumberParseException(e.getErrorType(), e.getMessage());
2950ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia      }
2951ca1e43d6e1fac07c7fc29c66c7da1fa9d7cf50f2Shaopeng Jia    }
29521524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    if (countryCode != 0) {
29531524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      String phoneNumberRegion = getRegionCodeForCountryCode(countryCode);
2954372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      if (!phoneNumberRegion.equals(defaultRegion)) {
2955203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia        // Metadata cannot be null because the country calling code is valid.
2956528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia        regionMetadata = getMetadataForRegionOrCallingCode(countryCode, phoneNumberRegion);
29575c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia      }
29581524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    } else {
2959372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      // If no extracted country calling code, use the region supplied instead. The national number
2960372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      // is just the normalized version of the number we were given to parse.
29611524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      normalize(nationalNumber);
29621524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      normalizedNationalNumber.append(nationalNumber);
2963372bff8dd464574d36737d47e495cad14346653cShaopeng Jia      if (defaultRegion != null) {
2964372bff8dd464574d36737d47e495cad14346653cShaopeng Jia        countryCode = regionMetadata.getCountryCode();
29655c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia        phoneNumber.setCountryCode(countryCode);
29665c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia      } else if (keepRawInput) {
29675c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia        phoneNumber.clearCountryCodeSource();
29681524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      }
29691524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
29701524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    if (normalizedNationalNumber.length() < MIN_LENGTH_FOR_NSN) {
29711524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      throw new NumberParseException(NumberParseException.ErrorType.TOO_SHORT_NSN,
29721524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia                                     "The string supplied is too short to be a phone number.");
29731524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
2974372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    if (regionMetadata != null) {
2975a48b2d221ba46df7446d1a87244efa985e8e292fShaopeng Jia      StringBuilder carrierCode = new StringBuilder();
2976f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia      StringBuilder potentialNationalNumber = new StringBuilder(normalizedNationalNumber);
2977f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia      maybeStripNationalPrefixAndCarrierCode(potentialNationalNumber, regionMetadata, carrierCode);
2978f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia      // We require that the NSN remaining after stripping the national prefix and carrier code be
2979f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia      // of a possible length for the region. Otherwise, we don't do the stripping, since the
2980f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia      // original number could be a valid short number.
2981f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia      if (!isShorterThanPossibleNormalNumber(regionMetadata, potentialNationalNumber.toString())) {
2982f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia        normalizedNationalNumber = potentialNationalNumber;
2983f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia        if (keepRawInput) {
2984f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia          phoneNumber.setPreferredDomesticCarrierCode(carrierCode.toString());
2985f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia        }
298652699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia      }
29871524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
29881524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    int lengthOfNationalNumber = normalizedNationalNumber.length();
29891524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    if (lengthOfNationalNumber < MIN_LENGTH_FOR_NSN) {
29901524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      throw new NumberParseException(NumberParseException.ErrorType.TOO_SHORT_NSN,
2991be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia                                     "The string supplied is too short to be a phone number.");
29921524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
29931524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    if (lengthOfNationalNumber > MAX_LENGTH_FOR_NSN) {
29941524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      throw new NumberParseException(NumberParseException.ErrorType.TOO_LONG,
2995be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia                                     "The string supplied is too long to be a phone number.");
29961524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
2997f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia    setItalianLeadingZerosForPhoneNumber(normalizedNationalNumber.toString(), phoneNumber);
29981524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    phoneNumber.setNationalNumber(Long.parseLong(normalizedNationalNumber.toString()));
29991524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
30001524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
30011524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
3002bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia   * Converts numberToParse to a form that we can parse and write it to nationalNumber if it is
3003bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia   * written in RFC3966; otherwise extract a possible number out of it and write to nationalNumber.
3004bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia   */
3005bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia  private void buildNationalNumberForParsing(String numberToParse, StringBuilder nationalNumber) {
3006bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia    int indexOfPhoneContext = numberToParse.indexOf(RFC3966_PHONE_CONTEXT);
3007bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia    if (indexOfPhoneContext > 0) {
3008bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia      int phoneContextStart = indexOfPhoneContext + RFC3966_PHONE_CONTEXT.length();
3009bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia      // If the phone context contains a phone number prefix, we need to capture it, whereas domains
3010bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia      // will be ignored.
3011bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia      if (numberToParse.charAt(phoneContextStart) == PLUS_SIGN) {
3012bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia        // Additional parameters might follow the phone context. If so, we will remove them here
3013bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia        // because the parameters after phone context are not important for parsing the
3014bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia        // phone number.
3015bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia        int phoneContextEnd = numberToParse.indexOf(';', phoneContextStart);
3016bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia        if (phoneContextEnd > 0) {
3017bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia          nationalNumber.append(numberToParse.substring(phoneContextStart, phoneContextEnd));
3018bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia        } else {
3019bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia          nationalNumber.append(numberToParse.substring(phoneContextStart));
3020bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia        }
3021bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia      }
3022bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia
3023bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia      // Now append everything between the "tel:" prefix and the phone-context. This should include
30248777f1913d34c3ecf72164ea85292e978e265eddShaopeng Jia      // the national number, an optional extension or isdn-subaddress component. Note we also
30258777f1913d34c3ecf72164ea85292e978e265eddShaopeng Jia      // handle the case when "tel:" is missing, as we have seen in some of the phone number inputs.
30268777f1913d34c3ecf72164ea85292e978e265eddShaopeng Jia      // In that case, we append everything from the beginning.
30278777f1913d34c3ecf72164ea85292e978e265eddShaopeng Jia      int indexOfRfc3966Prefix = numberToParse.indexOf(RFC3966_PREFIX);
30288777f1913d34c3ecf72164ea85292e978e265eddShaopeng Jia      int indexOfNationalNumber = (indexOfRfc3966Prefix >= 0) ?
30298777f1913d34c3ecf72164ea85292e978e265eddShaopeng Jia          indexOfRfc3966Prefix + RFC3966_PREFIX.length() : 0;
30308777f1913d34c3ecf72164ea85292e978e265eddShaopeng Jia      nationalNumber.append(numberToParse.substring(indexOfNationalNumber, indexOfPhoneContext));
3031bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia    } else {
3032bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia      // Extract a possible number from the string passed in (this strips leading characters that
3033bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia      // could not be the start of a phone number.)
3034bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia      nationalNumber.append(extractPossibleNumber(numberToParse));
3035bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia    }
3036bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia
3037bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia    // Delete the isdn-subaddress and everything after it if it is present. Note extension won't
3038bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia    // appear at the same time with isdn-subaddress according to paragraph 5.3 of the RFC3966 spec,
3039bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia    int indexOfIsdn = nationalNumber.indexOf(RFC3966_ISDN_SUBADDRESS);
3040bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia    if (indexOfIsdn > 0) {
3041bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia      nationalNumber.delete(indexOfIsdn, nationalNumber.length());
3042bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia    }
3043bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia    // If both phone context and isdn-subaddress are absent but other parameters are present, the
3044bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia    // parameters are left in nationalNumber. This is because we are concerned about deleting
3045bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia    // content from a potential number string when there is no strong evidence that the number is
3046bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia    // actually written in RFC3966.
3047bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia  }
3048bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia
3049bf5d9756fe9b13f5b2e0696c62949cea77396687Shaopeng Jia  /**
30501524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * Takes two phone numbers and compares them for equality.
30511524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *
3052372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * <p>Returns EXACT_MATCH if the country_code, NSN, presence of a leading zero for Italian numbers
30531524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * and any extension present are the same.
3054372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * Returns NSN_MATCH if either or both has no region specified, and the NSNs and extensions are
30551524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * the same.
3056372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * Returns SHORT_NSN_MATCH if either or both has no region specified, or the region specified is
3057372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * the same, and one NSN could be a shorter version of the other number. This includes the case
30581524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * where one has an extension specified, and the other does not.
30591524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * Returns NO_MATCH otherwise.
30601524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * For example, the numbers +1 345 657 1234 and 657 1234 are a SHORT_NSN_MATCH.
30611524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * The numbers +1 345 657 1234 and 345 657 are a NO_MATCH.
30621524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *
30631524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @param firstNumberIn  first number to compare
30641524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @param secondNumberIn  second number to compare
30651524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *
30661524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @return  NO_MATCH, SHORT_NSN_MATCH, NSN_MATCH or EXACT_MATCH depending on the level of equality
30671524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *     of the two numbers, described in the method definition.
30681524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
30691524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  public MatchType isNumberMatch(PhoneNumber firstNumberIn, PhoneNumber secondNumberIn) {
30701524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    // Make copies of the phone number so that the numbers passed in are not edited.
307176f6569af0619d12afd19991d8ff69a9bea4c142Shaopeng Jia    PhoneNumber firstNumber = new PhoneNumber();
30721524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    firstNumber.mergeFrom(firstNumberIn);
307376f6569af0619d12afd19991d8ff69a9bea4c142Shaopeng Jia    PhoneNumber secondNumber = new PhoneNumber();
30741524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    secondNumber.mergeFrom(secondNumberIn);
307552699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia    // First clear raw_input, country_code_source and preferred_domestic_carrier_code fields and any
307652699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia    // empty-string extensions so that we can use the proto-buffer equality method.
30777900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia    firstNumber.clearRawInput();
30785c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia    firstNumber.clearCountryCodeSource();
307952699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia    firstNumber.clearPreferredDomesticCarrierCode();
30807900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia    secondNumber.clearRawInput();
30815c24149d269da6e7d7b6b2797df096fdea64a019Shaopeng Jia    secondNumber.clearCountryCodeSource();
308252699e08e855fb0957944b4e73358ad9e0007c0cShaopeng Jia    secondNumber.clearPreferredDomesticCarrierCode();
30831524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    if (firstNumber.hasExtension() &&
3084be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia        firstNumber.getExtension().length() == 0) {
30851524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia        firstNumber.clearExtension();
30861524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
30871524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    if (secondNumber.hasExtension() &&
3088be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia        secondNumber.getExtension().length() == 0) {
30891524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia        secondNumber.clearExtension();
30901524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
30911524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    // Early exit if both had extensions and these are different.
309276f6569af0619d12afd19991d8ff69a9bea4c142Shaopeng Jia    if (firstNumber.hasExtension() && secondNumber.hasExtension() &&
309376f6569af0619d12afd19991d8ff69a9bea4c142Shaopeng Jia        !firstNumber.getExtension().equals(secondNumber.getExtension())) {
30941524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      return MatchType.NO_MATCH;
30951524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
309676f6569af0619d12afd19991d8ff69a9bea4c142Shaopeng Jia    int firstNumberCountryCode = firstNumber.getCountryCode();
309776f6569af0619d12afd19991d8ff69a9bea4c142Shaopeng Jia    int secondNumberCountryCode = secondNumber.getCountryCode();
3098372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    // Both had country_code specified.
30991524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    if (firstNumberCountryCode != 0 && secondNumberCountryCode != 0) {
310076f6569af0619d12afd19991d8ff69a9bea4c142Shaopeng Jia      if (firstNumber.exactlySameAs(secondNumber)) {
31011524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia        return MatchType.EXACT_MATCH;
31027900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia      } else if (firstNumberCountryCode == secondNumberCountryCode &&
310376f6569af0619d12afd19991d8ff69a9bea4c142Shaopeng Jia                 isNationalNumberSuffixOfTheOther(firstNumber, secondNumber)) {
31041524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia        // A SHORT_NSN_MATCH occurs if there is a difference because of the presence or absence of
31051524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia        // an 'Italian leading zero', the presence or absence of an extension, or one NSN being a
31061524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia        // shorter variant of the other.
31077900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia        return MatchType.SHORT_NSN_MATCH;
31081524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      }
31091524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      // This is not a match.
31101524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      return MatchType.NO_MATCH;
31111524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
3112372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    // Checks cases where one or both country_code fields were not specified. To make equality
3113372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    // checks easier, we first set the country_code fields to be equal.
311476f6569af0619d12afd19991d8ff69a9bea4c142Shaopeng Jia    firstNumber.setCountryCode(secondNumberCountryCode);
31151524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    // If all else was the same, then this is an NSN_MATCH.
311676f6569af0619d12afd19991d8ff69a9bea4c142Shaopeng Jia    if (firstNumber.exactlySameAs(secondNumber)) {
31171524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      return MatchType.NSN_MATCH;
31181524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
311976f6569af0619d12afd19991d8ff69a9bea4c142Shaopeng Jia    if (isNationalNumberSuffixOfTheOther(firstNumber, secondNumber)) {
31201524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia      return MatchType.SHORT_NSN_MATCH;
31211524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia    }
3122be1af2f8b62d5435eca48f3dd5c82e3d2c9bfa17Shaopeng Jia    return MatchType.NO_MATCH;
31231524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
31241524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
31257900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia  // Returns true when one national number is the suffix of the other or both are the same.
31267900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia  private boolean isNationalNumberSuffixOfTheOther(PhoneNumber firstNumber,
31277900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia                                                   PhoneNumber secondNumber) {
31287900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia    String firstNumberNationalNumber = String.valueOf(firstNumber.getNationalNumber());
31297900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia    String secondNumberNationalNumber = String.valueOf(secondNumber.getNationalNumber());
31307900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia    // Note that endsWith returns true if the numbers are equal.
31317900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia    return firstNumberNationalNumber.endsWith(secondNumberNationalNumber) ||
31327900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia           secondNumberNationalNumber.endsWith(firstNumberNationalNumber);
31337900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia  }
31347900ea273b8c33b3c6f70d7dd559127938d0fc3dShaopeng Jia
31351524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
31361524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * Takes two phone numbers as strings and compares them for equality. This is a convenience
313796a7214cdabf08f53f5b1a560304601c9f65e0b9Shaopeng Jia   * wrapper for {@link #isNumberMatch(PhoneNumber, PhoneNumber)}. No default region is known.
31381524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *
3139372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   * @param firstNumber  first number to compare. Can contain formatting, and can have country
3140372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *     calling code specified with + at the start.
31411524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @param secondNumber  second number to compare. Can contain formatting, and can have country
3142372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *     calling code specified with + at the start.
314374aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia   * @return  NOT_A_NUMBER, NO_MATCH, SHORT_NSN_MATCH, NSN_MATCH, EXACT_MATCH. See
314496a7214cdabf08f53f5b1a560304601c9f65e0b9Shaopeng Jia   *     {@link #isNumberMatch(PhoneNumber, PhoneNumber)} for more details.
31451524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
314674aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia  public MatchType isNumberMatch(String firstNumber, String secondNumber) {
314774aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia    try {
314874aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia      PhoneNumber firstNumberAsProto = parse(firstNumber, UNKNOWN_REGION);
314974aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia      return isNumberMatch(firstNumberAsProto, secondNumber);
315074aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia    } catch (NumberParseException e) {
315174aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia      if (e.getErrorType() == NumberParseException.ErrorType.INVALID_COUNTRY_CODE) {
315274aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia        try {
315374aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia          PhoneNumber secondNumberAsProto = parse(secondNumber, UNKNOWN_REGION);
315474aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia          return isNumberMatch(secondNumberAsProto, firstNumber);
315574aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia        } catch (NumberParseException e2) {
315674aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia          if (e2.getErrorType() == NumberParseException.ErrorType.INVALID_COUNTRY_CODE) {
315774aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia            try {
315874aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia              PhoneNumber firstNumberProto = new PhoneNumber();
315974aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia              PhoneNumber secondNumberProto = new PhoneNumber();
316074aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia              parseHelper(firstNumber, null, false, false, firstNumberProto);
316174aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia              parseHelper(secondNumber, null, false, false, secondNumberProto);
316274aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia              return isNumberMatch(firstNumberProto, secondNumberProto);
316374aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia            } catch (NumberParseException e3) {
316474aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia              // Fall through and return MatchType.NOT_A_NUMBER.
316574aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia            }
316674aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia          }
316774aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia        }
316874aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia      }
316974aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia    }
317074aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia    // One or more of the phone numbers we are trying to match is not a viable phone number.
317174aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia    return MatchType.NOT_A_NUMBER;
31721524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
31731524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia
31741524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  /**
31751524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * Takes two phone numbers and compares them for equality. This is a convenience wrapper for
317696a7214cdabf08f53f5b1a560304601c9f65e0b9Shaopeng Jia   * {@link #isNumberMatch(PhoneNumber, PhoneNumber)}. No default region is known.
31771524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   *
31781524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @param firstNumber  first number to compare in proto buffer format.
31791524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   * @param secondNumber  second number to compare. Can contain formatting, and can have country
3180372bff8dd464574d36737d47e495cad14346653cShaopeng Jia   *     calling code specified with + at the start.
318174aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia   * @return  NOT_A_NUMBER, NO_MATCH, SHORT_NSN_MATCH, NSN_MATCH, EXACT_MATCH. See
318296a7214cdabf08f53f5b1a560304601c9f65e0b9Shaopeng Jia   *     {@link #isNumberMatch(PhoneNumber, PhoneNumber)} for more details.
31831524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia   */
318474aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia  public MatchType isNumberMatch(PhoneNumber firstNumber, String secondNumber) {
3185372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    // First see if the second number has an implicit country calling code, by attempting to parse
3186372bff8dd464574d36737d47e495cad14346653cShaopeng Jia    // it.
318774aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia    try {
318874aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia      PhoneNumber secondNumberAsProto = parse(secondNumber, UNKNOWN_REGION);
318974aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia      return isNumberMatch(firstNumber, secondNumberAsProto);
319074aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia    } catch (NumberParseException e) {
319174aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia      if (e.getErrorType() == NumberParseException.ErrorType.INVALID_COUNTRY_CODE) {
3192372bff8dd464574d36737d47e495cad14346653cShaopeng Jia        // The second number has no country calling code. EXACT_MATCH is no longer possible.
319374aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia        // We parse it as if the region was the same as that for the first number, and if
319474aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia        // EXACT_MATCH is returned, we replace this with NSN_MATCH.
319574aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia        String firstNumberRegion = getRegionCodeForCountryCode(firstNumber.getCountryCode());
319674aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia        try {
319774aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia          if (!firstNumberRegion.equals(UNKNOWN_REGION)) {
319874aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia            PhoneNumber secondNumberWithFirstNumberRegion = parse(secondNumber, firstNumberRegion);
319974aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia            MatchType match = isNumberMatch(firstNumber, secondNumberWithFirstNumberRegion);
320074aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia            if (match == MatchType.EXACT_MATCH) {
320174aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia              return MatchType.NSN_MATCH;
320274aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia            }
320374aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia            return match;
320474aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia          } else {
3205372bff8dd464574d36737d47e495cad14346653cShaopeng Jia            // If the first number didn't have a valid country calling code, then we parse the
3206372bff8dd464574d36737d47e495cad14346653cShaopeng Jia            // second number without one as well.
320774aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia            PhoneNumber secondNumberProto = new PhoneNumber();
320874aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia            parseHelper(secondNumber, null, false, false, secondNumberProto);
320974aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia            return isNumberMatch(firstNumber, secondNumberProto);
321074aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia          }
321174aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia        } catch (NumberParseException e2) {
321274aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia          // Fall-through to return NOT_A_NUMBER.
321374aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia        }
321474aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia      }
321574aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia    }
321674aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia    // One or more of the phone numbers we are trying to match is not a viable phone number.
321774aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia    return MatchType.NOT_A_NUMBER;
321874aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia  }
321974aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia
322074aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia  /**
3221528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia   * Returns true if the number can be dialled from outside the region, or unknown. If the number
3222528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia   * can only be dialled from within the region, returns false. Does not check the number is a valid
32238777f1913d34c3ecf72164ea85292e978e265eddShaopeng Jia   * number. Note that, at the moment, this method does not handle short numbers.
3224528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia   * TODO: Make this method public when we have enough metadata to make it worthwhile.
322574aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia   *
3226528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia   * @param number  the phone-number for which we want to know whether it is diallable from
3227528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia   *     outside the region
322874aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia   */
3229528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia  // @VisibleForTesting
323074aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia  boolean canBeInternationallyDialled(PhoneNumber number) {
3231203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    PhoneMetadata metadata = getMetadataForRegion(getRegionCodeForNumber(number));
3232203cf688f8d56e2c1f9828801b113110465f39a7Shaopeng Jia    if (metadata == null) {
3233528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia      // Note numbers belonging to non-geographical entities (e.g. +800 numbers) are always
3234528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia      // internationally diallable, and will be caught here.
323574aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia      return true;
323674aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia    }
3237528b0d12a556ff0c2d16f99d56fcdd62657f433cShaopeng Jia    String nationalSignificantNumber = getNationalSignificantNumber(number);
323874aa862e30b4d1b2722e90b1a8684274441a7541Shaopeng Jia    return !isNumberMatchingDesc(nationalSignificantNumber, metadata.getNoInternationalDialling());
32391524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia  }
3240f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia
3241f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia  /**
3242f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia   * Returns true if the supplied region supports mobile number portability. Returns false for
3243f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia   * invalid, unknown or regions that don't support mobile number portability.
3244f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia   *
3245f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia   * @param regionCode  the region for which we want to know whether it supports mobile number
3246f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia   *                    portability or not.
3247f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia   */
3248f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia  public boolean isMobileNumberPortableRegion(String regionCode) {
3249f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia    PhoneMetadata metadata = getMetadataForRegion(regionCode);
3250f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia    if (metadata == null) {
3251f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia      logger.log(Level.WARNING, "Invalid or unknown region code provided: " + regionCode);
3252f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia      return false;
3253f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia    }
3254f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia    return metadata.isMobileNumberPortableRegion();
3255f9768eb3c8f303725fb4f899598481cbc4fb76a3Shaopeng Jia  }
32561524ca8c53cd2c3adee0bb2e2b95a93fee976862Shaopeng Jia}
3257