LocaleUtil { @Nonnull public static Locale parse(@Nonnull final String locale) { assert locale != null; if (locale.isEmpty()) { throw new IllegalArgumentException("Locale must not be empty"); } final String language; final String country; final String variant; final String[] parts = locale.split("_", 3); switch (parts.length) { case 1: language = parts[0].toLowerCase(Locale.ENGLISH); validateLanguage(language); return new Locale(language); case 2: language = parts[0].toLowerCase(Locale.ENGLISH); country = parts[1].toUpperCase(Locale.ENGLISH); validateLanguage(language); validateCountry(country); validateLanguageOrCountryNotEmpty(language, country); return new Locale(language, country); case 3: language = parts[0].toLowerCase(Locale.ENGLISH); country = parts[1].toUpperCase(Locale.ENGLISH); variant = parts[2]; validateLanguage(language); validateCountry(country); validateVariant(variant); validateLanguageOrCountryNotEmpty(language, country); return new Locale(language, country, variant); default: assert false; break; } assert false; return null; } private  LocaleUtil(); @Nonnull static Locale parse(@Nonnull final String locale);  }
@Test public void testValidLocales() { assertEquals(new Locale("nl"), LocaleUtil.parse("nl")); assertEquals(new Locale("nl", "NL"), LocaleUtil.parse("nl_nl")); assertEquals(new Locale("", "NL"), LocaleUtil.parse("_NL")); assertEquals(new Locale("nl", "NL"), LocaleUtil.parse("nl_NL")); assertEquals(new Locale("nl", "", "MAC"), LocaleUtil.parse("nl__MAC")); assertEquals(new Locale("nl", "NL", "MAC"), LocaleUtil.parse("nl_NL_MAC")); assertEquals(new Locale("", "NL", "MAC"), LocaleUtil.parse("_NL_MAC")); assertEquals(new Locale("es", "ES", "Traditional_WIN"), LocaleUtil.parse("es_ES_Traditional_WIN")); assertEquals(new Locale("nl", "", "_"), LocaleUtil.parse("nl___")); }
@Test public void testInvalidLocales() { try { LocaleUtil.parse(""); Assert.fail("IllegalArgumentException expected"); } catch (final IllegalArgumentException ignored) { } try { LocaleUtil.parse("__MAC"); Assert.fail("IllegalArgumentException expected"); } catch (final IllegalArgumentException ignored) { } try { LocaleUtil.parse("nl_G"); Assert.fail("IllegalArgumentException expected"); } catch (final IllegalArgumentException ignored) { } try { LocaleUtil.parse("nl_GBR_MAC"); Assert.fail("IllegalArgumentException expected"); } catch (final IllegalArgumentException ignored) { } try { LocaleUtil.parse("nl_GBR_MA"); Assert.fail("IllegalArgumentException expected"); } catch (final IllegalArgumentException ignored) { } try { LocaleUtil.parse("ac_GB"); Assert.fail("IllegalArgumentException expected"); } catch (final IllegalArgumentException ignored) { } try { LocaleUtil.parse("nl_UK"); Assert.fail("IllegalArgumentException expected"); } catch (final IllegalArgumentException ignored) { } }