2 * Copyright (C) 2016, 2017 Roland Häder
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU Affero General Public License as
6 * published by the Free Software Foundation, either version 3 of the
7 * License, or (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU Affero General Public License for more details.
14 * You should have received a copy of the GNU Affero General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 package org.mxchange.jjobs.beans.localization;
19 import java.text.MessageFormat;
20 import java.util.Iterator;
21 import java.util.LinkedHashMap;
22 import java.util.Locale;
24 import java.util.Objects;
25 import javax.annotation.PostConstruct;
26 import javax.enterprise.context.SessionScoped;
27 import javax.enterprise.event.Event;
28 import javax.enterprise.event.Observes;
29 import javax.enterprise.inject.Any;
30 import javax.faces.context.FacesContext;
31 import javax.inject.Inject;
32 import javax.inject.Named;
33 import org.mxchange.jcoreee.events.locale.LocaleChangeEvent;
34 import org.mxchange.jcoreee.events.locale.ObservableLocaleChangeEvent;
35 import org.mxchange.jjobs.beans.BaseJobsController;
36 import org.mxchange.juserlogincore.events.login.ObservableUserLoggedInEvent;
37 import org.mxchange.juserlogincore.events.logout.ObservableUserLogoutEvent;
40 * A session-scoped bean for handling localization/internationalization changes.
41 * This class is based on an example at [1] from mkyong.
43 * 1: http://www.mkyong.com/jsf2/jsf-2-internationalization-example/
45 * @author Roland Häder<roland@mxchange.org>
47 @Named ("localizationController")
49 public class JobsLocalizationSessionBean extends BaseJobsController implements JobsLocalizationSessionController {
54 private static final long serialVersionUID = 158_768_216_759_107L;
59 private Locale locale;
62 * Event being fired when a locale has changed successfully
66 private Event<ObservableLocaleChangeEvent> localeChangeEvent;
69 * Locale code (example: de for Germany)
71 private String localeCode;
74 * A map of all supported locales, using language code as key
76 private final Map<String, Locale> supportedLocales;
81 public JobsLocalizationSessionBean () {
82 // Call super constructor
86 this.supportedLocales = new LinkedHashMap<>(2);
90 * Event observer for logged-in user
92 * @param event Event instance
94 public void afterUserLoginEvent (@Observes final ObservableUserLoggedInEvent event) {
95 // event should not be null
98 throw new NullPointerException("event is null"); //NOI18N
99 } else if (event.getLoggedInUser() == null) {
101 throw new NullPointerException("event.loggedInUser is null"); //NOI18N
102 } else if (event.getLoggedInUser().getUserId() == null) {
104 throw new NullPointerException("event.loggedInUser.userId is null"); //NOI18N
105 } else if (event.getLoggedInUser().getUserId() < 1) {
107 throw new IllegalArgumentException(MessageFormat.format("userId of user={0} is not valid: {1}", event.getLoggedInUser(), event.getLoggedInUser().getUserId())); //NOI18N
110 // Is the locale set?
111 if (event.getLoggedInUser().getUserLocale() instanceof Locale) {
113 Locale userLocale = event.getLoggedInUser().getUserLocale();
116 this.changeLocale(userLocale);
121 * Event observer for logged-out user
123 * @param event Event instance
125 public void afterUserLogoutEvent (@Observes final ObservableUserLogoutEvent event) {
126 // event should not be null
129 throw new NullPointerException("event is null"); //NOI18N
130 } else if (event.getLoggedOutUser() == null) {
132 throw new NullPointerException("event.loggedOutUser is null"); //NOI18N
133 } else if (event.getLoggedOutUser().getUserId() == null) {
135 throw new NullPointerException("event.loggedOutUser.userId is null"); //NOI18N
136 } else if (event.getLoggedOutUser().getUserId() < 1) {
138 throw new IllegalArgumentException(MessageFormat.format("userId of user={0} is not valid: {1}", event.getLoggedOutUser(), event.getLoggedOutUser().getUserId())); //NOI18N
141 // Clear this bean as well
146 * Changes locale in application
148 public void doChangeLocale () {
149 // Is locale code set?
150 if (this.getLocaleCode() == null) {
152 throw new NullPointerException("this.localeCode is null"); //NOI18N
153 } else if (this.getLocaleCode().isEmpty()) {
155 throw new IllegalArgumentException("this.localeCode is empty"); //NOI18N
158 // Default new locale is null, will be handled later
159 Locale newLocale = null;
161 // Iterate over whole map
162 for (Map.Entry<String, Locale> entry : this.getSupportedLocales().entrySet()) {
163 Locale foundLocale = entry.getValue();
165 // Does the language match?
166 if (Objects.equals(foundLocale.toString(), this.getLocaleCode())) {
167 // Is found, take it as request locale
168 newLocale = foundLocale;
173 // Clear locale code field
176 // Has a matching locale
177 if (null == newLocale) {
179 throw new NullPointerException("this.localeCode=" + this.getLocaleCode() + " cannot be found."); //NOI18N
183 this.changeLocale(newLocale);
191 public Locale getLocale () {
198 * @param locale Locale
200 public void setLocale (final Locale locale) {
201 this.locale = locale;
205 * Getter for localeCode code
207 * @return Language code
209 public String getLocaleCode () {
210 return this.localeCode;
214 * Setter for localeCode code
216 * @param localeCode Language code
218 public void setLocaleCode (final String localeCode) {
219 this.localeCode = localeCode;
223 * Getter for selectable localizations
225 * @return Selectable localizations
227 @SuppressWarnings ("ReturnOfCollectionOrArrayField")
228 public Map<String, Locale> getSupportedLocales () {
230 return this.supportedLocales;
234 * Initializer for this bean
237 public void init () {
238 // Get default locale
239 Locale defaultLocale = FacesContext.getCurrentInstance().getApplication().getDefaultLocale();
242 this.getSupportedLocales().put(defaultLocale.toString(), defaultLocale);
244 // Get iterator from faces context
245 Iterator<Locale> iterator = FacesContext.getCurrentInstance().getApplication().getSupportedLocales();
248 while (iterator.hasNext()) {
250 Locale supportedLocale = iterator.next();
253 this.getSupportedLocales().put(supportedLocale.toString(), supportedLocale);
256 // Get locale instance from request (e.g. browser)
257 Locale requestLocale = FacesContext.getCurrentInstance().getExternalContext().getRequestLocale();
259 // Is no country code found?
260 if (requestLocale.getCountry().isEmpty()) {
261 // Then try to find one, get language from it
262 String language = requestLocale.getLanguage();
263 Boolean found = Boolean.FALSE;
265 // Iterate over whole map
266 for (Map.Entry<String, Locale> entry : this.getSupportedLocales().entrySet()) {
267 String languageCode = entry.getKey();
268 Locale foundLocale = entry.getValue();
270 // Does the language match?
271 if (languageCode.startsWith(language)) {
272 // Is found, take it as request locale
273 requestLocale = foundLocale;
274 found = Boolean.TRUE;
281 // Then set default locale
282 requestLocale = defaultLocale;
286 // Change locale, may set same back in faces context, but triggers event
287 this.changeLocale(requestLocale);
291 * Changes current locale in this controller and faces context to given.
292 * This method makes sure that locales with at least language and country
293 * information are being changed to.
295 * @param locale New locale to set
297 private void changeLocale (final Locale locale) {
298 // Is the locale language_country at least?
299 if (null == locale) {
301 throw new NullPointerException("locale is null"); //NOI18N
302 } else if (!locale.toString().contains("_")) { //NOI18N
304 throw new IllegalArgumentException(MessageFormat.format("locale={0} does not have country information set.", locale)); //NOI18N
307 // Set locale + code here
308 this.setLocale(locale);
309 this.setLocaleCode(locale.toString());
311 // Inform faces context
312 FacesContext.getCurrentInstance().getViewRoot().setLocale(locale);
315 this.localeChangeEvent.fire(new LocaleChangeEvent(locale));
321 private void clear () {
323 this.setLocaleCode(null);
324 this.setLocale(null);