2230885078fcc3ae95bf09d1bac0bf93d558e699
[svjatoslav_commons.git] / src / main / java / eu / svjatoslav / commons / network / LocaleConfiguration.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 java.util.ArrayList;
13 import java.util.List;
14
15 import javax.servlet.http.HttpServletRequest;
16
17 public class LocaleConfiguration {
18
19         Locale defaultLocale;
20
21         private final List<Locale> allowedLocales = new ArrayList<Locale>();
22
23         public LocaleConfiguration(final Locale defaultLocale,
24                         final Locale... allowedLocales) {
25
26                 this.defaultLocale = defaultLocale;
27
28                 for (final Locale locale : allowedLocales)
29                         this.getAllowedLocales().add(locale);
30         }
31
32         public Locale detectCurrentLocale(final HttpServletRequest request) {
33
34                 final String sessionLocaleString = (String) request.getSession()
35                                 .getAttribute("locale");
36
37                 Locale result = localeFromString(sessionLocaleString);
38                 if (result == null)
39                         result = defaultLocale;
40
41                 final Locale requestLocale = localeFromString(request
42                                 .getParameter("locale"));
43                 if (requestLocale != null)
44                         result = requestLocale;
45
46                 request.getSession().setAttribute("locale", result.asString());
47
48                 return result;
49         }
50
51         private Locale localeFromString(final String localeString) {
52                 for (final Locale locale : getAllowedLocales())
53                         if (locale.asString().equals(localeString))
54                                 return locale;
55
56                 return null;
57         }
58
59         public List<Locale> getAllowedLocales() {
60                 return allowedLocales;
61         }
62
63 }