+/*
+ * Svjatoslav Commons - shared library of common functionality.
+ * Copyright ©2012-2014, Svjatoslav Agejenko, svjatoslav@svjatoslav.eu
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of version 3 of the GNU Lesser General Public License
+ * or later as published by the Free Software Foundation.
+ */
+
+package eu.svjatoslav.commons.network;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.servlet.http.HttpServletRequest;
+
+public class LocaleConfiguration {
+
+ Locale defaultLocale;
+
+ private final List<Locale> allowedLocales = new ArrayList<Locale>();
+
+ public LocaleConfiguration(final Locale defaultLocale,
+ final Locale... allowedLocales) {
+
+ this.defaultLocale = defaultLocale;
+
+ for (final Locale locale : allowedLocales)
+ this.getAllowedLocales().add(locale);
+ }
+
+ public Locale detectCurrentLocale(final HttpServletRequest request) {
+
+ final String sessionLocaleString = (String) request.getSession()
+ .getAttribute("locale");
+
+ Locale result = localeFromString(sessionLocaleString);
+ if (result == null)
+ result = defaultLocale;
+
+ final Locale requestLocale = localeFromString(request
+ .getParameter("locale"));
+ if (requestLocale != null)
+ result = requestLocale;
+
+ request.getSession().setAttribute("locale", result.asString());
+
+ return result;
+ }
+
+ private Locale localeFromString(final String localeString) {
+ for (final Locale locale : getAllowedLocales())
+ if (locale.asString().equals(localeString))
+ return locale;
+
+ return null;
+ }
+
+ public List<Locale> getAllowedLocales() {
+ return allowedLocales;
+ }
+
+}