Removed Locale enum to make code usable for every possible language.
[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         String defaultLocale;
20
21         private final List<String> allowedLocales = new ArrayList<String>();
22
23         public LocaleConfiguration(final String defaultLocale,
24                         final String... allowedLocales) {
25
26                 this.defaultLocale = defaultLocale;
27
28                 for (final String locale : allowedLocales)
29                         getAllowedLocales().add(locale);
30         }
31
32         public String detectCurrentLocale(final HttpServletRequest request) {
33
34                 final String sessionLocaleString = (String) request.getSession()
35                                 .getAttribute("locale");
36
37                 String result = defaultLocale;
38                 if (isAllowedLocale(sessionLocaleString))
39                         result = sessionLocaleString;
40
41                 final String requestLocale = request.getParameter("locale");
42
43                 if (isAllowedLocale(requestLocale))
44                         result = requestLocale;
45
46                 request.getSession().setAttribute("locale", result);
47
48                 return result;
49         }
50
51         public List<String> getAllowedLocales() {
52                 return allowedLocales;
53         }
54
55         public boolean isAllowedLocale(final String locale) {
56                 return allowedLocales.contains(locale);
57         }
58
59 }