Code cleanup and formatting. Migrated to java 1.8.
[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 javax.servlet.http.HttpServletRequest;
13 import java.util.ArrayList;
14 import java.util.List;
15
16 public class LocaleConfiguration {
17
18     final String defaultLocale;
19     private final List<String> allowedLocales = new ArrayList<>();
20
21     public LocaleConfiguration(final String defaultLocale,
22                                final String... allowedLocales) {
23
24         this.defaultLocale = defaultLocale;
25
26         for (final String locale : allowedLocales)
27             getAllowedLocales().add(locale);
28     }
29
30     public String detectCurrentLocale(final HttpServletRequest request) {
31
32         final String sessionLocaleString = (String) request.getSession()
33                 .getAttribute("locale");
34
35         String result = defaultLocale;
36         if (isAllowedLocale(sessionLocaleString))
37             result = sessionLocaleString;
38
39         final String requestLocale = request.getParameter("locale");
40
41         if (isAllowedLocale(requestLocale))
42             result = requestLocale;
43
44         request.getSession().setAttribute("locale", result);
45
46         return result;
47     }
48
49     public List<String> getAllowedLocales() {
50         return allowedLocales;
51     }
52
53     public boolean isAllowedLocale(final String locale) {
54         return allowedLocales.contains(locale);
55     }
56
57 }