Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
How to parse a phone number with the google phone number util
import com.mycompany.mymodel.Phone;
import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber;
import java.util.Locale;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import static com.mycompany.mymodel.Phone.phone;
public class PhoneParser {
public static Phone getPhoneAsValueObject(String plainTextValue) {
return getPhoneAsValueObject(plainTextValue, null);
}
public static Phone getPhoneAsValueObject(String plainTextValue, Locale phoneLocaleIfPossible) {
if(plainTextValue == null){
return phone().countryPrefix("0").areaCode("0").number(null).get();
}
final PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance();
final Phonenumber.PhoneNumber globalPhoneNumber;
final Phonenumber.PhoneNumber phoneNumberWithoutExtension;
final String country = phoneLocaleIfPossible == null ? null : phoneLocaleIfPossible.getCountry();
try {
globalPhoneNumber = phoneNumberUtil.parse(plainTextValue, country);
phoneNumberWithoutExtension = !plainTextValue.contains(",") ? globalPhoneNumber :
phoneNumberUtil.parse(plainTextValue.substring(0, plainTextValue.lastIndexOf(',')), country);
} catch (NumberParseException e) {
return phone().countryPrefix("0").areaCode("0").number(plainTextValue).get();
}
if (!phoneNumberUtil.isValidNumber(globalPhoneNumber)) {
return phone().countryPrefix("0").areaCode("0").number(plainTextValue).get();
}
String nationalNumber = phoneNumberUtil.formatNationalNumberWithCarrierCode(phoneNumberWithoutExtension, null).trim();
String nationalDirectDialingPrefix = phoneNumberUtil.getNddPrefixForRegion(phoneNumberUtil.getRegionCodeForNumber(phoneNumberWithoutExtension), false);
int areaCodeLength = phoneNumberUtil.getLengthOfGeographicalAreaCode(phoneNumberWithoutExtension);
String nationalNumberWithoutPrefix = nationalNumber.replaceFirst("^[^0-9]*" + nationalDirectDialingPrefix, "");
String areaCode = nationalNumberWithoutPrefix.chars().filter(theChar -> theChar >= '0' && theChar <= '9')
.limit(areaCodeLength).boxed().map(theChar -> String.valueOf((char)theChar.intValue())).collect(Collectors.joining());
String localNumber = nationalNumberWithoutPrefix.substring(nationalNumberWithoutPrefix.indexOf(areaCode) + areaCodeLength)
.replaceFirst("^[^0-9]*", "").trim();
return phone().countryPrefix(String.valueOf(phoneNumberWithoutExtension.getCountryCode()))
.areaCode(StringUtils.isEmpty(areaCode) ? "0" : areaCode)
.number(localNumber)
.setExtensionNumber(StringUtils.isEmpty(globalPhoneNumber.getExtension()) ? null : globalPhoneNumber.getExtension())
.get();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment