Browse Source

JAVA: Replacing uses of StringBuffer with StringBuilder. Fixes issue 29.

pull/567/head
kushalp 15 years ago
committed by Mihaela Rosca
parent
commit
d31318b4d8
6 changed files with 67 additions and 67 deletions
  1. +5
    -5
      java/demo/src/com/google/phonenumbers/PhoneNumberParserServlet.java
  2. +6
    -6
      java/src/com/google/i18n/phonenumbers/AsYouTypeFormatter.java
  3. +33
    -33
      java/src/com/google/i18n/phonenumbers/PhoneNumberUtil.java
  4. +1
    -1
      java/src/com/google/i18n/phonenumbers/Phonenumber.java
  5. +1
    -1
      java/test/com/google/i18n/phonenumbers/PhoneNumberMatcherTest.java
  6. +21
    -21
      java/test/com/google/i18n/phonenumbers/PhoneNumberUtilTest.java

+ 5
- 5
java/demo/src/com/google/phonenumbers/PhoneNumberParserServlet.java View File

@ -77,7 +77,7 @@ public class PhoneNumberParserServlet extends HttpServlet {
e1.printStackTrace(); e1.printStackTrace();
} }
StringBuffer output;
StringBuilder output;
if (fileContents.length() == 0) { if (fileContents.length() == 0) {
output = getOutputForSingleNumber(phoneNumber, defaultCountry); output = getOutputForSingleNumber(phoneNumber, defaultCountry);
resp.setContentType("text/plain"); resp.setContentType("text/plain");
@ -90,8 +90,8 @@ public class PhoneNumberParserServlet extends HttpServlet {
resp.getWriter().println(output); resp.getWriter().println(output);
} }
private StringBuffer getOutputForFile(String defaultCountry, String fileContents) {
StringBuffer output = new StringBuffer();
private StringBuilder getOutputForFile(String defaultCountry, String fileContents) {
StringBuilder output = new StringBuilder();
output.append("<HTML><HEAD><TITLE>Results generated from phone numbers in the file provided:" output.append("<HTML><HEAD><TITLE>Results generated from phone numbers in the file provided:"
+ "</TITLE></HEAD><BODY>"); + "</TITLE></HEAD><BODY>");
output.append("<TABLE align=center border=1>"); output.append("<TABLE align=center border=1>");
@ -129,8 +129,8 @@ public class PhoneNumberParserServlet extends HttpServlet {
return output; return output;
} }
private StringBuffer getOutputForSingleNumber(String phoneNumber, String defaultCountry) {
StringBuffer output = new StringBuffer();
private StringBuilder getOutputForSingleNumber(String phoneNumber, String defaultCountry) {
StringBuilder output = new StringBuilder();
try { try {
PhoneNumber number = phoneUtil.parseAndKeepRawInput(phoneNumber, defaultCountry); PhoneNumber number = phoneUtil.parseAndKeepRawInput(phoneNumber, defaultCountry);
output.append("\n\n****Parsing Result:****"); output.append("\n\n****Parsing Result:****");


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

@ -40,11 +40,11 @@ import java.util.regex.Pattern;
*/ */
public class AsYouTypeFormatter { public class AsYouTypeFormatter {
private String currentOutput = ""; private String currentOutput = "";
private StringBuffer formattingTemplate = new StringBuffer();
private StringBuilder formattingTemplate = new StringBuilder();
// The pattern from numberFormat that is currently used to create formattingTemplate. // The pattern from numberFormat that is currently used to create formattingTemplate.
private String currentFormattingPattern = ""; private String currentFormattingPattern = "";
private StringBuffer accruedInput = new StringBuffer();
private StringBuffer accruedInputWithoutFormatting = new StringBuffer();
private StringBuilder accruedInput = new StringBuilder();
private StringBuilder accruedInputWithoutFormatting = new StringBuilder();
private boolean ableToFormat = true; private boolean ableToFormat = true;
private boolean isInternationalFormatting = false; private boolean isInternationalFormatting = false;
private boolean isExpectingCountryCallingCode = false; private boolean isExpectingCountryCallingCode = false;
@ -91,8 +91,8 @@ public class AsYouTypeFormatter {
// The position of a digit upon which inputDigitAndRememberPosition is most recently invoked, as // The position of a digit upon which inputDigitAndRememberPosition is most recently invoked, as
// found in accruedInputWithoutFormatting. // found in accruedInputWithoutFormatting.
private int positionToRemember = 0; private int positionToRemember = 0;
private StringBuffer prefixBeforeNationalNumber = new StringBuffer();
private StringBuffer nationalNumber = new StringBuffer();
private StringBuilder prefixBeforeNationalNumber = new StringBuilder();
private StringBuilder nationalNumber = new StringBuilder();
private List<NumberFormat> possibleFormats = new ArrayList<NumberFormat>(); private List<NumberFormat> possibleFormats = new ArrayList<NumberFormat>();
// A cache for frequently used country-specific regular expressions. // A cache for frequently used country-specific regular expressions.
@ -449,7 +449,7 @@ public class AsYouTypeFormatter {
if (nationalNumber.length() == 0) { if (nationalNumber.length() == 0) {
return false; return false;
} }
StringBuffer numberWithoutCountryCallingCode = new StringBuffer();
StringBuilder numberWithoutCountryCallingCode = new StringBuilder();
int countryCode = phoneUtil.extractCountryCode(nationalNumber, numberWithoutCountryCallingCode); int countryCode = phoneUtil.extractCountryCode(nationalNumber, numberWithoutCountryCallingCode);
if (countryCode == 0) { if (countryCode == 0) {
return false; return false;


+ 33
- 33
java/src/com/google/i18n/phonenumbers/PhoneNumberUtil.java View File

@ -544,12 +544,12 @@ public class PhoneNumberUtil {
/** /**
* Normalizes a string of characters representing a phone number. This is a wrapper for * Normalizes a string of characters representing a phone number. This is a wrapper for
* normalize(String number) but does in-place normalization of the StringBuffer provided.
* normalize(String number) but does in-place normalization of the StringBuilder provided.
* *
* @param number a StringBuffer of characters representing a phone number that will be normalized
* in place
* @param number a StringBuilder of characters representing a phone number that will be
* normalized in place
*/ */
static void normalize(StringBuffer number) {
static void normalize(StringBuilder number) {
String normalizedNumber = normalize(number.toString()); String normalizedNumber = normalize(number.toString());
number.replace(0, number.length(), normalizedNumber); number.replace(0, number.length(), normalizedNumber);
} }
@ -713,7 +713,7 @@ public class PhoneNumberUtil {
private static String normalizeHelper(String number, private static String normalizeHelper(String number,
Map<Character, Character> normalizationReplacements, Map<Character, Character> normalizationReplacements,
boolean removeNonMatches) { boolean removeNonMatches) {
StringBuffer normalizedNumber = new StringBuffer(number.length());
StringBuilder normalizedNumber = new StringBuilder(number.length());
char[] numberAsCharArray = number.toCharArray(); char[] numberAsCharArray = number.toCharArray();
for (char character : numberAsCharArray) { for (char character : numberAsCharArray) {
Character newDigit = normalizationReplacements.get(Character.toUpperCase(character)); Character newDigit = normalizationReplacements.get(Character.toUpperCase(character));
@ -808,16 +808,16 @@ public class PhoneNumberUtil {
* @return the formatted phone number * @return the formatted phone number
*/ */
public String format(PhoneNumber number, PhoneNumberFormat numberFormat) { public String format(PhoneNumber number, PhoneNumberFormat numberFormat) {
StringBuffer formattedNumber = new StringBuffer(20);
StringBuilder formattedNumber = new StringBuilder(20);
format(number, numberFormat, formattedNumber); format(number, numberFormat, formattedNumber);
return formattedNumber.toString(); return formattedNumber.toString();
} }
// Same as format(PhoneNumber, PhoneNumberFormat), but accepts mutable StringBuffer as parameters
// Same as format(PhoneNumber, PhoneNumberFormat), but accepts mutable StringBuilder as parameters
// to decrease object creation when invoked many times. // to decrease object creation when invoked many times.
public void format(PhoneNumber number, PhoneNumberFormat numberFormat, public void format(PhoneNumber number, PhoneNumberFormat numberFormat,
StringBuffer formattedNumber) {
// Clear the StringBuffer first.
StringBuilder formattedNumber) {
// Clear the StringBuilder first.
formattedNumber.setLength(0); formattedNumber.setLength(0);
int countryCode = number.getCountryCode(); int countryCode = number.getCountryCode();
String nationalSignificantNumber = getNationalSignificantNumber(number); String nationalSignificantNumber = getNationalSignificantNumber(number);
@ -895,10 +895,10 @@ public class PhoneNumberUtil {
} }
} }
StringBuffer formattedNumber =
new StringBuffer(formatAccordingToFormats(nationalSignificantNumber,
userDefinedFormatsCopy,
numberFormat));
StringBuilder formattedNumber =
new StringBuilder(formatAccordingToFormats(nationalSignificantNumber,
userDefinedFormatsCopy,
numberFormat));
maybeGetFormattedExtension(number, regionCode, numberFormat, formattedNumber); maybeGetFormattedExtension(number, regionCode, numberFormat, formattedNumber);
formatNumberByFormat(countryCallingCode, numberFormat, formattedNumber); formatNumberByFormat(countryCallingCode, numberFormat, formattedNumber);
return formattedNumber.toString(); return formattedNumber.toString();
@ -926,7 +926,7 @@ public class PhoneNumberUtil {
return nationalSignificantNumber; return nationalSignificantNumber;
} }
StringBuffer formattedNumber = new StringBuffer(20);
StringBuilder formattedNumber = new StringBuilder(20);
formattedNumber.append(formatNationalNumber(nationalSignificantNumber, formattedNumber.append(formatNationalNumber(nationalSignificantNumber,
regionCode, regionCode,
PhoneNumberFormat.NATIONAL, PhoneNumberFormat.NATIONAL,
@ -1018,7 +1018,7 @@ public class PhoneNumberUtil {
internationalPrefixForFormatting = metadata.getPreferredInternationalPrefix(); internationalPrefixForFormatting = metadata.getPreferredInternationalPrefix();
} }
StringBuffer formattedNumber = new StringBuffer(formattedNationalNumber);
StringBuilder formattedNumber = new StringBuilder(formattedNationalNumber);
maybeGetFormattedExtension(number, regionCode, PhoneNumberFormat.INTERNATIONAL, maybeGetFormattedExtension(number, regionCode, PhoneNumberFormat.INTERNATIONAL,
formattedNumber); formattedNumber);
if (internationalPrefixForFormatting.length() > 0) { if (internationalPrefixForFormatting.length() > 0) {
@ -1145,7 +1145,7 @@ public class PhoneNumberUtil {
UNIQUE_INTERNATIONAL_PREFIX.matcher(internationalPrefix).matches() UNIQUE_INTERNATIONAL_PREFIX.matcher(internationalPrefix).matches()
? internationalPrefix ? internationalPrefix
: metadata.getPreferredInternationalPrefix(); : metadata.getPreferredInternationalPrefix();
StringBuffer formattedNumber = new StringBuffer(rawInput);
StringBuilder formattedNumber = new StringBuilder(rawInput);
maybeGetFormattedExtension(number, regionCode, PhoneNumberFormat.INTERNATIONAL, maybeGetFormattedExtension(number, regionCode, PhoneNumberFormat.INTERNATIONAL,
formattedNumber); formattedNumber);
if (internationalPrefixForFormatting.length() > 0) { if (internationalPrefixForFormatting.length() > 0) {
@ -1173,7 +1173,7 @@ public class PhoneNumberUtil {
// December 2000, but it has not yet happened. // December 2000, but it has not yet happened.
// See http://en.wikipedia.org/wiki/%2B39 for more details. // See http://en.wikipedia.org/wiki/%2B39 for more details.
// Other regions such as Cote d'Ivoire and Gabon use this for their mobile numbers. // Other regions such as Cote d'Ivoire and Gabon use this for their mobile numbers.
StringBuffer nationalNumber = new StringBuffer(
StringBuilder nationalNumber = new StringBuilder(
(number.hasItalianLeadingZero() && (number.hasItalianLeadingZero() &&
number.getItalianLeadingZero() && number.getItalianLeadingZero() &&
isLeadingZeroPossible(number.getCountryCode())) isLeadingZeroPossible(number.getCountryCode()))
@ -1188,7 +1188,7 @@ public class PhoneNumberUtil {
*/ */
private void formatNumberByFormat(int countryCallingCode, private void formatNumberByFormat(int countryCallingCode,
PhoneNumberFormat numberFormat, PhoneNumberFormat numberFormat,
StringBuffer formattedNumber) {
StringBuilder formattedNumber) {
switch (numberFormat) { switch (numberFormat) {
case E164: case E164:
formattedNumber.insert(0, countryCallingCode).insert(0, PLUS_SIGN); formattedNumber.insert(0, countryCallingCode).insert(0, PLUS_SIGN);
@ -1329,7 +1329,7 @@ public class PhoneNumberUtil {
*/ */
private void maybeGetFormattedExtension(PhoneNumber number, String regionCode, private void maybeGetFormattedExtension(PhoneNumber number, String regionCode,
PhoneNumberFormat numberFormat, PhoneNumberFormat numberFormat,
StringBuffer formattedNumber) {
StringBuilder formattedNumber) {
if (number.hasExtension() && number.getExtension().length() > 0) { if (number.hasExtension() && number.getExtension().length() > 0) {
if (numberFormat == PhoneNumberFormat.RFC3966) { if (numberFormat == PhoneNumberFormat.RFC3966) {
formattedNumber.append(RFC3966_EXTN_PREFIX).append(number.getExtension()); formattedNumber.append(RFC3966_EXTN_PREFIX).append(number.getExtension());
@ -1344,7 +1344,7 @@ public class PhoneNumberUtil {
* prefix. This will be the default extension prefix, unless overridden by a preferred * prefix. This will be the default extension prefix, unless overridden by a preferred
* extension prefix for this region. * extension prefix for this region.
*/ */
private void formatExtension(String extensionDigits, String regionCode, StringBuffer extension) {
private void formatExtension(String extensionDigits, String regionCode, StringBuilder extension) {
PhoneMetadata metadata = getMetadataForRegion(regionCode); PhoneMetadata metadata = getMetadataForRegion(regionCode);
if (metadata.hasPreferredExtnPrefix()) { if (metadata.hasPreferredExtnPrefix()) {
extension.append(metadata.getPreferredExtnPrefix()).append(extensionDigits); extension.append(metadata.getPreferredExtnPrefix()).append(extensionDigits);
@ -1649,7 +1649,7 @@ public class PhoneNumberUtil {
// Number is too short, or doesn't match the basic phone number pattern. // Number is too short, or doesn't match the basic phone number pattern.
return false; return false;
} }
StringBuffer strippedNumber = new StringBuffer(number);
StringBuilder strippedNumber = new StringBuilder(number);
maybeStripExtension(strippedNumber); maybeStripExtension(strippedNumber);
return VALID_ALPHA_PHONE_PATTERN.matcher(strippedNumber).matches(); return VALID_ALPHA_PHONE_PATTERN.matcher(strippedNumber).matches();
} }
@ -1803,7 +1803,7 @@ public class PhoneNumberUtil {
// nationalNumber. It assumes that the leading plus sign or IDD has already been removed. Returns // nationalNumber. It assumes that the leading plus sign or IDD has already been removed. Returns
// 0 if fullNumber doesn't start with a valid country calling code, and leaves nationalNumber // 0 if fullNumber doesn't start with a valid country calling code, and leaves nationalNumber
// unmodified. // unmodified.
int extractCountryCode(StringBuffer fullNumber, StringBuffer nationalNumber) {
int extractCountryCode(StringBuilder fullNumber, StringBuilder nationalNumber) {
int potentialCountryCode; int potentialCountryCode;
int numberLength = fullNumber.length(); int numberLength = fullNumber.length();
for (int i = 1; i <= MAX_LENGTH_COUNTRY_CODE && i <= numberLength; i++) { for (int i = 1; i <= MAX_LENGTH_COUNTRY_CODE && i <= numberLength; i++) {
@ -1848,13 +1848,13 @@ public class PhoneNumberUtil {
* @return the country calling code extracted or 0 if none could be extracted * @return the country calling code extracted or 0 if none could be extracted
*/ */
int maybeExtractCountryCode(String number, PhoneMetadata defaultRegionMetadata, int maybeExtractCountryCode(String number, PhoneMetadata defaultRegionMetadata,
StringBuffer nationalNumber, boolean keepRawInput,
StringBuilder nationalNumber, boolean keepRawInput,
PhoneNumber phoneNumber) PhoneNumber phoneNumber)
throws NumberParseException { throws NumberParseException {
if (number.length() == 0) { if (number.length() == 0) {
return 0; return 0;
} }
StringBuffer fullNumber = new StringBuffer(number);
StringBuilder fullNumber = new StringBuilder(number);
// Set the default prefix to be something that will never match. // Set the default prefix to be something that will never match.
String possibleCountryIddPrefix = "NonMatch"; String possibleCountryIddPrefix = "NonMatch";
if (defaultRegionMetadata != null) { if (defaultRegionMetadata != null) {
@ -1890,8 +1890,8 @@ public class PhoneNumberUtil {
String defaultCountryCodeString = String.valueOf(defaultCountryCode); String defaultCountryCodeString = String.valueOf(defaultCountryCode);
String normalizedNumber = fullNumber.toString(); String normalizedNumber = fullNumber.toString();
if (normalizedNumber.startsWith(defaultCountryCodeString)) { if (normalizedNumber.startsWith(defaultCountryCodeString)) {
StringBuffer potentialNationalNumber =
new StringBuffer(normalizedNumber.substring(defaultCountryCodeString.length()));
StringBuilder potentialNationalNumber =
new StringBuilder(normalizedNumber.substring(defaultCountryCodeString.length()));
PhoneNumberDesc generalDesc = defaultRegionMetadata.getGeneralDesc(); PhoneNumberDesc generalDesc = defaultRegionMetadata.getGeneralDesc();
Pattern validNumberPattern = Pattern validNumberPattern =
regexCache.getPatternForRegex(generalDesc.getNationalNumberPattern()); regexCache.getPatternForRegex(generalDesc.getNationalNumberPattern());
@ -1923,7 +1923,7 @@ public class PhoneNumberUtil {
* Strips the IDD from the start of the number if present. Helper function used by * Strips the IDD from the start of the number if present. Helper function used by
* maybeStripInternationalPrefixAndNormalize. * maybeStripInternationalPrefixAndNormalize.
*/ */
private boolean parsePrefixAsIdd(Pattern iddPattern, StringBuffer number) {
private boolean parsePrefixAsIdd(Pattern iddPattern, StringBuilder number) {
Matcher m = iddPattern.matcher(number); Matcher m = iddPattern.matcher(number);
if (m.lookingAt()) { if (m.lookingAt()) {
int matchEnd = m.end(); int matchEnd = m.end();
@ -1955,7 +1955,7 @@ public class PhoneNumberUtil {
* not seem to be in international format. * not seem to be in international format.
*/ */
CountryCodeSource maybeStripInternationalPrefixAndNormalize( CountryCodeSource maybeStripInternationalPrefixAndNormalize(
StringBuffer number,
StringBuilder number,
String possibleIddPrefix) { String possibleIddPrefix) {
if (number.length() == 0) { if (number.length() == 0) {
return CountryCodeSource.FROM_DEFAULT_COUNTRY; return CountryCodeSource.FROM_DEFAULT_COUNTRY;
@ -1991,7 +1991,7 @@ public class PhoneNumberUtil {
* @param metadata the metadata for the region that we think this number is from * @param metadata the metadata for the region that we think this number is from
* @return the carrier code extracted if it is present, otherwise return an empty string. * @return the carrier code extracted if it is present, otherwise return an empty string.
*/ */
String maybeStripNationalPrefixAndCarrierCode(StringBuffer number, PhoneMetadata metadata) {
String maybeStripNationalPrefixAndCarrierCode(StringBuilder number, PhoneMetadata metadata) {
String carrierCode = ""; String carrierCode = "";
int numberLength = number.length(); int numberLength = number.length();
String possibleNationalPrefix = metadata.getNationalPrefixForParsing(); String possibleNationalPrefix = metadata.getNationalPrefixForParsing();
@ -2023,7 +2023,7 @@ public class PhoneNumberUtil {
} else { } else {
// Check that the resultant number is viable. If not, return. Check this by copying the // Check that the resultant number is viable. If not, return. Check this by copying the
// string buffer and making the transformation on the copy first. // string buffer and making the transformation on the copy first.
StringBuffer transformedNumber = new StringBuffer(number);
StringBuilder transformedNumber = new StringBuilder(number);
transformedNumber.replace(0, numberLength, prefixMatcher.replaceFirst(transformRule)); transformedNumber.replace(0, numberLength, prefixMatcher.replaceFirst(transformRule));
Matcher nationalNumber = nationalNumberRule.matcher(transformedNumber.toString()); Matcher nationalNumber = nationalNumberRule.matcher(transformedNumber.toString());
if (!nationalNumber.matches()) { if (!nationalNumber.matches()) {
@ -2045,7 +2045,7 @@ public class PhoneNumberUtil {
* @param number the non-normalized telephone number that we wish to strip the extension from * @param number the non-normalized telephone number that we wish to strip the extension from
* @return the phone extension * @return the phone extension
*/ */
String maybeStripExtension(StringBuffer number) {
String maybeStripExtension(StringBuilder number) {
Matcher m = EXTN_PATTERN.matcher(number); Matcher m = EXTN_PATTERN.matcher(number);
// If we find a potential extension, and the number preceding this is a viable number, we assume // If we find a potential extension, and the number preceding this is a viable number, we assume
// it is an extension. // it is an extension.
@ -2220,7 +2220,7 @@ public class PhoneNumberUtil {
if (keepRawInput) { if (keepRawInput) {
phoneNumber.setRawInput(numberToParse); phoneNumber.setRawInput(numberToParse);
} }
StringBuffer nationalNumber = new StringBuffer(number);
StringBuilder nationalNumber = new StringBuilder(number);
// Attempt to parse extension first, since it doesn't require region-specific data and we want // Attempt to parse extension first, since it doesn't require region-specific data and we want
// to have the non-normalised number here. // to have the non-normalised number here.
String extension = maybeStripExtension(nationalNumber); String extension = maybeStripExtension(nationalNumber);
@ -2231,7 +2231,7 @@ public class PhoneNumberUtil {
PhoneMetadata regionMetadata = getMetadataForRegion(defaultRegion); PhoneMetadata regionMetadata = getMetadataForRegion(defaultRegion);
// Check to see if the number is given in international format so we know whether this number is // Check to see if the number is given in international format so we know whether this number is
// from the default region or not. // from the default region or not.
StringBuffer normalizedNationalNumber = new StringBuffer();
StringBuilder normalizedNationalNumber = new StringBuilder();
int countryCode = maybeExtractCountryCode(nationalNumber.toString(), regionMetadata, int countryCode = maybeExtractCountryCode(nationalNumber.toString(), regionMetadata,
normalizedNationalNumber, keepRawInput, phoneNumber); normalizedNationalNumber, keepRawInput, phoneNumber);
if (countryCode != 0) { if (countryCode != 0) {


+ 1
- 1
java/src/com/google/i18n/phonenumbers/Phonenumber.java View File

@ -235,7 +235,7 @@ public final class Phonenumber {
@Override @Override
public String toString() { public String toString() {
StringBuffer outputString = new StringBuffer();
StringBuilder outputString = new StringBuilder();
outputString.append("Country Code: ").append(countryCode_); outputString.append("Country Code: ").append(countryCode_);
outputString.append(" National Number: ").append(nationalNumber_); outputString.append(" National Number: ").append(nationalNumber_);
if (hasItalianLeadingZero() && getItalianLeadingZero()) { if (hasItalianLeadingZero() && getItalianLeadingZero()) {


+ 1
- 1
java/test/com/google/i18n/phonenumbers/PhoneNumberMatcherTest.java View File

@ -543,7 +543,7 @@ public class PhoneNumberMatcherTest extends TestCase {
private void ensureTermination(String text, String defaultCountry, Leniency leniency) { private void ensureTermination(String text, String defaultCountry, Leniency leniency) {
for (int index = 0; index <= text.length(); index++) { for (int index = 0; index <= text.length(); index++) {
String sub = text.substring(index); String sub = text.substring(index);
StringBuffer matches = new StringBuffer();
StringBuilder matches = new StringBuilder();
// Iterates over all matches. // Iterates over all matches.
for (PhoneNumberMatch match : for (PhoneNumberMatch match :
phoneUtil.findNumbers(sub, defaultCountry, leniency, Long.MAX_VALUE)) { phoneUtil.findNumbers(sub, defaultCountry, leniency, Long.MAX_VALUE)) {


+ 21
- 21
java/test/com/google/i18n/phonenumbers/PhoneNumberUtilTest.java View File

@ -1042,7 +1042,7 @@ public class PhoneNumberUtilTest extends TestCase {
PhoneMetadata metadata = new PhoneMetadata(); PhoneMetadata metadata = new PhoneMetadata();
metadata.setNationalPrefixForParsing("34"); metadata.setNationalPrefixForParsing("34");
metadata.setGeneralDesc(new PhoneNumberDesc().setNationalNumberPattern("\\d{4,8}")); metadata.setGeneralDesc(new PhoneNumberDesc().setNationalNumberPattern("\\d{4,8}"));
StringBuffer numberToStrip = new StringBuffer("34356778");
StringBuilder numberToStrip = new StringBuilder("34356778");
String strippedNumber = "356778"; String strippedNumber = "356778";
phoneUtil.maybeStripNationalPrefixAndCarrierCode(numberToStrip, metadata); phoneUtil.maybeStripNationalPrefixAndCarrierCode(numberToStrip, metadata);
assertEquals("Should have had national prefix stripped.", assertEquals("Should have had national prefix stripped.",
@ -1059,7 +1059,7 @@ public class PhoneNumberUtilTest extends TestCase {
strippedNumber, numberToStrip.toString()); strippedNumber, numberToStrip.toString());
// If the resultant number doesn't match the national rule, it shouldn't be stripped. // If the resultant number doesn't match the national rule, it shouldn't be stripped.
metadata.setNationalPrefixForParsing("3"); metadata.setNationalPrefixForParsing("3");
numberToStrip = new StringBuffer("3123");
numberToStrip = new StringBuilder("3123");
strippedNumber = "3123"; strippedNumber = "3123";
phoneUtil.maybeStripNationalPrefixAndCarrierCode(numberToStrip, metadata); phoneUtil.maybeStripNationalPrefixAndCarrierCode(numberToStrip, metadata);
assertEquals("Should have had no change - after stripping, it wouldn't have matched " + assertEquals("Should have had no change - after stripping, it wouldn't have matched " +
@ -1067,7 +1067,7 @@ public class PhoneNumberUtilTest extends TestCase {
strippedNumber, numberToStrip.toString()); strippedNumber, numberToStrip.toString());
// Test extracting carrier selection code. // Test extracting carrier selection code.
metadata.setNationalPrefixForParsing("0(81)?"); metadata.setNationalPrefixForParsing("0(81)?");
numberToStrip = new StringBuffer("08122123456");
numberToStrip = new StringBuilder("08122123456");
strippedNumber = "22123456"; strippedNumber = "22123456";
assertEquals("81", phoneUtil.maybeStripNationalPrefixAndCarrierCode(numberToStrip, metadata)); assertEquals("81", phoneUtil.maybeStripNationalPrefixAndCarrierCode(numberToStrip, metadata));
assertEquals("Should have had national prefix and carrier code stripped.", assertEquals("Should have had national prefix and carrier code stripped.",
@ -1076,7 +1076,7 @@ public class PhoneNumberUtilTest extends TestCase {
metadata.setNationalPrefixTransformRule("5$15"); metadata.setNationalPrefixTransformRule("5$15");
// Note that a capturing group is present here. // Note that a capturing group is present here.
metadata.setNationalPrefixForParsing("0(\\d{2})"); metadata.setNationalPrefixForParsing("0(\\d{2})");
numberToStrip = new StringBuffer("031123");
numberToStrip = new StringBuilder("031123");
String transformedNumber = "5315123"; String transformedNumber = "5315123";
phoneUtil.maybeStripNationalPrefixAndCarrierCode(numberToStrip, metadata); phoneUtil.maybeStripNationalPrefixAndCarrierCode(numberToStrip, metadata);
assertEquals("Should transform the 031 to a 5315.", assertEquals("Should transform the 031 to a 5315.",
@ -1085,9 +1085,9 @@ public class PhoneNumberUtilTest extends TestCase {
public void testMaybeStripInternationalPrefix() { public void testMaybeStripInternationalPrefix() {
String internationalPrefix = "00[39]"; String internationalPrefix = "00[39]";
StringBuffer numberToStrip = new StringBuffer("0034567700-3898003");
StringBuilder numberToStrip = new StringBuilder("0034567700-3898003");
// Note the dash is removed as part of the normalization. // Note the dash is removed as part of the normalization.
StringBuffer strippedNumber = new StringBuffer("45677003898003");
StringBuilder strippedNumber = new StringBuilder("45677003898003");
assertEquals(CountryCodeSource.FROM_NUMBER_WITH_IDD, assertEquals(CountryCodeSource.FROM_NUMBER_WITH_IDD,
phoneUtil.maybeStripInternationalPrefixAndNormalize(numberToStrip, phoneUtil.maybeStripInternationalPrefixAndNormalize(numberToStrip,
internationalPrefix)); internationalPrefix));
@ -1099,14 +1099,14 @@ public class PhoneNumberUtilTest extends TestCase {
phoneUtil.maybeStripInternationalPrefixAndNormalize(numberToStrip, phoneUtil.maybeStripInternationalPrefixAndNormalize(numberToStrip,
internationalPrefix)); internationalPrefix));
numberToStrip = new StringBuffer("00945677003898003");
numberToStrip = new StringBuilder("00945677003898003");
assertEquals(CountryCodeSource.FROM_NUMBER_WITH_IDD, assertEquals(CountryCodeSource.FROM_NUMBER_WITH_IDD,
phoneUtil.maybeStripInternationalPrefixAndNormalize(numberToStrip, phoneUtil.maybeStripInternationalPrefixAndNormalize(numberToStrip,
internationalPrefix)); internationalPrefix));
assertEquals("The number supplied was not stripped of its international prefix.", assertEquals("The number supplied was not stripped of its international prefix.",
strippedNumber.toString(), numberToStrip.toString()); strippedNumber.toString(), numberToStrip.toString());
// Test it works when the international prefix is broken up by spaces. // Test it works when the international prefix is broken up by spaces.
numberToStrip = new StringBuffer("00 9 45677003898003");
numberToStrip = new StringBuilder("00 9 45677003898003");
assertEquals(CountryCodeSource.FROM_NUMBER_WITH_IDD, assertEquals(CountryCodeSource.FROM_NUMBER_WITH_IDD,
phoneUtil.maybeStripInternationalPrefixAndNormalize(numberToStrip, phoneUtil.maybeStripInternationalPrefixAndNormalize(numberToStrip,
internationalPrefix)); internationalPrefix));
@ -1119,8 +1119,8 @@ public class PhoneNumberUtilTest extends TestCase {
internationalPrefix)); internationalPrefix));
// Test the + symbol is also recognised and stripped. // Test the + symbol is also recognised and stripped.
numberToStrip = new StringBuffer("+45677003898003");
strippedNumber = new StringBuffer("45677003898003");
numberToStrip = new StringBuilder("+45677003898003");
strippedNumber = new StringBuilder("45677003898003");
assertEquals(CountryCodeSource.FROM_NUMBER_WITH_PLUS_SIGN, assertEquals(CountryCodeSource.FROM_NUMBER_WITH_PLUS_SIGN,
phoneUtil.maybeStripInternationalPrefixAndNormalize(numberToStrip, phoneUtil.maybeStripInternationalPrefixAndNormalize(numberToStrip,
internationalPrefix)); internationalPrefix));
@ -1129,15 +1129,15 @@ public class PhoneNumberUtilTest extends TestCase {
// If the number afterwards is a zero, we should not strip this - no country calling code begins // If the number afterwards is a zero, we should not strip this - no country calling code begins
// with 0. // with 0.
numberToStrip = new StringBuffer("0090112-3123");
strippedNumber = new StringBuffer("00901123123");
numberToStrip = new StringBuilder("0090112-3123");
strippedNumber = new StringBuilder("00901123123");
assertEquals(CountryCodeSource.FROM_DEFAULT_COUNTRY, assertEquals(CountryCodeSource.FROM_DEFAULT_COUNTRY,
phoneUtil.maybeStripInternationalPrefixAndNormalize(numberToStrip, phoneUtil.maybeStripInternationalPrefixAndNormalize(numberToStrip,
internationalPrefix)); internationalPrefix));
assertEquals("The number supplied had a 0 after the match so shouldn't be stripped.", assertEquals("The number supplied had a 0 after the match so shouldn't be stripped.",
strippedNumber.toString(), numberToStrip.toString()); strippedNumber.toString(), numberToStrip.toString());
// Here the 0 is separated by a space from the IDD. // Here the 0 is separated by a space from the IDD.
numberToStrip = new StringBuffer("009 0-112-3123");
numberToStrip = new StringBuilder("009 0-112-3123");
assertEquals(CountryCodeSource.FROM_DEFAULT_COUNTRY, assertEquals(CountryCodeSource.FROM_DEFAULT_COUNTRY,
phoneUtil.maybeStripInternationalPrefixAndNormalize(numberToStrip, phoneUtil.maybeStripInternationalPrefixAndNormalize(numberToStrip,
internationalPrefix)); internationalPrefix));
@ -1151,7 +1151,7 @@ public class PhoneNumberUtilTest extends TestCase {
String phoneNumber = "011112-3456789"; String phoneNumber = "011112-3456789";
String strippedNumber = "123456789"; String strippedNumber = "123456789";
int countryCallingCode = 1; int countryCallingCode = 1;
StringBuffer numberToFill = new StringBuffer();
StringBuilder numberToFill = new StringBuilder();
assertEquals("Did not extract country calling code " + countryCallingCode + " correctly.", assertEquals("Did not extract country calling code " + countryCallingCode + " correctly.",
countryCallingCode, countryCallingCode,
phoneUtil.maybeExtractCountryCode(phoneNumber, metadata, numberToFill, true, phoneUtil.maybeExtractCountryCode(phoneNumber, metadata, numberToFill, true,
@ -1169,7 +1169,7 @@ public class PhoneNumberUtilTest extends TestCase {
try { try {
String phoneNumber = "+6423456789"; String phoneNumber = "+6423456789";
int countryCallingCode = 64; int countryCallingCode = 64;
StringBuffer numberToFill = new StringBuffer();
StringBuilder numberToFill = new StringBuilder();
assertEquals("Did not extract country calling code " + countryCallingCode + " correctly.", assertEquals("Did not extract country calling code " + countryCallingCode + " correctly.",
countryCallingCode, countryCallingCode,
phoneUtil.maybeExtractCountryCode(phoneNumber, metadata, numberToFill, true, phoneUtil.maybeExtractCountryCode(phoneNumber, metadata, numberToFill, true,
@ -1182,7 +1182,7 @@ public class PhoneNumberUtilTest extends TestCase {
number.clear(); number.clear();
try { try {
String phoneNumber = "2345-6789"; String phoneNumber = "2345-6789";
StringBuffer numberToFill = new StringBuffer();
StringBuilder numberToFill = new StringBuilder();
assertEquals( assertEquals(
"Should not have extracted a country calling code - no international prefix present.", "Should not have extracted a country calling code - no international prefix present.",
0, 0,
@ -1195,7 +1195,7 @@ public class PhoneNumberUtilTest extends TestCase {
number.clear(); number.clear();
try { try {
String phoneNumber = "0119991123456789"; String phoneNumber = "0119991123456789";
StringBuffer numberToFill = new StringBuffer();
StringBuilder numberToFill = new StringBuilder();
phoneUtil.maybeExtractCountryCode(phoneNumber, metadata, numberToFill, true, number); phoneUtil.maybeExtractCountryCode(phoneNumber, metadata, numberToFill, true, number);
fail("Should have thrown an exception, no valid country calling code present."); fail("Should have thrown an exception, no valid country calling code present.");
} catch (NumberParseException e) { } catch (NumberParseException e) {
@ -1208,7 +1208,7 @@ public class PhoneNumberUtilTest extends TestCase {
try { try {
String phoneNumber = "(1 610) 619 4466"; String phoneNumber = "(1 610) 619 4466";
int countryCallingCode = 1; int countryCallingCode = 1;
StringBuffer numberToFill = new StringBuffer();
StringBuilder numberToFill = new StringBuilder();
assertEquals("Should have extracted the country calling code of the region passed in", assertEquals("Should have extracted the country calling code of the region passed in",
countryCallingCode, countryCallingCode,
phoneUtil.maybeExtractCountryCode(phoneNumber, metadata, numberToFill, true, phoneUtil.maybeExtractCountryCode(phoneNumber, metadata, numberToFill, true,
@ -1223,7 +1223,7 @@ public class PhoneNumberUtilTest extends TestCase {
try { try {
String phoneNumber = "(1 610) 619 4466"; String phoneNumber = "(1 610) 619 4466";
int countryCallingCode = 1; int countryCallingCode = 1;
StringBuffer numberToFill = new StringBuffer();
StringBuilder numberToFill = new StringBuilder();
assertEquals("Should have extracted the country calling code of the region passed in", assertEquals("Should have extracted the country calling code of the region passed in",
countryCallingCode, countryCallingCode,
phoneUtil.maybeExtractCountryCode(phoneNumber, metadata, numberToFill, false, phoneUtil.maybeExtractCountryCode(phoneNumber, metadata, numberToFill, false,
@ -1235,7 +1235,7 @@ public class PhoneNumberUtilTest extends TestCase {
number.clear(); number.clear();
try { try {
String phoneNumber = "(1 610) 619 446"; String phoneNumber = "(1 610) 619 446";
StringBuffer numberToFill = new StringBuffer();
StringBuilder numberToFill = new StringBuilder();
assertEquals("Should not have extracted a country calling code - invalid number after " + assertEquals("Should not have extracted a country calling code - invalid number after " +
"extraction of uncertain country calling code.", "extraction of uncertain country calling code.",
0, 0,
@ -1248,7 +1248,7 @@ public class PhoneNumberUtilTest extends TestCase {
number.clear(); number.clear();
try { try {
String phoneNumber = "(1 610) 619"; String phoneNumber = "(1 610) 619";
StringBuffer numberToFill = new StringBuffer();
StringBuilder numberToFill = new StringBuilder();
assertEquals("Should not have extracted a country calling code - too short number both " + assertEquals("Should not have extracted a country calling code - too short number both " +
"before and after extraction of uncertain country calling code.", "before and after extraction of uncertain country calling code.",
0, 0,


Loading…
Cancel
Save