Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8176853

Locale.Builder.removeUnicodeLocaleAttribute(null) should throw NullPointerException

XMLWordPrintable

    • Icon: Bug Bug
    • Resolution: Fixed
    • Icon: P3 P3
    • 10
    • None
    • core-libs
    • None
    • b11
    • Verified

      A colleague reports:

      java.util.Locale.Builder.removeUnicodeLocaleAttribute(null) is documented to throw NullPointerException, but instead throws IllformedLocaleException. This patch for OpenJDK 9 fixes this:

      diff -r 09b92d3067a3 src/java.base/share/classes/java/util/Locale.java
      --- a/src/java.base/share/classes/java/util/Locale.java Mon Mar 13 10:24:16 2017 -0700
      +++ b/src/java.base/share/classes/java/util/Locale.java Thu Mar 16 16:29:33 2017 +1100
      @@ -2696,6 +2696,7 @@
                * @see #setExtension(char, String)
                */
               public Builder removeUnicodeLocaleAttribute(String attribute) {
      + Objects.requireNonNull(attribute);
                   try {
                       localeBuilder.removeUnicodeLocaleAttribute(attribute);
                   } catch (LocaleSyntaxException e) {

      Here is a failing test that demonstrates the problem on OpenJDK8u121 (should also fail on OpenJDK 9, but this wasn't tested):

      @Test
      public void removeUnicodeLocaleAttribute() {
        Locale.Builder builder = new Locale.Builder();
        try {
          builder.removeUnicodeLocaleAttribute(null);
          fail();
        } catch (NullPointerException expected) {
        }
      }

      Test failure:

      java.util.IllformedLocaleException: Ill-formed Unicode locale attribute: null [at index 0]

      at java.util.Locale$Builder.removeUnicodeLocaleAttribute(Locale.java:2628)
      at LocaleBuilderTest.removeUnicodeLocaleAttribute(LocaleBuilderTest.java:16)
       ...


      More background:

      The documentation includes:

               * @throws NullPointerException if <code>attribute</code> is null
               * @throws IllformedLocaleException if <code>attribute</code> is ill-formed

      However the implementation delegates immediately to InternalLocaleBuilder. removeUnicodeLocaleAttribute() whose implementation starts as follows:
       if (attribute == null || !UnicodeLocaleExtension.isAttribute(attribute)) {

        throw new LocaleSyntaxException("Ill-formed Unicode locale attribute: " + attribute);

      }

      The patch applies to Locale.java rather than InternalLocaleBuilder.java because LocaleBuilder is the class that introduces the contract about NPE in its documentation.

            naoto Naoto Sato
            martin Martin Buchholz
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated:
              Resolved: