LocaleParser implements Parser<List<Locale>> { @Override public List<Locale> parse(final String input) throws MalformedInputException { String[] localesStr = input.split(LOCALE_SEPARATOR); List<LocaleWithWeight> localesWithWeight = new ArrayList<>(); for (String locale : localesStr) { double weight = 1.0; String[] localeParts = locale.split(WEIGHT_SEPARATOR); if (localeParts.length == 0) { continue; } if (localeParts[0].length() != 2) { continue; } if (localeParts.length > 1 && localeParts[1].length() > 0) { if (localeParts[1].startsWith(WEIGHT_PREFIX)) { weight = Double.parseDouble(localeParts[1].substring(2)); } else { continue; } } localesWithWeight.add(new LocaleWithWeight(new Locale(localeParts[0]), weight)); } return toLocales(localesWithWeight); }  @Override List<Locale> parse(final String input);  }
@Test public void shouldParseLocales() throws MalformedInputException { String localeString = "pl-PL,pl;q=0.8,en;q=0.4,ro;q=0.2,ru;q=0.2"; List<Locale> locales = LOCALE_PARSER.parse(localeString); assertThat(locales.get(0), is(new Locale("pl"))); assertThat(locales.get(1), is(new Locale("en"))); assertThat(locales.get(2), is(new Locale("ro"))); assertThat(locales.get(3), is(new Locale("ru"))); }
@Test public void shouldParseLocalesAndRespectWeights() throws MalformedInputException { String localeString = "pl-PL,ru;q=0.2,en;q=0.4,ro;q=0.3,pl;q=0.8"; List<Locale> locales = LOCALE_PARSER.parse(localeString); assertThat(locales.get(0), is(new Locale("pl"))); assertThat(locales.get(1), is(new Locale("en"))); assertThat(locales.get(2), is(new Locale("ro"))); assertThat(locales.get(3), is(new Locale("ru"))); }
@Test public void shouldHandleProperlyMissingWeight() throws MalformedInputException { String localeString = "pl-PL,ru;q=0.2,en;q=0.4,ro;q=0.3,pl"; List<Locale> locales = LOCALE_PARSER.parse(localeString); assertThat(locales.get(0), is(new Locale("pl"))); assertThat(locales.get(1), is(new Locale("en"))); assertThat(locales.get(2), is(new Locale("ro"))); assertThat(locales.get(3), is(new Locale("ru"))); }
@Test public void shouldIgnoreInvalidWeights() throws MalformedInputException { String localeString = "pl-PL,fr;TT,ru;q=0.2,en;q=0.4,ro;q=0.3,pl"; List<Locale> locales = LOCALE_PARSER.parse(localeString); assertThat(locales.get(0), is(new Locale("pl"))); assertThat(locales.get(1), is(new Locale("en"))); assertThat(locales.get(2), is(new Locale("ro"))); assertThat(locales.get(3), is(new Locale("ru"))); }
@Test public void shouldHandleErrorsTransparently() throws MalformedInputException { String localeString = "pl-PL,pl;,;;,,ru;q=0.2,en;q=0.4,ro;q=0.3"; List<Locale> locales = LOCALE_PARSER.parse(localeString); assertThat(locales.get(0), is(new Locale("pl"))); assertThat(locales.get(1), is(new Locale("en"))); assertThat(locales.get(2), is(new Locale("ro"))); assertThat(locales.get(3), is(new Locale("ru"))); }