/*
Find an AttachmentResource in a given set which either has the desired Locale
or failing that, the same language as the desired locale.
2539
public static AttachmentSummary matchByLocale(Collection<? extends AttachmentSummary> attachments,
                                                  AttachmentType desiredType, Locale desiredLocale) {
        Collection<AttachmentSummary> possibleMatches = new ArrayList<AttachmentSummary>();
        for (AttachmentSummary s : attachments) {
            AttachmentType attType = s.getAttachment().getType();

            if (attType.equals(desiredType)) {
                // This is either an exact match, or a candidate for a match-by-language
                if (s.getLocale().equals(desiredLocale)) {
                    return s;
                } else {
                    possibleMatches.add(s);
                }
            }
        }

        Locale baseDesiredLocale = new Locale(desiredLocale.getLanguage());
        for (AttachmentSummary s : possibleMatches) {
            if (s.getLocale().equals(baseDesiredLocale)) {
                return s;
            }
        }

        // If we've found no better match, can we at least provide English?
        for (AttachmentSummary s : possibleMatches) {
            if (s.getLocale().equals(Locale.ENGLISH)) {
                return s;
            }
        }

        // Getting desperate: do we have anything that's language is English?
        for (AttachmentSummary s : possibleMatches) {
            if (new Locale(s.getLocale().getLanguage()).equals(Locale.ENGLISH)) {
                return s;
            }
        }

        return null;
    }
732335
public ResourceBundle findResourceBundle(String resourcePath, Locale locale, String versionRange)
    {
        //if (ClassServiceBootstrap.repositoryAdmin == null)
        //    return null;

        ResourceBundle resourceBundle = this.getResourceBundleFromBundle(null, resourcePath, locale, versionRange);

        if (resourceBundle == null) {
            Object resource = this.deployThisResource(ClassFinderActivator.getPackageName(resourcePath, true), versionRange, false);
            if (resource != null)
            {
            	resourceBundle = this.getResourceBundleFromBundle(resource, resourcePath, locale, versionRange);
            	if (resourceBundle == null)
            	{
            		Class<?> c = this.getClassFromBundle(resource, resourcePath, versionRange);
            		if (c != null)
            		{
					   try {
						   resourceBundle = (ResourceBundle)c.newInstance();
					   } catch (InstantiationException e)   {
					       e.printStackTrace();	// Never
					   } catch (IllegalAccessException e)   {
					       e.printStackTrace();	// Never
					   } catch (Exception e) {
					       e.printStackTrace();	// Never
					   }            			
            		}
            	}
            }
        }

        return resourceBundle;
    }
1197165
private static String getLocalizedValues(final String locale, final List<?> items) {
        val foundLocale = findLocale(StringUtils.defaultString(locale, "en"), items);
        if (foundLocale.isPresent()) {
            return foundLocale.get();
        }

        if (!items.isEmpty()) {
            val item = items.get(0);
            var value = StringUtils.EMPTY;
            if (item instanceof LocalizedName) {
                value = ((LocalizedName) item).getValue();
            }
            if (item instanceof LocalizedURI) {
                value = ((LocalizedURI) item).getValue();
            }
            if (item instanceof XSString) {
                value = ((XSString) item).getValue();
            }
            LOGGER.trace("Loading first available locale [{}]", value);
            return value;
        }
        return null;
    }
56575
private ResourceBundle getResourceBundleFromBundle(Object resource, String baseName, Locale locale, String versionRange)
    {
    	ResourceBundle resourceBundle = null;
        if (resource == null)
        {
            Object classAccess = this.getClassBundleService(null, baseName, versionRange, null, 0);
            if (classAccess != null)
            {
                if ((classAccess != null) && (USE_NO_RESOURCE_HACK))
                {
	                try {
						URL url = classAccess.getClass().getClassLoader().getResource(baseName);
						InputStream stream = url.openStream();
						resourceBundle = new PropertyResourceBundle(stream);
					} catch (IOException e) {
						e.printStackTrace();
					}
                }
                else
                {
                    ClassLoader loader = classAccess.getClass().getClassLoader();
                	resourceBundle = ResourceBundle.getBundle(baseName, locale, loader);
                }
            }
        }
        else
        {
        	Bundle bundle = this.findBundle(resource, bundleContext, ClassFinderActivator.getPackageName(baseName, true), versionRange);
            if (USE_NO_RESOURCE_HACK)
            {
                try {
                	// TODO - If I have to do this, then I will have to link up the resourcebundle using the locales.
                	baseName = baseName.replace('.', File.separatorChar) + ClassFinderActivator.PROPERTIES;
					URL url = bundle.getEntry(baseName);
					if (url != null)
						resourceBundle = new PropertyResourceBundle(url.openStream());
				} catch (IOException e) {
					e.printStackTrace();
				}
            }
            else
            {
            	ClassLoader loader = bundle.getClass().getClassLoader();
            	resourceBundle = ResourceBundle.getBundle(baseName, locale, loader);
            }
        }
        return resourceBundle;
    }
946512
function resolveLocale(locales) {
	const localesFingerprint = locales.toString()
	if (resolvedLocales[localesFingerprint]) {
		return resolvedLocales[localesFingerprint] 
	}
	return resolvedLocales[localesFingerprint] = intlDateTimeFormatSupportedLocale(locales)
}
57385
public CLDR.Locale match(MetaLocale locale) {
    MetaLocale result = availableBundlesMap.get(locale);
    MetaLocale maxBundleId = null;
    if (result == null) {
      // If the locale isn't expanded, do that here by adding likely subtags.
      // For the vast majority of cases this code shouldn't be executed, since
      // we've indexed permutations of locales to create a static mapping to
      // bundle identifiers.
      maxBundleId = languageResolver.addLikelySubtags(locale);
      MetaLocale minBundleId = languageResolver.removeLikelySubtags(maxBundleId);
      result = availableBundlesMap.get(minBundleId);
    }
    if (result == null) {
      // Fallback necessary to find best match for language tags that have
      // invalid fields, e.g. those with an unknown region, etc.
      MetaLocale key = maxBundleId.copy();
      for (int flags : LanguageResolver.MATCH_ORDER) {
        LanguageResolver.set(maxBundleId, key, flags);
        result = availableBundlesMap.get(key);
        if (result != null && result.hasLanguage()) {
          return result;
        }
      }
    }
    return result != null ? result : availableBundlesMap.get((MetaLocale)CLDR.Locale.en);
  }
353561
String getResourceString(String key) {
        if (outputRB == null) {
            try {
                outputRB = ResourceBundle.getBundle(L10N_RB_NAME, locale);
            } catch (MissingResourceException mre) {
                error("Cannot find ResourceBundle: %s for locale: %s", L10N_RB_NAME, locale);
                return "";
            }
        }
        String s;
        try {
            s = outputRB.getString(key);
        } catch (MissingResourceException mre) {
            error("Missing resource: %s in %s", key, L10N_RB_NAME);
            return "";
        }
        return s;
    }
713641
public static boolean hasLocale(final Locale locale) {
        try {
            ResourceBundle.getBundle(Keys.LANGUAGE, locale);

            return true;
        } catch (final MissingResourceException e) {
            return false;
        }
    }
1289565
public static CmsJspContentAttachmentsBean getAttachmentsForLocale(
        CmsObject cms,
        CmsResource content,
        String locale) {

        Optional<CmsResource> detailOnly = CmsDetailOnlyContainerUtil.getDetailOnlyPage(cms, content, locale);
        if (!detailOnly.isPresent()) {
            return new CmsJspContentAttachmentsBean();
        } else {
            try {
                return new CmsJspContentAttachmentsBean(cms, detailOnly.get());
            } catch (Exception e) {
                LOG.error(e.getLocalizedMessage(), e);
                return new CmsJspContentAttachmentsBean();
            }
        }
    }
413962
def locate_resource(name, lang, filter=None):
  
  task_dir = resource_dir.get(name, name)
  package_id = u"{}.{}".format(task_dir, lang)
  p = path.join(polyglot_path, task_dir, lang)
  if not path.isdir(p):
    if downloader.status(package_id) != downloader.INSTALLED:
      raise ValueError("This resource is available in the index "
                       "but not downloaded, yet. Try to run\n\n"
                       "polyglot download {}".format(package_id))
  return path.join(p, os.listdir(p)[0])
1345545
function getTranslation(keyPath, locale) {
    var translation = eval('_locales.' + locale + '.' + keyPath);
    if(!translation || (translation === undefined)) {
      return null;
    }
    return translation;
  }
831298
public Resource getResource(String name, Locale locale, String encoding) throws IOException {
        name = UrlUtils.cleanName(name);
        locale = cleanLocale(locale);
        return loadResource(name, locale, encoding);
    }
1337688
private function getFromExcludedSource($key, $replace, $locale, $fallback)
    {
        if(!PageKey::fromLineKeyString($key)->isExcludedSource()) return null;

        return parent::get($key, $replace, $locale, $fallback);
    }
826731
public String getMessage(String key, Locale locale)
	{
		if (null == locale)
		{
			return getMessage(key);
		}
		return CollectionTools.getString(getResourceBundle(locale), key, getBehaviourOnMissingMessage().getValueOnMissingMessage(key));
	}
880536
private ResourceBundle findBundle(String baseName) {
    ResourceBundle resourceBundle = null;

    // first try to load the resource bundle with the specified locale
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    if (null != locale) {
      try {
        resourceBundle = ResourceBundle.getBundle(baseName, locale, cl);
      } catch (Exception e) {
        log.fatal("unable to load a default bundle: "+baseName+"_"+locale);
      }
      // check that the requested main locale matches the resource bundle's,
      // since we get the system fallback locale if no match is found
      if(!resourceBundle.getLocale().equals(locale)) {
        resourceBundle = null;
      }
    }

    // loop through the fall back locales until a bundle is found
    if (null == resourceBundle) {
      if(null != fallback) {
        while(fallback.hasMoreElements()) {
          Locale testLocale = (Locale) fallback.nextElement();
          log.debug("looking up locale "+testLocale);
          ResourceBundle testBundle = ResourceBundle.getBundle(baseName, testLocale, cl);
          String language = testBundle.getLocale().getLanguage();
          String country = testBundle.getLocale().getCountry();

          if (testBundle.getLocale().equals(testLocale)) {
            resourceBundle = testBundle;
            log.debug("found bundle for locale " +baseName+"_"+ testBundle.getLocale());
            break;
          } else if (testLocale.getLanguage().equals(language)) {
            if (testLocale.getCountry().equals(country)) {
              // language and country match which is good, keep looking for variant too
              resourceBundle = testBundle;
              log.debug("potential bundle: " + baseName + "_" + testBundle.getLocale());
              continue;
            } else {
              // only accept this if there is no better previous lookup
              if (null == resourceBundle) {
                resourceBundle = testBundle;
                log.debug("potential bundle: " + baseName+"_"+testBundle.getLocale());
              }
              continue;
            }
          }
        }
      }

      // make sure the resource bundle is loaded (should not happen)
      if (null == resourceBundle) {
        resourceBundle = ResourceBundle.getBundle(baseName);
        if (null != resourceBundle) {
          log.debug("system locale bundle taken: " + baseName + "_" + resourceBundle.getLocale());
        }
      }
    }

    return resourceBundle;
  }
1324599
public static Set<String> getAvailableLocaleNameSet(String bundlePrefix, ClassLoader loader) {
        return getAvailEntry(bundlePrefix, loader).getLocaleNameSet();
    }
1132182
@SuppressWarnings({"unchecked"})
    public static <T extends LocalizableResource> T get(Class<T> cls, String locale) {
        Map<String, LocalizableResource> localeCache = getLocaleCache(cls);
        T m = (T) localeCache.get(locale);
        if (m != null) {
            return m;
        }
        synchronized (cache) {
            m = (T) localeCache.get(locale);
            if (m != null) {
                return m;
            }
            m = provider.create(cls, locale);
            put(cls, locale, m);
            return m;
        }
    }