public ResolvedLocale resolve()

in locales-common/src/main/java/com/spotify/i18n/locales/common/impl/LocalesResolverBaseImpl.java [100:139]


  public ResolvedLocale resolve(final String acceptLanguage) {
    // Fail fast when resolution is impossible
    if (Strings.isNullOrEmpty(acceptLanguage)) {
      return defaultResolvedLocale();
    }

    // Get a map of supported locales, keyed by locale for translations, with corresponding related
    // locales for formatting as values
    Map<ULocale, Set<ULocale>> supportedLocalesMap =
        supportedLocales().stream()
            .collect(
                Collectors.toMap(
                    sl -> sl.localeForTranslations(), sl -> sl.relatedLocalesForFormatting()));

    // Generate matcher for all supported translations locales
    LocaleMatcher localeMatcherForTranslations = getLocaleMatcher(supportedLocalesMap.keySet());

    // We parse the accept-language value into a list of language ranges
    List<LanguageRange> languageRanges = AcceptLanguageUtils.parse(acceptLanguage);

    // We first try to get the best match directly
    Optional<ResolvedLocale> bestMatch =
        getBestMatch(languageRanges, localeMatcherForTranslations, supportedLocalesMap);

    // If there was no match, we override the accept-language entries with values from the default
    // locale, to find the closest match possible. This is required when the set of supported
    // locales contains several variants of the same language (for instance: en and en-GB, fr and
    // fr-CA, es and es-419, ...)
    if (bestMatch.isEmpty()) {
      bestMatch =
          getBestMatchBasedOnDefaultLocale(
              defaultResolvedLocale(),
              languageRanges,
              localeMatcherForTranslations,
              supportedLocalesMap);
    }

    // We return our best match, or the default locale if there was no such match.
    return bestMatch.orElse(defaultResolvedLocale());
  }