Browse Source

Merge branch 'master' into hash_as_diallable_char

reviewable/pr1312/r2
Tiago Salem Herrmann 9 years ago
committed by GitHub
parent
commit
879ebce8b7
669 changed files with 45115 additions and 36566 deletions
  1. +9
    -1
      .travis.yml
  2. +1
    -1
      README.md
  3. +1
    -1
      cpp/CMakeLists.txt
  4. +832
    -769
      cpp/src/phonenumbers/alternate_format.cc
  5. +12829
    -10859
      cpp/src/phonenumbers/lite_metadata.cc
  6. +12480
    -12175
      cpp/src/phonenumbers/metadata.cc
  7. +63
    -50
      cpp/src/phonenumbers/phonenumberutil.cc
  8. +3227
    -3163
      cpp/src/phonenumbers/short_metadata.cc
  9. +993
    -923
      cpp/src/phonenumbers/test_metadata.cc
  10. +8
    -10
      cpp/test/phonenumbers/phonenumberutil_test.cc
  11. +4
    -4
      java/carrier/pom.xml
  12. +3
    -3
      java/carrier/src/com/google/i18n/phonenumbers/PhoneNumberToCarrierMapper.java
  13. BIN
      java/carrier/src/com/google/i18n/phonenumbers/carrier/data/243_en
  14. BIN
      java/carrier/src/com/google/i18n/phonenumbers/carrier/data/27_en
  15. BIN
      java/carrier/src/com/google/i18n/phonenumbers/carrier/data/91_en
  16. BIN
      java/carrier/src/com/google/i18n/phonenumbers/carrier/data/963_en
  17. BIN
      java/carrier/src/com/google/i18n/phonenumbers/carrier/data/config
  18. +5
    -5
      java/demo/pom.xml
  19. +4
    -4
      java/geocoder/pom.xml
  20. +5
    -17
      java/geocoder/src/com/google/i18n/phonenumbers/PhoneNumberToTimeZonesMapper.java
  21. +2
    -2
      java/geocoder/src/com/google/i18n/phonenumbers/geocoding/PhoneNumberOfflineGeocoder.java
  22. BIN
      java/geocoder/src/com/google/i18n/phonenumbers/geocoding/data/82_pl
  23. BIN
      java/geocoder/src/com/google/i18n/phonenumbers/geocoding/data/82_pt
  24. BIN
      java/geocoder/src/com/google/i18n/phonenumbers/geocoding/data/82_ro
  25. BIN
      java/geocoder/src/com/google/i18n/phonenumbers/geocoding/data/82_ru
  26. BIN
      java/geocoder/src/com/google/i18n/phonenumbers/geocoding/data/82_sl
  27. BIN
      java/geocoder/src/com/google/i18n/phonenumbers/geocoding/data/82_sr
  28. BIN
      java/geocoder/src/com/google/i18n/phonenumbers/geocoding/data/82_uk
  29. BIN
      java/geocoder/src/com/google/i18n/phonenumbers/geocoding/data/82_vi
  30. BIN
      java/geocoder/src/com/google/i18n/phonenumbers/geocoding/data/config
  31. +3
    -3
      java/internal/prefixmapper/pom.xml
  32. +2
    -2
      java/internal/prefixmapper/src/com/google/i18n/phonenumbers/prefixmapper/MappingFileProvider.java
  33. +2
    -2
      java/internal/prefixmapper/src/com/google/i18n/phonenumbers/prefixmapper/PhonePrefixMap.java
  34. +8
    -8
      java/internal/prefixmapper/src/com/google/i18n/phonenumbers/prefixmapper/PrefixFileReader.java
  35. +2
    -2
      java/internal/prefixmapper/src/com/google/i18n/phonenumbers/prefixmapper/PrefixTimeZonesMap.java
  36. +2
    -2
      java/internal/prefixmapper/test/com/google/i18n/phonenumbers/prefixmapper/MappingFileProviderTest.java
  37. BIN
      java/lib/protobuf-javanano-3.0.0-alpha-7.jar
  38. +0
    -54
      java/lib/protobuf-javanano-readme.md
  39. +21
    -11
      java/libphonenumber/pom.xml
  40. +45
    -45
      java/libphonenumber/src/com/google/i18n/phonenumbers/AsYouTypeFormatter.java
  41. +3
    -1
      java/libphonenumber/src/com/google/i18n/phonenumbers/MetadataLoader.java
  42. +13
    -43
      java/libphonenumber/src/com/google/i18n/phonenumbers/MetadataManager.java
  43. +2
    -1
      java/libphonenumber/src/com/google/i18n/phonenumbers/MetadataSource.java
  44. +8
    -9
      java/libphonenumber/src/com/google/i18n/phonenumbers/MultiFileMetadataSourceImpl.java
  45. +23
    -9
      java/libphonenumber/src/com/google/i18n/phonenumbers/NumberParseException.java
  46. +2
    -2
      java/libphonenumber/src/com/google/i18n/phonenumbers/PhoneNumberMatch.java
  47. +42
    -42
      java/libphonenumber/src/com/google/i18n/phonenumbers/PhoneNumberMatcher.java
  48. +287
    -309
      java/libphonenumber/src/com/google/i18n/phonenumbers/PhoneNumberUtil.java
  49. +1124
    -0
      java/libphonenumber/src/com/google/i18n/phonenumbers/Phonemetadata.java
  50. +2
    -2
      java/libphonenumber/src/com/google/i18n/phonenumbers/RegexCache.java
  51. +29
    -29
      java/libphonenumber/src/com/google/i18n/phonenumbers/ShortNumberInfo.java
  52. +8
    -9
      java/libphonenumber/src/com/google/i18n/phonenumbers/SingleFileMetadataSourceImpl.java
  53. BIN
      java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_255
  54. BIN
      java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_27
  55. BIN
      java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_30
  56. BIN
      java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_31
  57. BIN
      java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_34
  58. BIN
      java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_350
  59. BIN
      java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_351
  60. BIN
      java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_352
  61. BIN
      java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_358
  62. BIN
      java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_359
  63. BIN
      java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_36
  64. BIN
      java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_372
  65. BIN
      java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_373
  66. BIN
      java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_380
  67. BIN
      java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_381
  68. BIN
      java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_385
  69. BIN
      java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_43
  70. BIN
      java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_44
  71. BIN
      java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_49
  72. BIN
      java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_505
  73. BIN
      java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_506
  74. BIN
      java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_54
  75. BIN
      java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_55
  76. BIN
      java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_58
  77. BIN
      java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_595
  78. BIN
      java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_61
  79. BIN
      java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_62
  80. BIN
      java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_63
  81. BIN
      java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_66
  82. BIN
      java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_675
  83. BIN
      java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_676
  84. BIN
      java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_679
  85. BIN
      java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_7
  86. BIN
      java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_81
  87. BIN
      java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_84
  88. BIN
      java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_855
  89. BIN
      java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_90
  90. BIN
      java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_91
  91. BIN
      java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_94
  92. BIN
      java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_95
  93. BIN
      java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_971
  94. BIN
      java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_972
  95. BIN
      java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_995
  96. BIN
      java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberMetadataProto_800
  97. BIN
      java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberMetadataProto_808
  98. BIN
      java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberMetadataProto_870
  99. BIN
      java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberMetadataProto_878
  100. BIN
      java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberMetadataProto_881

+ 9
- 1
.travis.yml View File

@ -1,5 +1,13 @@
language: java
install:
# Invoke the "travis" profile during Maven steps; see <profile> in pom.xml
# files. This is configured not to build the "cpp-build" module.
# The "mvn install" command will run by default during the "install" phase by
# Travis, without the profile flag. Here we customize the install phase to use
# the relevant profile. If we want to build "cpp-build" with Travis CI it's safe
# to remove this line entirely.
- mvn install -P travis -DskipTests=true -Dmaven.javadoc.skip=true -B -V
script:
- mvn test
- mvn -P travis test
- ant clean -f java/build.xml && ant jar -f java/build.xml
- ant junit -f java/build.xml

+ 1
- 1
README.md View File

