LocaleUtil { public static Locale getLocale(HttpServletRequest httpServletRequest) { Locale locale = httpServletRequest.getLocale(); logger.info(">>>>>>>>> Locale from httpServletRequest is: " + locale.toString()); if (locale.toString().isEmpty() || locale.toString().equalsIgnoreCase("null")){ try { logger.info(">>>>>>>>> Fail to get locale from httpServletRequest and try to get from Http Header"); String acceptLanguageHeader = httpServletRequest.getHeader("Accept-Language"); String[] acceptLanguages=languagePattern.split(acceptLanguageHeader); for (String acceptLanguage : acceptLanguages) { acceptLanguage = qPattern.matcher(acceptLanguage).replaceAll("").trim(); if (localePattern.matcher(acceptLanguage).matches()){ String [] languageAndCountry = acceptLanguage.split("-"); String language = languageAndCountry[0].trim(); String country = languageAndCountry[1].trim(); if (supportedLanguage.contains(language)){ locale = new Locale(language, country, ""); break; } } else { if (supportedLanguage.contains(acceptLanguage)){ locale = new Locale(acceptLanguage); break; } } } } catch (Exception e) { logger.info(">>>>>>>>> Exception happended and return DEFAULT_LOCALE"); return DEFAULT_LOCALE; } } logger.info(">>>>>>>>> Returned Locale is: " + locale.toString()); return locale; }  static Locale getLocale(HttpServletRequest httpServletRequest);  }
@Test public void getDefaultLocaleTest() { MockHttpServletRequest request = new MockHttpServletRequest(); Locale locale_empty = LocaleUtil.getLocale(request); Locale default_locale = Locale.forLanguageTag("en"); assertEquals(default_locale, locale_empty); }
@Test public void getLocalbyAcceptLanguage() { MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader("accept-language", "en, jp;q=0.7, ko;q=0.8"); Locale cLocale = new Locale("en"); assertEquals(cLocale, LocaleUtil.getLocale(request)); }