Created dedicated locale configuration handler.
[svjatoslav_commons.git] / src / main / java / eu / svjatoslav / commons / network / LocaleConfiguration.java
diff --git a/src/main/java/eu/svjatoslav/commons/network/LocaleConfiguration.java b/src/main/java/eu/svjatoslav/commons/network/LocaleConfiguration.java
new file mode 100755 (executable)
index 0000000..2230885
--- /dev/null
@@ -0,0 +1,63 @@
+/*
+ * 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;
+       }
+
+}