diff --git a/api/src/main/java/org/openmrs/util/LocaleUtility.java b/api/src/main/java/org/openmrs/util/LocaleUtility.java index a39a04f03c43..54ba421e1a8c 100644 --- a/api/src/main/java/org/openmrs/util/LocaleUtility.java +++ b/api/src/main/java/org/openmrs/util/LocaleUtility.java @@ -15,6 +15,7 @@ import java.util.MissingResourceException; import java.util.Set; +import org.apache.commons.lang3.LocaleUtils; import org.openmrs.GlobalProperty; import org.openmrs.api.GlobalPropertyListener; import org.openmrs.api.context.Context; @@ -127,18 +128,29 @@ public static boolean areCompatible(Locale lhs, Locale rhs) { * Should get locale from language code country code and variant */ public static Locale fromSpecification(String localeSpecification) { - Locale createdLocale = null; + Locale createdLocale; localeSpecification = localeSpecification.trim(); + try { + createdLocale = LocaleUtils.toLocale(localeSpecification); + } catch (IllegalArgumentException e) { + createdLocale = generateLocaleFromLegacyFormat(localeSpecification); + } + + return createdLocale; + } + + private static Locale generateLocaleFromLegacyFormat(String localeSpecification) { + Locale createdLocale = null; + String[] localeComponents = localeSpecification.split("_"); if (localeComponents.length == 1) { createdLocale = new Locale(localeComponents[0]); } else if (localeComponents.length == 2) { createdLocale = new Locale(localeComponents[0], localeComponents[1]); } else if (localeComponents.length > 2) { - String variant = localeSpecification.substring(localeSpecification.indexOf(localeComponents[2])); // gets everything after the - // second underscore + String variant = localeSpecification.substring(localeSpecification.indexOf(localeComponents[2])); createdLocale = new Locale(localeComponents[0], localeComponents[1], variant); } diff --git a/api/src/test/java/org/openmrs/util/LocaleUtilityTest.java b/api/src/test/java/org/openmrs/util/LocaleUtilityTest.java index ddde89ff7d94..a7a06cfae37d 100644 --- a/api/src/test/java/org/openmrs/util/LocaleUtilityTest.java +++ b/api/src/test/java/org/openmrs/util/LocaleUtilityTest.java @@ -3,7 +3,7 @@ * v. 2.0. If a copy of the MPL was not distributed with this file, You can * obtain one at http://mozilla.org/MPL/2.0/. OpenMRS is also distributed under * the terms of the Healthcare Disclaimer located at http://openmrs.org/license. - * + * * Copyright (C) OpenMRS Inc. OpenMRS is a registered trademark and the OpenMRS * graphic logo is a trademark of OpenMRS Inc. */ @@ -178,6 +178,14 @@ public void fromSpecification_shouldGetLocaleFromLanguageCodeAndCountryCode() { assertEquals(Locale.UK, LocaleUtility.fromSpecification("en_GB")); } + /** + * @see LocaleUtility#fromSpecification(String) + */ + @Test + public void fromSpecification_shouldGetLocaleFromBCP47Format() { + assertEquals(Locale.UK, LocaleUtility.fromSpecification("en-GB")); + } + /** * @see LocaleUtility#fromSpecification(String) */