]> git.argeo.org Git - lgpl/argeo-commons.git/blob - org.argeo.cms.ui/src/org/argeo/cms/ui/widgets/auth/LocaleChoice.java
Expose servlet context helpers.
[lgpl/argeo-commons.git] / org.argeo.cms.ui / src / org / argeo / cms / ui / widgets / auth / LocaleChoice.java
1 package org.argeo.cms.ui.widgets.auth;
2
3 import java.util.Collections;
4 import java.util.List;
5 import java.util.Locale;
6
7 import javax.security.auth.callback.LanguageCallback;
8
9 import org.argeo.cms.CmsException;
10 import org.argeo.cms.LocaleUtils;
11
12 /** Choose in a list of locales. TODO: replace with {@link LanguageCallback} */
13 public class LocaleChoice {
14 private final List<Locale> locales;
15
16 private Integer selectedIndex = null;
17 private final Integer defaultIndex;
18
19 public LocaleChoice(List<Locale> locales, Locale defaultLocale) {
20 Integer defaultIndex = null;
21 this.locales = Collections.unmodifiableList(locales);
22 for (int i = 0; i < locales.size(); i++)
23 if (locales.get(i).equals(defaultLocale))
24 defaultIndex = i;
25
26 // based on language only
27 if (defaultIndex == null)
28 for (int i = 0; i < locales.size(); i++)
29 if (locales.get(i).getLanguage().equals(defaultLocale.getLanguage()))
30 defaultIndex = i;
31
32 if (defaultIndex == null)
33 throw new CmsException("Default locale " + defaultLocale + " is not in available locales " + locales);
34 this.defaultIndex = defaultIndex;
35
36 this.selectedIndex = defaultIndex;
37 }
38
39 /**
40 * Convenience constructor based on a comma separated list of iso codes (en,
41 * en_US, fr_CA, etc.). Default selection is default locale.
42 */
43 public LocaleChoice(String locales, Locale defaultLocale) {
44 this(LocaleUtils.asLocaleList(locales), defaultLocale);
45 }
46
47 public String[] getSupportedLocalesLabels() {
48 String[] labels = new String[locales.size()];
49 for (int i = 0; i < locales.size(); i++) {
50 Locale locale = locales.get(i);
51 if (locale.getCountry().equals(""))
52 labels[i] = locale.getDisplayLanguage(locale) + " [" + locale.getLanguage() + "]";
53 else
54 labels[i] = locale.getDisplayLanguage(locale) + " (" + locale.getDisplayCountry(locale) + ") ["
55 + locale.getLanguage() + "_" + locale.getCountry() + "]";
56
57 }
58 return labels;
59 }
60
61 public Locale getSelectedLocale() {
62 if (selectedIndex == null)
63 return null;
64 return locales.get(selectedIndex);
65 }
66
67 public void setSelectedIndex(Integer selectedIndex) {
68 this.selectedIndex = selectedIndex;
69 }
70
71 public Integer getSelectedIndex() {
72 return selectedIndex;
73 }
74
75 public Integer getDefaultIndex() {
76 return defaultIndex;
77 }
78
79 public List<Locale> getLocales() {
80 return locales;
81 }
82
83 public Locale getDefaultLocale() {
84 return locales.get(getDefaultIndex());
85 }
86 }