String extension = maybeStripExtension(nationalNumber);
if (extension.length() > 0) {
phoneNumber.setExtension(extension);
}
PhoneMetadata regionMetadata = getMetadataForRegion(defaultRegion);
// Check to see if the number is given in international format so we know whether this number is
// from the default region or not.
StringBuilder normalizedNationalNumber = new StringBuilder();
int countryCode = 0;
try {
// TODO: This method should really just take in the string buffer that has already
// been created, and just remove the prefix, rather than taking in a string and then
// outputting a string buffer.
countryCode = maybeExtractCountryCode(nationalNumber.toString(), regionMetadata,
normalizedNationalNumber, keepRawInput, phoneNumber);
} catch (NumberParseException e) {
Matcher matcher = PLUS_CHARS_PATTERN.matcher(nationalNumber.toString());
if (e.getErrorType() == NumberParseException.ErrorType.INVALID_COUNTRY_CODE &&
matcher.lookingAt()) {
// Strip the plus-char, and try again.
countryCode = maybeExtractCountryCode(nationalNumber.substring(matcher.end()),
regionMetadata, normalizedNationalNumber,
keepRawInput, phoneNumber);
if (countryCode == 0) {
throw new NumberParseException(NumberParseException.ErrorType.INVALID_COUNTRY_CODE,
"Could not interpret numbers after plus-sign.");
}
} else {
throw new NumberParseException(e.getErrorType(), e.getMessage());
}
}
if (countryCode != 0) {
String phoneNumberRegion = getRegionCodeForCountryCode(countryCode);
if (!phoneNumberRegion.equals(defaultRegion)) {
// Metadata cannot be null because the country calling code is valid.
regionMetadata = getMetadataForRegionOrCallingCode(countryCode, phoneNumberRegion);
}
} else {
// If no extracted country calling code, use the region supplied instead. The national number
// is just the normalized version of the number we were given to parse.
normalize(nationalNumber);
normalizedNationalNumber.append(nationalNumber);
if (defaultRegion != null) {
countryCode = regionMetadata.getCountryCode();
phoneNumber.setCountryCode(countryCode);
} else if (keepRawInput) {
phoneNumber.clearCountryCodeSource();
}
}