@ -20,7 +20,7 @@ If you want to report an issue, or to contribute to the project, please read the
* ` PhoneNumberOfflineGeocoder ` - provides geographical information related to a phone number.
* ` PhoneNumberToCarrierMapper ` - provides carrier information related to a phone number.
# Demo (v7.6.0)
# Demo (v7.7.0)
[Java](http://libphonenumber.appspot.com/)
[JavaScript](https://rawgit.com/googlei18n/libphonenumber/master/javascript/i18n/phonenumbers/demo-compiled.html)


+ 1
- 1
cpp/CMakeLists.txt View File

@ -18,7 +18,7 @@ cmake_minimum_required (VERSION 2.8)
project (libphonenumber)
set (libphonenumber_VERSION_MAJOR 7)
set (libphonenumber_VERSION_MINOR 6)
set (libphonenumber_VERSION_MINOR 7)
# Helper functions dealing with finding libraries and programs this library
# depends on.


+ 832
- 769
cpp/src/phonenumbers/alternate_format.cc
File diff suppressed because it is too large
View File


+ 12829
- 10859
cpp/src/phonenumbers/lite_metadata.cc
File diff suppressed because it is too large
View File


+ 12480
- 12175
cpp/src/phonenumbers/metadata.cc
File diff suppressed because it is too large
View File


+ 63
- 50
cpp/src/phonenumbers/phonenumberutil.cc View File

@ -52,7 +52,9 @@
namespace i18n {
namespace phonenumbers {
using google::protobuf::RepeatedField;
using google::protobuf::RepeatedPtrField;
using std::find;
// static constants
const size_t PhoneNumberUtil::kMinLengthForNsn;
@ -263,17 +265,41 @@ void NormalizeHelper(const map<char32, char>& normalization_replacements,
number->assign(normalized_number);
}
PhoneNumberUtil::ValidationResult TestNumberLengthAgainstPattern(
const RegExp& number_pattern, const string& number) {
string extracted_number;
if (number_pattern.FullMatch(number, &extracted_number)) {
// Helper method to check a number against possible lengths for this number, and
// determine whether it matches, or is too short or too long. Currently, if a
// number pattern suggests that numbers of length 7 and 10 are possible, and a
// number in between these possible lengths is entered, such as of length 8,
// this will return TOO_LONG.
PhoneNumberUtil::ValidationResult TestNumberLength(
const string& number, const PhoneNumberDesc& phone_number_desc) {
RepeatedField<int> possible_lengths = phone_number_desc.possible_length();
RepeatedField<int> local_lengths =
phone_number_desc.possible_length_local_only();
int actual_length = number.length();
if (find(local_lengths.begin(), local_lengths.end(), actual_length) !=
local_lengths.end()) {
return PhoneNumberUtil::IS_POSSIBLE;
}
if (number_pattern.PartialMatch(number, &extracted_number)) {
return PhoneNumberUtil::TOO_LONG;
} else {
// There should always be "possibleLengths" set for every element. This will
// be a build-time check once ShortNumberMetadata.xml is migrated to contain
// this information as well.
int minimum_length = possible_lengths.Get(0);
if (minimum_length == actual_length) {
return PhoneNumberUtil::IS_POSSIBLE;
} else if (minimum_length > actual_length) {
return PhoneNumberUtil::TOO_SHORT;
} else if (*(possible_lengths.end() - 1) < actual_length) {
return PhoneNumberUtil::TOO_LONG;
}
// Note that actually the number is not too long if possible_lengths does not
// contain the length: we know it is less than the highest possible number
// length, and higher than the lowest possible number length. However, we
// don't currently have an enum to express this, so we return TOO_LONG in the
// short-term.
// We skip the first element; we've already checked it.
return find(possible_lengths.begin() + 1, possible_lengths.end(),
actual_length) != possible_lengths.end()
? PhoneNumberUtil::IS_POSSIBLE : PhoneNumberUtil::TOO_LONG;
}
} // namespace
@ -662,8 +688,7 @@ PhoneNumberUtil::PhoneNumberUtil()
country_calling_code_to_region_map.end());
// Sort all the pairs in ascending order according to country calling code.
std::sort(country_calling_code_to_region_code_map_->begin(),
country_calling_code_to_region_code_map_->end(),
OrderByFirst());
country_calling_code_to_region_code_map_->end(), OrderByFirst());
}
PhoneNumberUtil::~PhoneNumberUtil() {
@ -787,9 +812,9 @@ bool PhoneNumberUtil::HasValidCountryCallingCode(
// locate the pair with the same country_code in the sorted vector.
IntRegionsPair target_pair;
target_pair.first = country_calling_code;
return (binary_search(country_calling_code_to_region_code_map_->begin(),
country_calling_code_to_region_code_map_->end(),
target_pair, OrderByFirst()));
return (std::binary_search(country_calling_code_to_region_code_map_->begin(),
country_calling_code_to_region_code_map_->end(),
target_pair, OrderByFirst()));
}
// Returns a pointer to the phone metadata for the appropriate region or NULL
@ -1034,8 +1059,8 @@ void PhoneNumberUtil::FormatNumberForMobileDialing(
string national_number;
GetNationalSignificantNumber(number_no_extension, &national_number);
if (CanBeInternationallyDialled(number_no_extension) &&
!IsShorterThanPossibleNormalNumber(region_metadata,
national_number)) {
TestNumberLength(national_number, region_metadata->general_desc()) !=
TOO_SHORT) {
Format(number_no_extension, INTERNATIONAL, formatted_number);
} else {
Format(number_no_extension, NATIONAL, formatted_number);
@ -1056,8 +1081,9 @@ void PhoneNumberUtil::FormatNumberForMobileDialing(
// national format, but don't have it when used for display. The
// reverse is true for mobile numbers. As a result, we output them in
// the international format to make it work.
((region_code == "MX" || region_code == "CL") &&
is_fixed_line_or_mobile)) &&
((region_code == "MX" ||
region_code == "CL") &&
is_fixed_line_or_mobile)) &&
CanBeInternationallyDialled(number_no_extension)) {
Format(number_no_extension, INTERNATIONAL, formatted_number);
} else {
@ -1986,11 +2012,11 @@ PhoneNumberUtil::ErrorType PhoneNumberUtil::ParseHelper(
&potential_national_number,
&carrier_code);
// We require that the NSN remaining after stripping the national prefix
// and carrier code be of a possible length for the region. Otherwise, we
// don't do the stripping, since the original number could be a valid short
// number.
if (!IsShorterThanPossibleNormalNumber(country_metadata,
potential_national_number)) {
// and carrier code be long enough to be a possible length for the region.
// Otherwise, we don't do the stripping, since the original number could be
// a valid short number.
if (TestNumberLength(potential_national_number,
country_metadata->general_desc()) != TOO_SHORT) {
normalized_national_number.assign(potential_national_number);
if (keep_raw_input) {
temp_number.set_preferred_domestic_carrier_code(carrier_code);
@ -2099,10 +2125,7 @@ PhoneNumberUtil::ValidationResult PhoneNumberUtil::IsPossibleNumberWithReason(
// Metadata cannot be NULL because the country calling code is valid.
const PhoneMetadata* metadata =
GetMetadataForRegionOrCallingCode(country_code, region_code);
const RegExp& possible_number_pattern = reg_exps_->regexp_cache_->GetRegExp(
StrCat("(", metadata->general_desc().possible_number_pattern(), ")"));
return TestNumberLengthAgainstPattern(possible_number_pattern,
national_number);
return TestNumberLength(national_number, metadata->general_desc());
}
bool PhoneNumberUtil::TruncateTooLongNumber(PhoneNumber* number) const {
@ -2204,19 +2227,22 @@ void PhoneNumberUtil::SetItalianLeadingZerosForPhoneNumber(
}
}
bool PhoneNumberUtil::IsNumberPossibleForDesc(
const string& national_number, const PhoneNumberDesc& number_desc) const {
return reg_exps_->regexp_cache_.get()->
GetRegExp(number_desc.possible_number_pattern())
.FullMatch(national_number);
}
bool PhoneNumberUtil::IsNumberMatchingDesc(
const string& national_number, const PhoneNumberDesc& number_desc) const {
return IsNumberPossibleForDesc(national_number, number_desc) &&
reg_exps_->regexp_cache_.get()->
GetRegExp(number_desc.national_number_pattern())
.FullMatch(national_number);
// Check if any possible number lengths are present; if so, we use them to
// avoid checking the validation pattern if they don't match. If they are
// absent, this means they match the general description, which we have
// already checked before checking a specific number type.
int actual_length = national_number.length();
if (number_desc.possible_length_size() > 0 &&
std::find(number_desc.possible_length().begin(),
number_desc.possible_length().end(),
actual_length) == number_desc.possible_length().end()) {
return false;
}
return reg_exps_->regexp_cache_
->GetRegExp(number_desc.national_number_pattern())
.FullMatch(national_number);
}
PhoneNumberUtil::PhoneNumberType PhoneNumberUtil::GetNumberTypeHelper(
@ -2733,16 +2759,12 @@ PhoneNumberUtil::ErrorType PhoneNumberUtil::MaybeExtractCountryCode(
NULL);
VLOG(4) << "Number without country calling code prefix: "
<< potential_national_number;
const RegExp& possible_number_pattern =
reg_exps_->regexp_cache_->GetRegExp(
StrCat("(", general_num_desc.possible_number_pattern(), ")"));
// If the number was not valid before but is valid now, or if it was too
// long before, we consider the number with the country code stripped to
// be a better result and keep that instead.
if ((!valid_number_pattern.FullMatch(*national_number) &&
valid_number_pattern.FullMatch(potential_national_number)) ||
TestNumberLengthAgainstPattern(possible_number_pattern,
*national_number) == TOO_LONG) {
TestNumberLength(*national_number, general_num_desc) == TOO_LONG) {
national_number->assign(potential_national_number);
if (keep_raw_input) {
phone_number->set_country_code_source(
@ -2898,15 +2920,6 @@ AsYouTypeFormatter* PhoneNumberUtil::GetAsYouTypeFormatter(
return new AsYouTypeFormatter(region_code);
}
bool PhoneNumberUtil::IsShorterThanPossibleNormalNumber(
const PhoneMetadata* country_metadata, const string& number) const {
const RegExp& possible_number_pattern =
reg_exps_->regexp_cache_->GetRegExp(StrCat("(",
country_metadata->general_desc().possible_number_pattern(), ")"));
return TestNumberLengthAgainstPattern(possible_number_pattern, number) ==
PhoneNumberUtil::TOO_SHORT;
}
bool PhoneNumberUtil::CanBeInternationallyDialled(
const PhoneNumber& number) const {
string region_code;


+ 3227
- 3163
cpp/src/phonenumbers/short_metadata.cc
File diff suppressed because it is too large
View File


+ 993
- 923
cpp/src/phonenumbers/test_metadata.cc
File diff suppressed because it is too large
View File


+ 8
- 10
cpp/test/phonenumbers/phonenumberutil_test.cc View File

@ -132,11 +132,6 @@ class PhoneNumberUtilTest : public testing::Test {
phone_number);
}
static bool Equals(const PhoneNumberDesc& expected_number,
const PhoneNumberDesc& actual_number) {
return ExactlySameAs(expected_number, actual_number);
}
bool ContainsOnlyValidDigits(const string& s) const {
return phone_util_.ContainsOnlyValidDigits(s);
}
@ -228,7 +223,10 @@ TEST_F(PhoneNumberUtilTest, GetInstanceLoadUSMetadata) {
metadata->general_desc().national_number_pattern());
EXPECT_EQ("\\d{7}(?:\\d{3})?",
metadata->general_desc().possible_number_pattern());
EXPECT_TRUE(Equals(metadata->general_desc(), metadata->fixed_line()));
// Fixed-line data should be inherited from the general desc for the national
// number pattern, since it wasn't overridden.
EXPECT_EQ(metadata->general_desc().national_number_pattern(),
metadata->fixed_line().national_number_pattern());
EXPECT_EQ("\\d{10}", metadata->toll_free().possible_number_pattern());
EXPECT_EQ(1, metadata->general_desc().possible_length_size());
EXPECT_EQ(10, metadata->general_desc().possible_length(0));
@ -1157,7 +1155,7 @@ TEST_F(PhoneNumberUtilTest, FormatNumberForMobileDialing) {
// added before dialing from a mobile phone for regular length numbers, but
// not for short numbers.
test_number.set_country_code(36);
test_number.set_national_number(301234567L);
test_number.set_national_number(301234567ULL);
phone_util_.FormatNumberForMobileDialing(
test_number, RegionCode::HU(), false, &formatted_number);
EXPECT_EQ("06301234567", formatted_number);
@ -1176,7 +1174,7 @@ TEST_F(PhoneNumberUtilTest, FormatNumberForMobileDialing) {
// numbers are always output in international format, but short numbers are
// in national format.
test_number.set_country_code(1);
test_number.set_national_number(6502530000L);
test_number.set_national_number(6502530000ULL);
phone_util_.FormatNumberForMobileDialing(
test_number, RegionCode::US(), false, &formatted_number);
EXPECT_EQ("+16502530000", formatted_number);
@ -1365,7 +1363,7 @@ TEST_F(PhoneNumberUtilTest, GetLengthOfGeographicalAreaCode) {
// A mobile number in Argentina also has an area code.
number.set_country_code(54);
number.set_national_number(91187654321);
number.set_national_number(91187654321ULL);
EXPECT_EQ(3, phone_util_.GetLengthOfGeographicalAreaCode(number));
// Google Sydney, which has area code "2".
@ -1755,7 +1753,7 @@ TEST_F(PhoneNumberUtilTest, IsPossibleNumber) {
RegionCode::GB()));
EXPECT_TRUE(phone_util_.IsPossibleNumberForString("+44 20 7031 3000",
RegionCode::GB()));
EXPECT_TRUE(phone_util_.IsPossibleNumberForString("(020) 7031 3000",
EXPECT_TRUE(phone_util_.IsPossibleNumberForString("(020) 7031 300",
RegionCode::GB()));
EXPECT_TRUE(phone_util_.IsPossibleNumberForString("7031 3000",
RegionCode::GB()));


+ 4
- 4
java/carrier/pom.xml View File

@ -3,14 +3,14 @@
<modelVersion>4.0.0</modelVersion>
<groupId>com.googlecode.libphonenumber</groupId>
<artifactId>carrier</artifactId>
<version>1.42-SNAPSHOT</version>
<version>1.44-SNAPSHOT</version>
<packaging>jar</packaging>
<url>https://github.com/googlei18n/libphonenumber/</url>
<parent>
<groupId>com.googlecode.libphonenumber</groupId>
<artifactId>libphonenumber-parent</artifactId>
<version>7.6.1-SNAPSHOT</version>
<version>7.7.1-SNAPSHOT</version>
</parent>
<build>
@ -56,12 +56,12 @@
<dependency>
<groupId>com.googlecode.libphonenumber</groupId>
<artifactId>libphonenumber</artifactId>
<version>7.6.1-SNAPSHOT</version>
<version>7.7.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.googlecode.libphonenumber</groupId>
<artifactId>prefixmapper</artifactId>
<version>2.52-SNAPSHOT</version>
<version>2.54-SNAPSHOT</version>
</dependency>
</dependencies>


+ 3
- 3
java/carrier/src/com/google/i18n/phonenumbers/PhoneNumberToCarrierMapper.java View File

@ -117,8 +117,8 @@ public class PhoneNumberToCarrierMapper {
* Checks if the supplied number type supports carrier lookup.
*/
private boolean isMobile(PhoneNumberType numberType) {
return (numberType == PhoneNumberType.MOBILE ||
numberType == PhoneNumberType.FIXED_LINE_OR_MOBILE ||
numberType == PhoneNumberType.PAGER);
return (numberType == PhoneNumberType.MOBILE
|| numberType == PhoneNumberType.FIXED_LINE_OR_MOBILE
|| numberType == PhoneNumberType.PAGER);
}
}

BIN
java/carrier/src/com/google/i18n/phonenumbers/carrier/data/243_en View File


BIN
java/carrier/src/com/google/i18n/phonenumbers/carrier/data/27_en View File


BIN
java/carrier/src/com/google/i18n/phonenumbers/carrier/data/91_en View File


BIN
java/carrier/src/com/google/i18n/phonenumbers/carrier/data/963_en View File


BIN
java/carrier/src/com/google/i18n/phonenumbers/carrier/data/config View File


+ 5
- 5
java/demo/pom.xml View File

@ -4,11 +4,11 @@
<parent>
<artifactId>libphonenumber-parent</artifactId>
<groupId>com.googlecode.libphonenumber</groupId>
<version>7.6.1-SNAPSHOT</version>
<version>7.7.1-SNAPSHOT</version>
</parent>
<groupId>com.googlecode.libphonenumber</groupId>
<artifactId>demo</artifactId>
<version>7.6.1-SNAPSHOT</version>
<version>7.7.1-SNAPSHOT</version>
<properties>
<gae.version>1.9.32</gae.version>
@ -48,17 +48,17 @@
<dependency>
<groupId>com.googlecode.libphonenumber</groupId>
<artifactId>libphonenumber</artifactId>
<version>7.6.1-SNAPSHOT</version>
<version>7.7.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.googlecode.libphonenumber</groupId>
<artifactId>geocoder</artifactId>
<version>2.52-SNAPSHOT</version>
<version>2.54-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.googlecode.libphonenumber</groupId>
<artifactId>carrier</artifactId>
<version>1.42-SNAPSHOT</version>
<version>1.44-SNAPSHOT</version>
</dependency>
</dependencies>


+ 4
- 4
java/geocoder/pom.xml View File

@ -3,14 +3,14 @@
<modelVersion>4.0.0</modelVersion>
<groupId>com.googlecode.libphonenumber</groupId>
<artifactId>geocoder</artifactId>
<version>2.52-SNAPSHOT</version>
<version>2.54-SNAPSHOT</version>
<packaging>jar</packaging>
<url>https://github.com/googlei18n/libphonenumber/</url>
<parent>
<groupId>com.googlecode.libphonenumber</groupId>
<artifactId>libphonenumber-parent</artifactId>
<version>7.6.1-SNAPSHOT</version>
<version>7.7.1-SNAPSHOT</version>
</parent>
<build>
@ -64,12 +64,12 @@
<dependency>
<groupId>com.googlecode.libphonenumber</groupId>
<artifactId>libphonenumber</artifactId>
<version>7.6.1-SNAPSHOT</version>
<version>7.7.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.googlecode.libphonenumber</groupId>
<artifactId>prefixmapper</artifactId>
<version>2.52-SNAPSHOT</version>
<version>2.54-SNAPSHOT</version>
</dependency>
</dependencies>


+ 5
- 17
java/geocoder/src/com/google/i18n/phonenumbers/PhoneNumberToTimeZonesMapper.java View File

@ -45,7 +45,7 @@ public class PhoneNumberToTimeZonesMapper {
UNKNOWN_TIME_ZONE_LIST.add(UNKNOWN_TIMEZONE);
}
private static final Logger LOGGER =
private static final Logger logger =
Logger.getLogger(PhoneNumberToTimeZonesMapper.class.getName());
private PrefixTimeZonesMap prefixTimeZonesMap = null;
@ -68,7 +68,7 @@ public class PhoneNumberToTimeZonesMapper {
in = new ObjectInputStream(source);
map.readExternal(in);
} catch (IOException e) {
LOGGER.log(Level.WARNING, e.toString());
logger.log(Level.WARNING, e.toString());
} finally {
close(in);
}
@ -80,7 +80,7 @@ public class PhoneNumberToTimeZonesMapper {
try {
in.close();
} catch (IOException e) {
LOGGER.log(Level.WARNING, e.toString());
logger.log(Level.WARNING, e.toString());
}
}
}
@ -137,25 +137,13 @@ public class PhoneNumberToTimeZonesMapper {
PhoneNumberType numberType = PhoneNumberUtil.getInstance().getNumberType(number);
if (numberType == PhoneNumberType.UNKNOWN) {
return UNKNOWN_TIME_ZONE_LIST;
} else if (!canBeGeocoded(numberType)) {
} else if (!PhoneNumberUtil.getInstance().isNumberGeographical(
numberType, number.getCountryCode())) {
return getCountryLevelTimeZonesforNumber(number);
}
return getTimeZonesForGeographicalNumber(number);
}
/**
* A similar method is implemented as PhoneNumberUtil.isNumberGeographical, which performs a
* stricter check, as it determines if a number has a geographical association. Also, if new
* phone number types were added, we should check if this other method should be updated too.
* TODO: Remove duplication by completing the logic in the method in PhoneNumberUtil.
* For more information, see the comments in that method.
*/
private boolean canBeGeocoded(PhoneNumberType numberType) {
return (numberType == PhoneNumberType.FIXED_LINE ||
numberType == PhoneNumberType.MOBILE ||
numberType == PhoneNumberType.FIXED_LINE_OR_MOBILE);
}
/**
* Returns a String with the ICU unknown time zone.
*/


+ 2
- 2
java/geocoder/src/com/google/i18n/phonenumbers/geocoding/PhoneNumberOfflineGeocoder.java View File

@ -88,8 +88,8 @@ public class PhoneNumberOfflineGeocoder {
* Returns the customary display name in the given language for the given region.
*/
private String getRegionDisplayName(String regionCode, Locale language) {
return (regionCode == null || regionCode.equals("ZZ") ||
regionCode.equals(PhoneNumberUtil.REGION_CODE_FOR_NON_GEO_ENTITY))
return (regionCode == null || regionCode.equals("ZZ")
|| regionCode.equals(PhoneNumberUtil.REGION_CODE_FOR_NON_GEO_ENTITY))
? "" : new Locale("", regionCode).getDisplayCountry(language);
}


BIN
java/geocoder/src/com/google/i18n/phonenumbers/geocoding/data/82_pl View File


BIN
java/geocoder/src/com/google/i18n/phonenumbers/geocoding/data/82_pt View File


BIN
java/geocoder/src/com/google/i18n/phonenumbers/geocoding/data/82_ro View File


BIN
java/geocoder/src/com/google/i18n/phonenumbers/geocoding/data/82_ru View File


BIN
java/geocoder/src/com/google/i18n/phonenumbers/geocoding/data/82_sl View File


BIN
java/geocoder/src/com/google/i18n/phonenumbers/geocoding/data/82_sr View File


BIN
java/geocoder/src/com/google/i18n/phonenumbers/geocoding/data/82_uk View File


BIN
java/geocoder/src/com/google/i18n/phonenumbers/geocoding/data/82_vi View File


BIN
java/geocoder/src/com/google/i18n/phonenumbers/geocoding/data/config View File


+ 3
- 3
java/internal/prefixmapper/pom.xml View File

@ -3,14 +3,14 @@
<modelVersion>4.0.0</modelVersion>
<groupId>com.googlecode.libphonenumber</groupId>
<artifactId>prefixmapper</artifactId>
<version>2.52-SNAPSHOT</version>
<version>2.54-SNAPSHOT</version>
<packaging>jar</packaging>
<url>https://github.com/googlei18n/libphonenumber/</url>
<parent>
<groupId>com.googlecode.libphonenumber</groupId>
<artifactId>libphonenumber-parent</artifactId>
<version>7.6.1-SNAPSHOT</version>
<version>7.7.1-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
@ -51,7 +51,7 @@
<dependency>
<groupId>com.googlecode.libphonenumber</groupId>
<artifactId>libphonenumber</artifactId>
<version>7.6.1-SNAPSHOT</version>
<version>7.7.1-SNAPSHOT</version>
</dependency>
</dependencies>


+ 2
- 2
java/internal/prefixmapper/src/com/google/i18n/phonenumbers/prefixmapper/MappingFileProvider.java View File

@ -210,8 +210,8 @@ public class MappingFileProvider implements Externalizable {
}
private boolean onlyOneOfScriptOrRegionIsEmpty(String script, String region) {
return (script.length() == 0 && region.length() > 0) ||
(region.length() == 0 && script.length() > 0);
return (script.length() == 0 && region.length() > 0)
|| (region.length() == 0 && script.length() > 0);
}
private StringBuilder constructFullLocale(String language, String script, String region) {


+ 2
- 2
java/internal/prefixmapper/src/com/google/i18n/phonenumbers/prefixmapper/PhonePrefixMap.java View File

@ -37,7 +37,7 @@ import java.util.logging.Logger;
*/
public class PhonePrefixMap implements Externalizable {
private final PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
private static final Logger LOGGER = Logger.getLogger(PhonePrefixMap.class.getName());
private static final Logger logger = Logger.getLogger(PhonePrefixMap.class.getName());
private PhonePrefixMapStorageStrategy phonePrefixMapStorage;
@ -96,7 +96,7 @@ public class PhonePrefixMap implements Externalizable {
return sizeOfFlyweightMapStorage < sizeOfDefaultMapStorage
? flyweightMapStorage : defaultMapStorage;
} catch (IOException e) {
LOGGER.severe(e.getMessage());
logger.severe(e.getMessage());
return createFlyweightMapStorage();
}
}


+ 8
- 8
java/internal/prefixmapper/src/com/google/i18n/phonenumbers/prefixmapper/PrefixFileReader.java View File

@ -32,7 +32,7 @@ import java.util.logging.Logger;
* @author Shaopeng Jia
*/
public class PrefixFileReader {
private static final Logger LOGGER = Logger.getLogger(PrefixFileReader.class.getName());
private static final Logger logger = Logger.getLogger(PrefixFileReader.class.getName());
private final String phonePrefixDataDirectory;
// The mappingFileProvider knows for which combination of countryCallingCode and language a phone
@ -56,7 +56,7 @@ public class PrefixFileReader {
in = new ObjectInputStream(source);
mappingFileProvider.readExternal(in);
} catch (IOException e) {
LOGGER.log(Level.WARNING, e.toString());
logger.log(Level.WARNING, e.toString());
} finally {
close(in);
}
@ -84,7 +84,7 @@ public class PrefixFileReader {
map.readExternal(in);
availablePhonePrefixMaps.put(fileName, map);
} catch (IOException e) {
LOGGER.log(Level.WARNING, e.toString());
logger.log(Level.WARNING, e.toString());
} finally {
close(in);
}
@ -95,7 +95,7 @@ public class PrefixFileReader {
try {
in.close();
} catch (IOException e) {
LOGGER.log(Level.WARNING, e.toString());
logger.log(Level.WARNING, e.toString());
}
}
}
@ -116,12 +116,12 @@ public class PrefixFileReader {
int countryCallingCode = number.getCountryCode();
// As the NANPA data is split into multiple files covering 3-digit areas, use a phone number
// prefix of 4 digits for NANPA instead, e.g. 1650.
int phonePrefix = (countryCallingCode != 1) ?
countryCallingCode : (1000 + (int) (number.getNationalNumber() / 10000000));
int phonePrefix = (countryCallingCode != 1)
? countryCallingCode : (1000 + (int) (number.getNationalNumber() / 10000000));
PhonePrefixMap phonePrefixDescriptions =
getPhonePrefixDescriptions(phonePrefix, lang, script, region);
String description = (phonePrefixDescriptions != null) ?
phonePrefixDescriptions.lookup(number) : null;
String description = (phonePrefixDescriptions != null)
? phonePrefixDescriptions.lookup(number) : null;
// When a location is not available in the requested language, fall back to English.
if ((description == null || description.length() == 0) && mayFallBackToEnglish(lang)) {
PhonePrefixMap defaultMap = getPhonePrefixDescriptions(phonePrefix, "en", "", "");


+ 2
- 2
java/internal/prefixmapper/src/com/google/i18n/phonenumbers/prefixmapper/PrefixTimeZonesMap.java View File

@ -88,8 +88,8 @@ public class PrefixTimeZonesMap implements Externalizable {
* @return the list of corresponding time zones
*/
public List<String> lookupTimeZonesForNumber(PhoneNumber number) {
long phonePrefix = Long.parseLong(number.getCountryCode() +
PhoneNumberUtil.getInstance().getNationalSignificantNumber(number));
long phonePrefix = Long.parseLong(number.getCountryCode()
+ PhoneNumberUtil.getInstance().getNationalSignificantNumber(number));
return lookupTimeZonesForNumber(phonePrefix);
}


+ 2
- 2
java/internal/prefixmapper/test/com/google/i18n/phonenumbers/prefixmapper/MappingFileProviderTest.java View File

@ -38,7 +38,7 @@ import java.util.logging.Logger;
*/
public class MappingFileProviderTest extends TestCase {
private final MappingFileProvider mappingProvider = new MappingFileProvider();
private static final Logger LOGGER = Logger.getLogger(MappingFileProviderTest.class.getName());
private static final Logger logger = Logger.getLogger(MappingFileProviderTest.class.getName());
public MappingFileProviderTest() {
SortedMap<Integer, Set<String>> mapping = new TreeMap<Integer, Set<String>>();
@ -68,7 +68,7 @@ public class MappingFileProviderTest extends TestCase {
new ObjectInputStream(new ByteArrayInputStream(byteArrayOutputStream.toByteArray())));
assertEquals(mappingProvider.toString(), newMappingProvider.toString());
} catch (IOException e) {
LOGGER.log(Level.SEVERE, e.getMessage());
logger.log(Level.SEVERE, e.getMessage());
fail();
}
}


BIN
java/lib/protobuf-javanano-3.0.0-alpha-7.jar View File


+ 0
- 54
java/lib/protobuf-javanano-readme.md View File

@ -1,54 +0,0 @@
# How to regenerate `Phonemetadata.java`
You need to re-generate
`java/libphonenumber/src/com/google/i18n/phonenumbers/nano/Phonemetadata.java` if you update
`resources/phonemetadata.proto` or the protobuf version.
Here are convenience instructions to update `Phonemetadata.java`.
Checklist:
- Are we still depending on Maven's 3.0.0-alpha-7 version of com.google.protobuf.nano
protobuf-javanano?
- Are you on a Linux x86_64 architecture? Check via the `arch` command in your terminal.
If you answered no to any question, refer instead to the full instructions, [How to update the
protobuf version](#how-to-update-the-protobuf-version).
```
mkdir /tmp/custom_protoc/ && \
cd /tmp/custom_protoc/ && \
wget https://github.com/google/protobuf/releases/download/v3.0.0-beta-4/protoc-3.0.0-beta-4-linux-x86_64.zip && \
unzip protoc-3.0.0-beta-4-linux-x86_64.zip
```
Then go to the root of your libphonenumber git repository and run:
```
/tmp/custom_protoc/bin/protoc --javanano_out=java/libphonenumber/src \
resources/phonemetadata.proto \
--proto_path=resources
```
# How to update the protobuf version
- Start by finding a protobuf library version released to Maven Central that has functionality you
need, e.g. nano. See http://mvnrepository.com/artifact/com.google.protobuf.
- Update the protobuf library dependency's `groupId`, `artifactId`, and `version` to match this
artifact in all the `pom.xml` files. You can find the files by searching for
`<groupId>com.google.protobuf` in the GitHub repository.
- Download the `.jar` from the Maven Repository,
e.g. from http://repo1.maven.org/maven2/com/google/protobuf/nano/protobuf-javanano/3.0.0-alpha-7/,
and copy to `java/lib/`, replacing the previous version's `.jar`.
- See https://github.com/google/protobuf/releases for the release containing the chosen version, and
download the `protoc` binary for your machine's architecture from the same release and use this to
re-generate `java/libphonenumber/src/com/google/i18n/phonenumbers/nano/Phonemetadata.java` and
check in any changes to this file. The command from the root directory is:
```
protoc --javanano_out=java/libphonenumber/src \
resources/phonemetadata.proto \
--proto_path=resources
```
- Update the convenience instructions, [How to regenerate `Phonemetadata.java`]
(#how-to-regenerate-phonemetadatajava).

+ 21
- 11
java/libphonenumber/pom.xml View File

@ -3,14 +3,14 @@
<modelVersion>4.0.0</modelVersion>
<groupId>com.googlecode.libphonenumber</groupId>
<artifactId>libphonenumber</artifactId>
<version>7.6.1-SNAPSHOT</version>
<version>7.7.1-SNAPSHOT</version>
<packaging>jar</packaging>
<url>https://github.com/googlei18n/libphonenumber/</url>
<parent>
<groupId>com.googlecode.libphonenumber</groupId>
<artifactId>libphonenumber-parent</artifactId>
<version>7.6.1-SNAPSHOT</version>
<version>7.7.1-SNAPSHOT</version>
</parent>
<build>
@ -29,6 +29,25 @@
</testResource>
</testResources>
<plugins>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<version>3.2.0</version>
<configuration>
<instructions>
<Export-Package>com.google.i18n.phonenumbers</Export-Package>
</instructions>
</configuration>
</plugin>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<version>3.0.2</version>
<configuration>
<archive>
<manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>animal-sniffer-maven-plugin</artifactId>
@ -52,13 +71,4 @@
</plugins>
</build>
<dependencies>
<dependency>
<groupId>com.google.protobuf.nano</groupId>
<artifactId>protobuf-javanano</artifactId>
<!-- If updating the version, see instructions in java/lib/protobuf-javanano-readme.md. -->
<version>3.0.0-alpha-7</version>
</dependency>
</dependencies>
</project>

+ 45
- 45
java/libphonenumber/src/com/google/i18n/phonenumbers/AsYouTypeFormatter.java View File

@ -16,8 +16,8 @@
package com.google.i18n.phonenumbers;
import com.google.i18n.phonenumbers.nano.Phonemetadata.NumberFormat;
import com.google.i18n.phonenumbers.nano.Phonemetadata.PhoneMetadata;
import com.google.i18n.phonenumbers.Phonemetadata.NumberFormat;
import com.google.i18n.phonenumbers.Phonemetadata.PhoneMetadata;
import java.util.ArrayList;
import java.util.Iterator;
@ -61,11 +61,8 @@ public class AsYouTypeFormatter {
// Character used when appropriate to separate a prefix, such as a long NDD or a country calling
// code, from the national number.
private static final char SEPARATOR_BEFORE_NATIONAL_NUMBER = ' ';
private static final PhoneMetadata EMPTY_METADATA;
static {
EMPTY_METADATA = new PhoneMetadata();
EMPTY_METADATA.internationalPrefix = "NA";
}
private static final PhoneMetadata EMPTY_METADATA =
new PhoneMetadata().setInternationalPrefix("NA");
private PhoneMetadata defaultMetadata;
private PhoneMetadata currentMetadata;
@ -85,8 +82,8 @@ public class AsYouTypeFormatter {
// prevents invalid punctuation (such as the star sign in Israeli star numbers) getting into the
// output of the AYTF.
private static final Pattern ELIGIBLE_FORMAT_PATTERN =
Pattern.compile("[" + PhoneNumberUtil.VALID_PUNCTUATION + "]*" +
"(\\$\\d" + "[" + PhoneNumberUtil.VALID_PUNCTUATION + "]*)+");
Pattern.compile("[" + PhoneNumberUtil.VALID_PUNCTUATION + "]*"
+ "(\\$\\d" + "[" + PhoneNumberUtil.VALID_PUNCTUATION + "]*)+");
// A set of characters that, if found in a national prefix formatting rules, are an indicator to
// us that we should separate the national prefix from the number when formatting.
private static final Pattern NATIONAL_PREFIX_SEPARATORS_PATTERN = Pattern.compile("[- ]");
@ -154,7 +151,7 @@ public class AsYouTypeFormatter {
Iterator<NumberFormat> it = possibleFormats.iterator();
while (it.hasNext()) {
NumberFormat numberFormat = it.next();
String pattern = numberFormat.pattern;
String pattern = numberFormat.getPattern();
if (currentFormattingPattern.equals(pattern)) {
return false;
}
@ -162,7 +159,7 @@ public class AsYouTypeFormatter {
currentFormattingPattern = pattern;
shouldAddSpaceAfterNationalPrefix =
NATIONAL_PREFIX_SEPARATORS_PATTERN.matcher(
numberFormat.nationalPrefixFormattingRule).find();
numberFormat.getNationalPrefixFormattingRule()).find();
// With a new formatting template, the matched position using the old template needs to be
// reset.
lastMatchPosition = 0;
@ -176,17 +173,18 @@ public class AsYouTypeFormatter {
}
private void getAvailableFormats(String leadingDigits) {
NumberFormat[] numberFormats =
(isCompleteNumber && currentMetadata.intlNumberFormat.length > 0)
? currentMetadata.intlNumberFormat
: currentMetadata.numberFormat;
boolean nationalPrefixIsUsedByCountry = (!currentMetadata.nationalPrefix.equals(""));
for (NumberFormat format : numberFormats) {
if (!nationalPrefixIsUsedByCountry || isCompleteNumber ||
format.nationalPrefixOptionalWhenFormatting ||
PhoneNumberUtil.formattingRuleHasFirstGroupOnly(
format.nationalPrefixFormattingRule)) {
if (isFormatEligible(format.format)) {
List<NumberFormat> formatList =
(isCompleteNumber && currentMetadata.intlNumberFormatSize() > 0)
? currentMetadata.intlNumberFormats()
: currentMetadata.numberFormats();
boolean nationalPrefixIsUsedByCountry = currentMetadata.hasNationalPrefix();
for (NumberFormat format : formatList) {
if (!nationalPrefixIsUsedByCountry
|| isCompleteNumber
|| format.isNationalPrefixOptionalWhenFormatting()
|| PhoneNumberUtil.formattingRuleHasFirstGroupOnly(
format.getNationalPrefixFormattingRule())) {
if (isFormatEligible(format.getFormat())) {
possibleFormats.add(format);
}
}
@ -203,14 +201,14 @@ public class AsYouTypeFormatter {
Iterator<NumberFormat> it = possibleFormats.iterator();
while (it.hasNext()) {
NumberFormat format = it.next();
if (format.leadingDigitsPattern.length == 0) {
if (format.leadingDigitsPatternSize() == 0) {
// Keep everything that isn't restricted by leading digits.
continue;
}
int lastLeadingDigitsPattern =
Math.min(indexOfLeadingDigitsPattern, format.leadingDigitsPattern.length - 1);
Math.min(indexOfLeadingDigitsPattern, format.leadingDigitsPatternSize() - 1);
Pattern leadingDigitsPattern = regexCache.getPatternForRegex(
format.leadingDigitsPattern[lastLeadingDigitsPattern]);
format.getLeadingDigitsPattern(lastLeadingDigitsPattern));
Matcher m = leadingDigitsPattern.matcher(leadingDigits);
if (!m.lookingAt()) {
it.remove();
@ -219,7 +217,7 @@ public class AsYouTypeFormatter {
}
private boolean createFormattingTemplate(NumberFormat format) {
String numberPattern = format.pattern;
String numberPattern = format.getPattern();
// The formatter doesn't format numbers when numberPattern contains "|", e.g.
// (20|3)\d{4}. In those cases we quickly return.
@ -233,7 +231,7 @@ public class AsYouTypeFormatter {
// Replace any standalone digit (not the one in d{}) with \d
numberPattern = STANDALONE_DIGIT_PATTERN.matcher(numberPattern).replaceAll("\\\\d");
formattingTemplate.setLength(0);
String tempTemplate = getFormattingTemplate(numberPattern, format.format);
String tempTemplate = getFormattingTemplate(numberPattern, format.getFormat());
if (tempTemplate.length() > 0) {
formattingTemplate.append(tempTemplate);
return true;
@ -361,6 +359,7 @@ public class AsYouTypeFormatter {
extractedNationalPrefix = removeNationalPrefixFromNationalNumber();
return attemptToChooseFormattingPattern();
}
// fall through
default:
if (isExpectingCountryCallingCode) {
if (attemptToExtractCountryCallingCode()) {
@ -420,23 +419,23 @@ public class AsYouTypeFormatter {
}
private boolean isDigitOrLeadingPlusSign(char nextChar) {
return Character.isDigit(nextChar) ||
(accruedInput.length() == 1 &&
PhoneNumberUtil.PLUS_CHARS_PATTERN.matcher(Character.toString(nextChar)).matches());
return Character.isDigit(nextChar)
|| (accruedInput.length() == 1
&& PhoneNumberUtil.PLUS_CHARS_PATTERN.matcher(Character.toString(nextChar)).matches());
}
/**
* Check to see if there is an exact pattern match for these digits. If so, we should use this
* Checks to see if there is an exact pattern match for these digits. If so, we should use this
* instead of any other formatting template whose leadingDigitsPattern also matches the input.
*/
String attemptToFormatAccruedDigits() {
for (NumberFormat numberFormat : possibleFormats) {
Matcher m = regexCache.getPatternForRegex(numberFormat.pattern).matcher(nationalNumber);
Matcher m = regexCache.getPatternForRegex(numberFormat.getPattern()).matcher(nationalNumber);
if (m.matches()) {
shouldAddSpaceAfterNationalPrefix =
NATIONAL_PREFIX_SEPARATORS_PATTERN.matcher(
numberFormat.nationalPrefixFormattingRule).find();
String formattedNumber = m.replaceAll(numberFormat.format);
numberFormat.getNationalPrefixFormattingRule()).find();
String formattedNumber = m.replaceAll(numberFormat.getFormat());
return appendNationalNumber(formattedNumber);
}
}
@ -451,10 +450,11 @@ public class AsYouTypeFormatter {
if (!ableToFormat) {
return originalPosition;
}
int accruedInputIndex = 0, currentOutputIndex = 0;
int accruedInputIndex = 0;
int currentOutputIndex = 0;
while (accruedInputIndex < positionToRemember && currentOutputIndex < currentOutput.length()) {
if (accruedInputWithoutFormatting.charAt(accruedInputIndex) ==
currentOutput.charAt(currentOutputIndex)) {
if (accruedInputWithoutFormatting.charAt(accruedInputIndex)
== currentOutput.charAt(currentOutputIndex)) {
accruedInputIndex++;
}
currentOutputIndex++;
@ -469,8 +469,8 @@ public class AsYouTypeFormatter {
*/
private String appendNationalNumber(String nationalNumber) {
int prefixBeforeNationalNumberLength = prefixBeforeNationalNumber.length();
if (shouldAddSpaceAfterNationalPrefix && prefixBeforeNationalNumberLength > 0 &&
prefixBeforeNationalNumber.charAt(prefixBeforeNationalNumberLength - 1)
if (shouldAddSpaceAfterNationalPrefix && prefixBeforeNationalNumberLength > 0
&& prefixBeforeNationalNumber.charAt(prefixBeforeNationalNumberLength - 1)
!= SEPARATOR_BEFORE_NATIONAL_NUMBER) {
// We want to add a space after the national prefix if the national prefix formatting rule
// indicates that this would normally be done, with the exception of the case where we already
@ -529,8 +529,8 @@ public class AsYouTypeFormatter {
// that national significant numbers in NANPA always start with [2-9] after the national prefix.
// Numbers beginning with 1[01] can only be short/emergency numbers, which don't need the
// national prefix.
return (currentMetadata.countryCode == 1) && (nationalNumber.charAt(0) == '1') &&
(nationalNumber.charAt(1) != '0') && (nationalNumber.charAt(1) != '1');
return (currentMetadata.getCountryCode() == 1) && (nationalNumber.charAt(0) == '1')
&& (nationalNumber.charAt(1) != '0') && (nationalNumber.charAt(1) != '1');
}
// Returns the national prefix extracted, or an empty string if it is not present.
@ -540,9 +540,9 @@ public class AsYouTypeFormatter {
startOfNationalNumber = 1;
prefixBeforeNationalNumber.append('1').append(SEPARATOR_BEFORE_NATIONAL_NUMBER);
isCompleteNumber = true;
} else if (!currentMetadata.nationalPrefixForParsing.equals("")) {
} else if (currentMetadata.hasNationalPrefixForParsing()) {
Pattern nationalPrefixForParsing =
regexCache.getPatternForRegex(currentMetadata.nationalPrefixForParsing);
regexCache.getPatternForRegex(currentMetadata.getNationalPrefixForParsing());
Matcher m = nationalPrefixForParsing.matcher(nationalNumber);
// Since some national prefix patterns are entirely optional, check that a national prefix
// could actually be extracted.
@ -569,8 +569,8 @@ public class AsYouTypeFormatter {
*/
private boolean attemptToExtractIdd() {
Pattern internationalPrefix =
regexCache.getPatternForRegex("\\" + PhoneNumberUtil.PLUS_SIGN + "|" +
currentMetadata.internationalPrefix);
regexCache.getPatternForRegex("\\" + PhoneNumberUtil.PLUS_SIGN + "|"
+ currentMetadata.getInternationalPrefix());
Matcher iddMatcher = internationalPrefix.matcher(accruedInputWithoutFormatting);
if (iddMatcher.lookingAt()) {
isCompleteNumber = true;


+ 3
- 1
java/libphonenumber/src/com/google/i18n/phonenumbers/MetadataLoader.java View File

@ -19,7 +19,9 @@ package com.google.i18n.phonenumbers;
import java.io.InputStream;
/**
* Interface for caller to specify a customized phone metadata loader.
* Interface for clients to specify a customized phone metadata loader, useful for Android apps to
* load Android resources since the library loads Java resources by default. Note that
* implementation owners have the responsibility to ensure this is thread-safe.
*/
public interface MetadataLoader {
/**


+ 13
- 43
java/libphonenumber/src/com/google/i18n/phonenumbers/MetadataManager.java View File

@ -16,11 +16,9 @@
package com.google.i18n.phonenumbers;
import com.google.i18n.phonenumbers.nano.Phonemetadata.PhoneMetadata;
import com.google.i18n.phonenumbers.nano.Phonemetadata.PhoneMetadataCollection;
import com.google.protobuf.nano.CodedInputByteBufferNano;
import com.google.i18n.phonenumbers.Phonemetadata.PhoneMetadata;
import com.google.i18n.phonenumbers.Phonemetadata.PhoneMetadataCollection;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
@ -61,39 +59,13 @@ final class MetadataManager {
private MetadataManager() {
}
// The size of the byte buffer in bytes used to convert a stream containing metadata for a single
// region, to a nanoproto-compatible CodedInputByteBufferNano. This was determined by the size of
// the binary metadata files that contain each region's metadata.
static final int DEFAULT_BUFFER_SIZE = 16 * 1024;
// The size of the byte buffer in bytes used to convert a stream containing metadata for all
// regions, to a nanoproto-compatible CodedInputByteBufferNano. This was determined by the size of
// the binary metadata file that contains all regions' metadata.
static final int ALL_REGIONS_BUFFER_SIZE = 256 * 1024;
static CodedInputByteBufferNano convertStreamToByteBuffer(ObjectInputStream in, int bufferSize)
throws IOException {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
int nRead;
byte[] data = new byte[bufferSize];
while ((nRead = in.read(data, 0, bufferSize)) != -1) {
outputStream.write(data, 0, nRead);
}
outputStream.flush();
return CodedInputByteBufferNano.newInstance(outputStream.toByteArray());
}
/**
* Loads and returns the metadata protocol buffer from the given stream and closes the stream.
* Loads and returns the metadata object from the given stream and closes the stream.
*
* @param source the non-null stream from which metadata is to be read.
* @param bufferSize the size of the buffer in bytes used to convert the stream to a
nanoproto-compatible {@code CodedInputByteBufferNano}.
* @return the loaded metadata protocol buffer.
* @param source the non-null stream from which metadata is to be read
* @return the loaded metadata object
*/
static PhoneMetadataCollection loadMetadataAndCloseInput(InputStream source, int bufferSize) {
static PhoneMetadataCollection loadMetadataAndCloseInput(InputStream source) {
ObjectInputStream ois = null;
try {
try {
@ -103,7 +75,7 @@ final class MetadataManager {
}
PhoneMetadataCollection metadataCollection = new PhoneMetadataCollection();
try {
metadataCollection.mergeFrom(convertStreamToByteBuffer(ois, bufferSize));
metadataCollection.readExternal(ois);
} catch (IOException e) {
throw new RuntimeException("cannot load/parse metadata", e);
}
@ -130,10 +102,9 @@ final class MetadataManager {
// that they are present, by checking the map of available data first.
throw new IllegalStateException("missing metadata: " + fileName);
}
PhoneMetadataCollection alternateFormatData =
loadMetadataAndCloseInput(source, DEFAULT_BUFFER_SIZE);
for (PhoneMetadata metadata : alternateFormatData.metadata) {
callingCodeToAlternateFormatsMap.put(metadata.countryCode, metadata);
PhoneMetadataCollection alternateFormats = loadMetadataAndCloseInput(source);
for (PhoneMetadata metadata : alternateFormats.getMetadataList()) {
callingCodeToAlternateFormatsMap.put(metadata.getCountryCode(), metadata);
}
}
@ -157,10 +128,9 @@ final class MetadataManager {
// that they are present, by checking the map of available data first.
throw new IllegalStateException("missing metadata: " + fileName);
}
PhoneMetadataCollection shortNumberData =
loadMetadataAndCloseInput(source, DEFAULT_BUFFER_SIZE);
for (PhoneMetadata metadata : shortNumberData.metadata) {
regionCodeToShortNumberMetadataMap.put(regionCode, metadata);
PhoneMetadataCollection shortNumberMetadata = loadMetadataAndCloseInput(source);
for (PhoneMetadata metadata : shortNumberMetadata.getMetadataList()) {
regionCodeToShortNumberMetadataMap.put(regionCode, metadata);
}
}


+ 2
- 1
java/libphonenumber/src/com/google/i18n/phonenumbers/MetadataSource.java View File

@ -16,12 +16,13 @@
package com.google.i18n.phonenumbers;
import com.google.i18n.phonenumbers.nano.Phonemetadata.PhoneMetadata;
import com.google.i18n.phonenumbers.Phonemetadata.PhoneMetadata;
/**
* A source for phone metadata for all regions.
*/
interface MetadataSource {
/**
* Gets phone metadata for a region.
* @param regionCode the region code.


+ 8
- 9
java/libphonenumber/src/com/google/i18n/phonenumbers/MultiFileMetadataSourceImpl.java View File

@ -16,12 +16,12 @@
package com.google.i18n.phonenumbers;
import com.google.i18n.phonenumbers.nano.Phonemetadata.PhoneMetadata;
import com.google.i18n.phonenumbers.nano.Phonemetadata.PhoneMetadataCollection;
import com.google.i18n.phonenumbers.Phonemetadata.PhoneMetadata;
import com.google.i18n.phonenumbers.Phonemetadata.PhoneMetadataCollection;
import java.io.InputStream;
import java.util.concurrent.ConcurrentHashMap;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
@ -116,17 +116,16 @@ final class MultiFileMetadataSourceImpl implements MetadataSource {
// that they are present, by checking the map of available data first.
throw new IllegalStateException("missing metadata: " + fileName);
}
PhoneMetadataCollection metadataCollection =
MetadataManager.loadMetadataAndCloseInput(source, MetadataManager.DEFAULT_BUFFER_SIZE);
PhoneMetadata[] metadatas = metadataCollection.metadata;
if (metadatas.length == 0) {
PhoneMetadataCollection metadataCollection = MetadataManager.loadMetadataAndCloseInput(source);
List<PhoneMetadata> metadataList = metadataCollection.getMetadataList();
if (metadataList.isEmpty()) {
// Sanity check; this should not happen since we build with non-empty metadata.
throw new IllegalStateException("empty metadata: " + fileName);
}
if (metadatas.length > 1) {
if (metadataList.size() > 1) {
logger.log(Level.WARNING, "invalid metadata (too many entries): " + fileName);
}
PhoneMetadata metadata = metadatas[0];
PhoneMetadata metadata = metadataList.get(0);
PhoneMetadata oldValue = map.putIfAbsent(key, metadata);
return (oldValue != null) ? oldValue : metadata;
}


+ 23
- 9
java/libphonenumber/src/com/google/i18n/phonenumbers/NumberParseException.java View File

@ -22,20 +22,34 @@ package com.google.i18n.phonenumbers;
@SuppressWarnings("serial")
public class NumberParseException extends Exception {
/**
* The reason that a string could not be interpreted as a phone number.
*/
public enum ErrorType {
/**
* The country code supplied did not belong to a supported country or non-geographical entity.
*/
INVALID_COUNTRY_CODE,
// This generally indicates the string passed in had less than 3 digits in it. More
// specifically, the number failed to match the regular expression VALID_PHONE_NUMBER in
// PhoneNumberUtil.java.
/**
* This generally indicates the string passed in had less than 3 digits in it. More
* specifically, the number failed to match the regular expression VALID_PHONE_NUMBER in
* PhoneNumberUtil.java.
*/
NOT_A_NUMBER,
// This indicates the string started with an international dialing prefix, but after this was
// stripped from the number, had less digits than any valid phone number (including country
// code) could have.
/**
* This indicates the string started with an international dialing prefix, but after this was
* stripped from the number, had less digits than any valid phone number (including country
* code) could have.
*/
TOO_SHORT_AFTER_IDD,
// This indicates the string, after any country code has been stripped, had less digits than any
// valid phone number could have.
/**
* This indicates the string, after any country code has been stripped, had less digits than any
* valid phone number could have.
*/
TOO_SHORT_NSN,
// This indicates the string had more digits than any valid phone number could have.
/**
* This indicates the string had more digits than any valid phone number could have.
*/
TOO_LONG,
}


+ 2
- 2
java/libphonenumber/src/com/google/i18n/phonenumbers/PhoneNumberMatch.java View File

@ -112,8 +112,8 @@ public final class PhoneNumberMatch {
return false;
}
PhoneNumberMatch other = (PhoneNumberMatch) obj;
return rawString.equals(other.rawString) && (start == other.start) &&
number.equals(other.number);
return rawString.equals(other.rawString) && (start == other.start)
&& number.equals(other.number);
}
@Override


+ 42
- 42
java/libphonenumber/src/com/google/i18n/phonenumbers/PhoneNumberMatcher.java View File

@ -19,10 +19,10 @@ package com.google.i18n.phonenumbers;
import com.google.i18n.phonenumbers.PhoneNumberUtil.Leniency;
import com.google.i18n.phonenumbers.PhoneNumberUtil.MatchType;
import com.google.i18n.phonenumbers.PhoneNumberUtil.PhoneNumberFormat;
import com.google.i18n.phonenumbers.Phonenumber.PhoneNumber;
import com.google.i18n.phonenumbers.Phonemetadata.NumberFormat;
import com.google.i18n.phonenumbers.Phonemetadata.PhoneMetadata;
import com.google.i18n.phonenumbers.Phonenumber.PhoneNumber.CountryCodeSource;
import com.google.i18n.phonenumbers.nano.Phonemetadata.NumberFormat;
import com.google.i18n.phonenumbers.nano.Phonemetadata.PhoneMetadata;
import com.google.i18n.phonenumbers.Phonenumber.PhoneNumber;
import java.lang.Character.UnicodeBlock;
import java.util.Iterator;
@ -138,10 +138,10 @@ final class PhoneNumberMatcher implements Iterator<PhoneNumberMatch> {
* closing bracket first. We limit the sets of brackets in a phone number to four.
*/
MATCHING_BRACKETS = Pattern.compile(
"(?:[" + openingParens + "])?" + "(?:" + nonParens + "+" + "[" + closingParens + "])?" +
nonParens + "+" +
"(?:[" + openingParens + "]" + nonParens + "+[" + closingParens + "])" + bracketPairLimit +
nonParens + "*");
"(?:[" + openingParens + "])?" + "(?:" + nonParens + "+" + "[" + closingParens + "])?"
+ nonParens + "+"
+ "(?:[" + openingParens + "]" + nonParens + "+[" + closingParens + "])" + bracketPairLimit
+ nonParens + "*");
/* Limit on the number of leading (plus) characters. */
String leadLimit = limit(0, 2);
@ -167,9 +167,9 @@ final class PhoneNumberMatcher implements Iterator<PhoneNumberMatch> {
/* Phone number pattern allowing optional punctuation. */
PATTERN = Pattern.compile(
"(?:" + leadClass + punctuation + ")" + leadLimit +
digitSequence + "(?:" + punctuation + digitSequence + ")" + blockLimit +
"(?:" + PhoneNumberUtil.EXTN_PATTERNS_FOR_MATCHING + ")?",
"(?:" + leadClass + punctuation + ")" + leadLimit
+ digitSequence + "(?:" + punctuation + digitSequence + ")" + blockLimit
+ "(?:" + PhoneNumberUtil.EXTN_PATTERNS_FOR_MATCHING + ")?",
PhoneNumberUtil.REGEX_FLAGS);
}
@ -211,16 +211,16 @@ final class PhoneNumberMatcher implements Iterator<PhoneNumberMatch> {
* Creates a new instance. See the factory methods in {@link PhoneNumberUtil} on how to obtain a
* new instance.
*
* @param util the phone number util to use
* @param text the character sequence that we will search, null for no text
* @param country the country to assume for phone numbers not written in international format
* (with a leading plus, or with the international dialing prefix of the
* specified region). May be null or "ZZ" if only numbers with a
* leading plus should be considered.
* @param util the phone number util to use
* @param text the character sequence that we will search, null for no text
* @param country the country to assume for phone numbers not written in international format
* (with a leading plus, or with the international dialing prefix of the specified region).
* May be null or "ZZ" if only numbers with a leading plus should be
* considered.
* @param leniency the leniency to use when evaluating candidate phone numbers
* @param maxTries the maximum number of invalid numbers to try before giving up on the text.
* This is to cover degenerate cases where the text has a lot of false positives
* in it. Must be {@code >= 0}.
* This is to cover degenerate cases where the text has a lot of false positives in it. Must
* be {@code >= 0}.
*/
PhoneNumberMatcher(PhoneNumberUtil util, CharSequence text, String country, Leniency leniency,
long maxTries) {
@ -292,12 +292,12 @@ final class PhoneNumberMatcher implements Iterator<PhoneNumberMatch> {
return false;
}
UnicodeBlock block = UnicodeBlock.of(letter);
return block.equals(UnicodeBlock.BASIC_LATIN) ||
block.equals(UnicodeBlock.LATIN_1_SUPPLEMENT) ||
block.equals(UnicodeBlock.LATIN_EXTENDED_A) ||
block.equals(UnicodeBlock.LATIN_EXTENDED_ADDITIONAL) ||
block.equals(UnicodeBlock.LATIN_EXTENDED_B) ||
block.equals(UnicodeBlock.COMBINING_DIACRITICAL_MARKS);
return block.equals(UnicodeBlock.BASIC_LATIN)
|| block.equals(UnicodeBlock.LATIN_1_SUPPLEMENT)
|| block.equals(UnicodeBlock.LATIN_EXTENDED_A)
|| block.equals(UnicodeBlock.LATIN_EXTENDED_ADDITIONAL)
|| block.equals(UnicodeBlock.LATIN_EXTENDED_B)
|| block.equals(UnicodeBlock.COMBINING_DIACRITICAL_MARKS);
}
private static boolean isInvalidPunctuationSymbol(char character) {
@ -426,9 +426,9 @@ final class PhoneNumberMatcher implements Iterator<PhoneNumberMatch> {
// TODO: Remove this or make it significantly less hacky once we've decided how to
// handle these short codes going forward in ShortNumberInfo. We could use the formatting
// rules for instance, but that would be slower.
if (phoneUtil.getRegionCodeForCountryCode(number.getCountryCode()).equals("IL") &&
phoneUtil.getNationalSignificantNumber(number).length() == 4 &&
(offset == 0 || (offset > 0 && text.charAt(offset - 1) != '*'))) {
if (phoneUtil.getRegionCodeForCountryCode(number.getCountryCode()).equals("IL")
&& phoneUtil.getNationalSignificantNumber(number).length() == 4
&& (offset == 0 || (offset > 0 && text.charAt(offset - 1) != '*'))) {
// No match.
return null;
}
@ -495,8 +495,8 @@ final class PhoneNumberMatcher implements Iterator<PhoneNumberMatch> {
// as we do not need to distinguish between different countries with the same country
// calling code and this is faster.
String region = util.getRegionCodeForCountryCode(number.getCountryCode());
if (util.getNddPrefixForRegion(region, true) != null &&
Character.isDigit(normalizedCandidate.charAt(fromIndex))) {
if (util.getNddPrefixForRegion(region, true) != null
&& Character.isDigit(normalizedCandidate.charAt(fromIndex))) {
// This means there is no formatting symbol after the NDC. In this case, we only
// accept the number if there is no formatting symbol at all in the number, except
// for extensions. This is only important for countries with national prefixes.
@ -524,8 +524,8 @@ final class PhoneNumberMatcher implements Iterator<PhoneNumberMatch> {
// First we check if the national significant number is formatted as a block.
// We use contains and not equals, since the national significant number may be present with
// a prefix such as a national number prefix, or the country code itself.
if (candidateGroups.length == 1 ||
candidateGroups[candidateNumberGroupIndex].contains(
if (candidateGroups.length == 1
|| candidateGroups[candidateNumberGroupIndex].contains(
util.getNationalSignificantNumber(number))) {
return true;
}
@ -541,8 +541,8 @@ final class PhoneNumberMatcher implements Iterator<PhoneNumberMatch> {
}
// Now check the first group. There may be a national prefix at the start, so we only check
// that the candidate group ends with the formatted number group.
return (candidateNumberGroupIndex >= 0 &&
candidateGroups[candidateNumberGroupIndex].endsWith(formattedNumberGroups[0]));
return (candidateNumberGroupIndex >= 0
&& candidateGroups[candidateNumberGroupIndex].endsWith(formattedNumberGroups[0]));
}
/**
@ -585,7 +585,7 @@ final class PhoneNumberMatcher implements Iterator<PhoneNumberMatch> {
PhoneMetadata alternateFormats =
MetadataManager.getAlternateFormatsForCountry(number.getCountryCode());
if (alternateFormats != null) {
for (NumberFormat alternateFormat : alternateFormats.numberFormat) {
for (NumberFormat alternateFormat : alternateFormats.numberFormats()) {
formattedNumberGroups = getNationalNumberGroups(util, number, alternateFormat);
if (checker.checkGroups(util, number, normalizedCandidate, formattedNumberGroups)) {
return true;
@ -610,10 +610,10 @@ final class PhoneNumberMatcher implements Iterator<PhoneNumberMatch> {
// If the first slash is after the country calling code, this is permitted.
boolean candidateHasCountryCode =
(number.getCountryCodeSource() == CountryCodeSource.FROM_NUMBER_WITH_PLUS_SIGN ||
number.getCountryCodeSource() == CountryCodeSource.FROM_NUMBER_WITHOUT_PLUS_SIGN);
if (candidateHasCountryCode &&
PhoneNumberUtil.normalizeDigitsOnly(candidate.substring(0, firstSlashInBodyIndex))
(number.getCountryCodeSource() == CountryCodeSource.FROM_NUMBER_WITH_PLUS_SIGN
|| number.getCountryCodeSource() == CountryCodeSource.FROM_NUMBER_WITHOUT_PLUS_SIGN);
if (candidateHasCountryCode
&& PhoneNumberUtil.normalizeDigitsOnly(candidate.substring(0, firstSlashInBodyIndex))
.equals(Integer.toString(number.getCountryCode()))) {
// Any more slashes and this is illegal.
return candidate.substring(secondSlashInBodyIndex + 1).contains("/");
@ -665,17 +665,17 @@ final class PhoneNumberMatcher implements Iterator<PhoneNumberMatch> {
// Check if a national prefix should be present when formatting this number.
String nationalNumber = util.getNationalSignificantNumber(number);
NumberFormat formatRule =
util.chooseFormattingPatternForNumber(metadata.numberFormat, nationalNumber);
util.chooseFormattingPatternForNumber(metadata.numberFormats(), nationalNumber);
// To do this, we check that a national prefix formatting rule was present and that it wasn't
// just the first-group symbol ($1) with punctuation.
if ((formatRule != null) && formatRule.nationalPrefixFormattingRule.length() > 0) {
if (formatRule.nationalPrefixOptionalWhenFormatting) {
if ((formatRule != null) && formatRule.getNationalPrefixFormattingRule().length() > 0) {
if (formatRule.isNationalPrefixOptionalWhenFormatting()) {
// The national-prefix is optional in these cases, so we don't need to check if it was
// present.
return true;
}
if (PhoneNumberUtil.formattingRuleHasFirstGroupOnly(
formatRule.nationalPrefixFormattingRule)) {
formatRule.getNationalPrefixFormattingRule())) {
// National Prefix not needed for this number.
return true;
}


+ 287
- 309
java/libphonenumber/src/com/google/i18n/phonenumbers/PhoneNumberUtil.java
File diff suppressed because it is too large
View File


+ 1124
- 0
java/libphonenumber/src/com/google/i18n/phonenumbers/Phonemetadata.java
File diff suppressed because it is too large
View File


+ 2
- 2
java/libphonenumber/src/com/google/i18n/phonenumbers/RegexCache.java View File

@ -41,7 +41,7 @@ public class RegexCache {
return pattern;
}
// This method is used for testing.
// @VisibleForTesting
boolean containsRegex(String regex) {
return cache.containsKey(regex);
}
@ -54,6 +54,7 @@ public class RegexCache {
@SuppressWarnings("serial")
public LRUCache(int size) {
this.size = size;
// Using access-order instead of insertion-order.
map = new LinkedHashMap<K, V>(size * 4 / 3 + 1, 0.75f, true) {
@Override
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
@ -75,4 +76,3 @@ public class RegexCache {
}
}
}

+ 29
- 29
java/libphonenumber/src/com/google/i18n/phonenumbers/ShortNumberInfo.java View File

@ -16,11 +16,11 @@
package com.google.i18n.phonenumbers;
import com.google.i18n.phonenumbers.Phonenumber.PhoneNumber;
import com.google.i18n.phonenumbers.internal.MatcherApi;
import com.google.i18n.phonenumbers.internal.RegexBasedMatcher;
import com.google.i18n.phonenumbers.nano.Phonemetadata.PhoneMetadata;
import com.google.i18n.phonenumbers.nano.Phonemetadata.PhoneNumberDesc;
import com.google.i18n.phonenumbers.Phonemetadata.PhoneMetadata;
import com.google.i18n.phonenumbers.Phonemetadata.PhoneNumberDesc;
import com.google.i18n.phonenumbers.Phonenumber.PhoneNumber;
import java.util.ArrayList;
import java.util.Arrays;
@ -61,7 +61,7 @@ public class ShortNumberInfo {
TOLL_FREE,
STANDARD_RATE,
PREMIUM_RATE,
UNKNOWN_COST
UNKNOWN_COST;
}
/** Returns the singleton instance of the ShortNumberInfo. */
@ -130,7 +130,7 @@ public class ShortNumberInfo {
if (phoneMetadata == null) {
return false;
}
return matcherApi.matchesPossibleNumber(shortNumber, phoneMetadata.generalDesc);
return matcherApi.matchesPossibleNumber(shortNumber, phoneMetadata.getGeneralDesc());
}
/**
@ -151,7 +151,7 @@ public class ShortNumberInfo {
return false;
}
return matcherApi.matchesPossibleNumber(getNationalSignificantNumber(number),
phoneMetadata.generalDesc);
phoneMetadata.getGeneralDesc());
}
/**
@ -171,7 +171,7 @@ public class ShortNumberInfo {
if (phoneMetadata == null) {
continue;
}
if (matcherApi.matchesPossibleNumber(shortNumber, phoneMetadata.generalDesc)) {
if (matcherApi.matchesPossibleNumber(shortNumber, phoneMetadata.getGeneralDesc())) {
return true;
}
}
@ -199,11 +199,11 @@ public class ShortNumberInfo {
if (phoneMetadata == null) {
return false;
}
PhoneNumberDesc generalDesc = phoneMetadata.generalDesc;
PhoneNumberDesc generalDesc = phoneMetadata.getGeneralDesc();
if (!matchesPossibleNumberAndNationalNumber(shortNumber, generalDesc)) {
return false;
}
PhoneNumberDesc shortNumberDesc = phoneMetadata.shortCode;
PhoneNumberDesc shortNumberDesc = phoneMetadata.getShortCode();
return matchesPossibleNumberAndNationalNumber(shortNumber, shortNumberDesc);
}
@ -226,11 +226,11 @@ public class ShortNumberInfo {
return false;
}
String shortNumber = getNationalSignificantNumber(number);
PhoneNumberDesc generalDesc = phoneMetadata.generalDesc;
PhoneNumberDesc generalDesc = phoneMetadata.getGeneralDesc();
if (!matchesPossibleNumberAndNationalNumber(shortNumber, generalDesc)) {
return false;
}
PhoneNumberDesc shortNumberDesc = phoneMetadata.shortCode;
PhoneNumberDesc shortNumberDesc = phoneMetadata.getShortCode();
return matchesPossibleNumberAndNationalNumber(shortNumber, shortNumberDesc);
}
@ -292,13 +292,13 @@ public class ShortNumberInfo {
// The cost categories are tested in order of decreasing expense, since if for some reason the
// patterns overlap the most expensive matching cost category should be returned.
if (matchesPossibleNumberAndNationalNumber(shortNumber, phoneMetadata.premiumRate)) {
if (matchesPossibleNumberAndNationalNumber(shortNumber, phoneMetadata.getPremiumRate())) {
return ShortNumberCost.PREMIUM_RATE;
}
if (matchesPossibleNumberAndNationalNumber(shortNumber, phoneMetadata.standardRate)) {
if (matchesPossibleNumberAndNationalNumber(shortNumber, phoneMetadata.getStandardRate())) {
return ShortNumberCost.STANDARD_RATE;
}
if (matchesPossibleNumberAndNationalNumber(shortNumber, phoneMetadata.tollFree)) {
if (matchesPossibleNumberAndNationalNumber(shortNumber, phoneMetadata.getTollFree())) {
return ShortNumberCost.TOLL_FREE;
}
if (isEmergencyNumber(shortNumber, regionDialingFrom)) {
@ -346,13 +346,13 @@ public class ShortNumberInfo {
// The cost categories are tested in order of decreasing expense, since if for some reason the
// patterns overlap the most expensive matching cost category should be returned.
if (matchesPossibleNumberAndNationalNumber(shortNumber, phoneMetadata.premiumRate)) {
if (matchesPossibleNumberAndNationalNumber(shortNumber, phoneMetadata.getPremiumRate())) {
return ShortNumberCost.PREMIUM_RATE;
}
if (matchesPossibleNumberAndNationalNumber(shortNumber, phoneMetadata.standardRate)) {
if (matchesPossibleNumberAndNationalNumber(shortNumber, phoneMetadata.getStandardRate())) {
return ShortNumberCost.STANDARD_RATE;
}
if (matchesPossibleNumberAndNationalNumber(shortNumber, phoneMetadata.tollFree)) {
if (matchesPossibleNumberAndNationalNumber(shortNumber, phoneMetadata.getTollFree())) {
return ShortNumberCost.TOLL_FREE;
}
if (isEmergencyNumber(shortNumber, regionDialingFrom)) {
@ -429,7 +429,7 @@ public class ShortNumberInfo {
for (String regionCode : regionCodes) {
PhoneMetadata phoneMetadata = MetadataManager.getShortNumberMetadataForRegion(regionCode);
if (phoneMetadata != null
&& matchesPossibleNumberAndNationalNumber(nationalNumber, phoneMetadata.shortCode)) {
&& matchesPossibleNumberAndNationalNumber(nationalNumber, phoneMetadata.getShortCode())) {
// The number is valid for this region.
return regionCode;
}
@ -457,9 +457,9 @@ public class ShortNumberInfo {
if (phoneMetadata == null) {
return "";
}
PhoneNumberDesc desc = phoneMetadata.shortCode;
if (!desc.exampleNumber.equals("")) {
return desc.exampleNumber;
PhoneNumberDesc desc = phoneMetadata.getShortCode();
if (desc.hasExampleNumber()) {
return desc.getExampleNumber();
}
return "";
}
@ -481,20 +481,20 @@ public class ShortNumberInfo {
PhoneNumberDesc desc = null;
switch (cost) {
case TOLL_FREE:
desc = phoneMetadata.tollFree;
desc = phoneMetadata.getTollFree();
break;
case STANDARD_RATE:
desc = phoneMetadata.standardRate;
desc = phoneMetadata.getStandardRate();
break;
case PREMIUM_RATE:
desc = phoneMetadata.premiumRate;
desc = phoneMetadata.getPremiumRate();
break;
default:
// UNKNOWN_COST numbers are computed by the process of elimination from the other cost
// categories.
}
if (desc != null && !desc.exampleNumber.equals("")) {
return desc.exampleNumber;
if (desc != null && desc.hasExampleNumber()) {
return desc.getExampleNumber();
}
return "";
}
@ -543,12 +543,12 @@ public class ShortNumberInfo {
return false;
}
PhoneMetadata metadata = MetadataManager.getShortNumberMetadataForRegion(regionCode);
if (metadata == null || metadata.emergency == null) {
if (metadata == null || !metadata.hasEmergency()) {
return false;
}
String normalizedNumber = PhoneNumberUtil.normalizeDigitsOnly(number);
PhoneNumberDesc emergencyDesc = metadata.emergency;
PhoneNumberDesc emergencyDesc = metadata.getEmergency();
boolean allowPrefixMatchForRegion =
allowPrefixMatch && !REGIONS_WHERE_EMERGENCY_NUMBERS_MUST_BE_EXACT.contains(regionCode);
return matcherApi.matchesNationalNumber(normalizedNumber, emergencyDesc,
@ -572,7 +572,7 @@ public class ShortNumberInfo {
PhoneMetadata phoneMetadata = MetadataManager.getShortNumberMetadataForRegion(regionCode);
return (phoneMetadata != null)
&& (matchesPossibleNumberAndNationalNumber(nationalNumber,
phoneMetadata.carrierSpecific));
phoneMetadata.getCarrierSpecific()));
}
/**


+ 8
- 9
java/libphonenumber/src/com/google/i18n/phonenumbers/SingleFileMetadataSourceImpl.java View File

@ -16,8 +16,8 @@
package com.google.i18n.phonenumbers;
import com.google.i18n.phonenumbers.nano.Phonemetadata.PhoneMetadata;
import com.google.i18n.phonenumbers.nano.Phonemetadata.PhoneMetadataCollection;
import com.google.i18n.phonenumbers.Phonemetadata.PhoneMetadata;
import com.google.i18n.phonenumbers.Phonemetadata.PhoneMetadataCollection;
import java.io.InputStream;
import java.util.Collections;
@ -101,16 +101,15 @@ final class SingleFileMetadataSourceImpl implements MetadataSource {
// loading depending on what data is available in the jar.
throw new IllegalStateException("missing metadata: " + fileName);
}
PhoneMetadataCollection metadataCollection =
MetadataManager.loadMetadataAndCloseInput(source, MetadataManager.ALL_REGIONS_BUFFER_SIZE);
PhoneMetadata[] metadatas = metadataCollection.metadata;
if (metadatas.length == 0) {
PhoneMetadataCollection metadataCollection = MetadataManager.loadMetadataAndCloseInput(source);
List<PhoneMetadata> metadataList = metadataCollection.getMetadataList();
if (metadataList.isEmpty()) {
// This should not happen since clients shouldn't be using this implementation!
throw new IllegalStateException("empty metadata: " + fileName);
}
for (PhoneMetadata metadata : metadatas) {
String regionCode = metadata.id;
int countryCallingCode = metadata.countryCode;
for (PhoneMetadata metadata : metadataList) {
String regionCode = metadata.getId();
int countryCallingCode = metadata.getCountryCode();
boolean isNonGeoRegion = PhoneNumberUtil.REGION_CODE_FOR_NON_GEO_ENTITY.equals(regionCode);
if (isNonGeoRegion) {
countryCodeToNonGeographicalMetadataMap.put(countryCallingCode, metadata);


BIN
java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_255 View File


BIN
java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_27 View File


BIN
java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_30 View File


BIN
java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_31 View File


BIN
java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_34 View File


BIN
java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_350 View File


BIN
java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_351 View File


BIN
java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_352 View File


BIN
java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_358 View File


BIN
java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_359 View File


BIN
java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_36 View File


BIN
java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_372 View File


BIN
java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_373 View File


BIN
java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_380 View File


BIN
java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_381 View File


BIN
java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_385 View File


BIN
java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_43 View File


BIN
java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_44 View File


BIN
java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_49 View File


BIN
java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_505 View File


BIN
java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_506 View File


BIN
java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_54 View File


BIN
java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_55 View File


BIN
java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_58 View File


BIN
java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_595 View File


BIN
java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_61 View File


BIN
java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_62 View File


BIN
java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_63 View File


BIN
java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_66 View File


BIN
java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_675 View File


BIN
java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_676 View File


BIN
java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_679 View File


BIN
java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_7 View File


BIN
java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_81 View File


BIN
java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_84 View File


BIN
java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_855 View File


BIN
java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_90 View File


BIN
java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_91 View File


BIN
java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_94 View File


BIN
java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_95 View File


BIN
java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_971 View File


BIN
java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_972 View File


BIN
java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberAlternateFormatsProto_995 View File


BIN
java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberMetadataProto_800 View File


BIN
java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberMetadataProto_808 View File


BIN
java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberMetadataProto_870 View File


BIN
java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberMetadataProto_878 View File


BIN
java/libphonenumber/src/com/google/i18n/phonenumbers/data/PhoneNumberMetadataProto_881 View File


Some files were not shown because too many files changed in this diff

Loading…
Cancel
Save