Changed license to LGPLv3 or later.
[svjatoslav_commons.git] / src / main / java / eu / svjatoslav / commons / network / LocaleHelper.java
1 /*
2  * Svjatoslav Commons - shared library of common functionality.
3  * Copyright ©2012-2014, Svjatoslav Agejenko, svjatoslav@svjatoslav.eu
4  * 
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of version 3 of the GNU Lesser General Public License
7  * or later as published by the Free Software Foundation.
8  */
9
10 package eu.svjatoslav.commons.network;
11
12 import javax.servlet.http.HttpServletRequest;
13
14 public class LocaleHelper {
15
16         public static Locale detectLocale(final HttpServletRequest request) {
17
18                 final String sessionLocaleString = (String) request.getSession()
19                                 .getAttribute("locale");
20
21                 Locale sessionLocale = localeFromString(sessionLocaleString);
22                 if (sessionLocale == null)
23                         sessionLocale = Locale.ENG;
24
25                 final Locale requestLocale = localeFromString(request
26                                 .getParameter("locale"));
27                 if (requestLocale != null)
28                         sessionLocale = requestLocale;
29
30                 request.getSession().setAttribute("locale", sessionLocale.asString());
31
32                 return sessionLocale;
33         }
34
35         public static Locale localeFromString(final String localeString) {
36                 for (final Locale locale : Locale.values())
37                         if (locale.asString().equals(localeString))
38                                 return locale;
39
40                 return null;
41         }
42
43 }