2 * Copyright (C) 2016 - 2020 Free Software Foundation
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.text.NumberFormat;
21 import java.util.Iterator;
22 import java.util.LinkedHashMap;
23 import java.util.Locale;
25 import java.util.Objects;
26 import javax.annotation.PostConstruct;
27 import javax.enterprise.context.SessionScoped;
28 import javax.enterprise.event.Event;
29 import javax.enterprise.event.Observes;
30 import javax.enterprise.inject.Any;
31 import javax.faces.context.FacesContext;
32 import javax.inject.Inject;
33 import javax.inject.Named;
34 import org.mxchange.jcoreee.events.locale.LocaleChangeEvent;
35 import org.mxchange.jcoreee.events.locale.ObservableLocaleChangeEvent;
36 import org.mxchange.jjobs.beans.BaseJobsBean;
37 import org.mxchange.juserlogincore.events.login.ObservableUserLoggedInEvent;
38 import org.mxchange.juserlogincore.events.logout.ObservableUserLogoutEvent;
41 * A session-scoped bean for handling localization/internationalization changes.
42 * This class is based on an example at [1] from mkyong.
44 * 1: http://www.mkyong.com/jsf2/jsf-2-internationalization-example/
46 * @author Roland Häder<roland@mxchange.org>
48 @Named ("localizationController")
50 public class JobsLocalizationSessionBean extends BaseJobsBean implements JobsLocalizationSessionController {
55 private static NumberFormat NUMBER_FORMAT;
60 private static final long serialVersionUID = 158_768_216_759_107L;
65 private Locale locale;
68 * Event being fired when a locale has changed successfully
72 private Event<ObservableLocaleChangeEvent> localeChangeEvent;
75 * Locale code (example: de for Germany)
77 private String localeCode;
80 * A map of all supported locales, using language code as key
82 private final Map<String, Locale> supportedLocales;
87 public JobsLocalizationSessionBean () {
88 // Call super constructor
92 this.supportedLocales = new LinkedHashMap<>(2);
96 * Event observer for logged-in user
98 * @param event Event instance
100 public void afterUserLoginEvent (@Observes final ObservableUserLoggedInEvent event) {
101 // Event and contained entity instance should not be null
104 throw new NullPointerException("event is null"); //NOI18N
105 } else if (event.getLoggedInUser() == null) {
107 throw new NullPointerException("event.loggedInUser is null"); //NOI18N
108 } else if (event.getLoggedInUser().getUserId() == null) {
110 throw new NullPointerException("event.loggedInUser.userId is null"); //NOI18N
111 } else if (event.getLoggedInUser().getUserId() < 1) {
113 throw new IllegalArgumentException(MessageFormat.format("userId of user={0} is not valid: {1}", event.getLoggedInUser(), event.getLoggedInUser().getUserId())); //NOI18N
116 // Is the locale set?
117 if (event.getLoggedInUser().getUserLocale() instanceof Locale) {
119 final Locale userLocale = event.getLoggedInUser().getUserLocale();
122 this.changeLocale(userLocale, Boolean.TRUE);
127 * Event observer for logged-out user
129 * @param event Event instance
131 public void afterUserLogoutEvent (@Observes final ObservableUserLogoutEvent event) {
132 // Event and contained entity instance should not be null
135 throw new NullPointerException("event is null"); //NOI18N
136 } else if (event.getLoggedOutUser() == null) {
138 throw new NullPointerException("event.loggedOutUser is null"); //NOI18N
139 } else if (event.getLoggedOutUser().getUserId() == null) {
141 throw new NullPointerException("event.loggedOutUser.userId is null"); //NOI18N
142 } else if (event.getLoggedOutUser().getUserId() < 1) {
144 throw new IllegalArgumentException(MessageFormat.format("userId of user={0} is not valid: {1}", event.getLoggedOutUser(), event.getLoggedOutUser().getUserId())); //NOI18N
147 // Clear this bean as well
152 * Changes locale in application
154 public void doChangeLocale () {
155 // Is locale code set?
156 if (this.getLocaleCode() == null) {
158 throw new NullPointerException("this.localeCode is null"); //NOI18N
159 } else if (this.getLocaleCode().isEmpty()) {
161 throw new IllegalArgumentException("this.localeCode is empty"); //NOI18N
164 // Default new locale is null, will be handled later
165 Locale newLocale = null;
167 // Iterate over whole map
168 for (final Map.Entry<String, Locale> entry : this.getSupportedLocales().entrySet()) {
169 final Locale foundLocale = entry.getValue();
171 // Does the language match?
172 if (Objects.equals(foundLocale.toString(), this.getLocaleCode())) {
173 // Is found, take it as request locale
174 newLocale = foundLocale;
179 // Clear locale code field
182 // Has a matching locale
183 if (null == newLocale) {
185 throw new NullPointerException("this.localeCode=" + this.getLocaleCode() + " cannot be found."); //NOI18N
189 this.changeLocale(newLocale, Boolean.TRUE);
192 NUMBER_FORMAT = NumberFormat.getNumberInstance(newLocale);
196 public String formatCurrency (final Float amount) {
198 return NUMBER_FORMAT.format(amount);
202 public Locale getLocale () {
209 * @param locale Locale
211 public void setLocale (final Locale locale) {
212 this.locale = locale;
216 * Getter for localeCode code
218 * @return Language code
220 public String getLocaleCode () {
221 return this.localeCode;
225 * Setter for localeCode code
227 * @param localeCode Language code
229 public void setLocaleCode (final String localeCode) {
230 this.localeCode = localeCode;
234 * Getter for selectable localizations
236 * @return Selectable localizations
238 @SuppressWarnings ("ReturnOfCollectionOrArrayField")
239 public Map<String, Locale> getSupportedLocales () {
241 return this.supportedLocales;
245 * Initializer for this bean
248 public void init () {
249 // Get default locale
250 final Locale defaultLocale = FacesContext.getCurrentInstance().getApplication().getDefaultLocale();
253 this.getSupportedLocales().put(defaultLocale.toString(), defaultLocale);
255 // Get iterator from faces context
256 final Iterator<Locale> iterator = FacesContext.getCurrentInstance().getApplication().getSupportedLocales();
259 while (iterator.hasNext()) {
261 Locale supportedLocale = iterator.next();
264 this.getSupportedLocales().put(supportedLocale.toString(), supportedLocale);
267 // Get locale instance from request (e.g. browser)
268 Locale requestLocale = FacesContext.getCurrentInstance().getExternalContext().getRequestLocale();
270 // Is no country code found?
271 if (requestLocale.getCountry().isEmpty()) {
272 // Then try to find one, get language from it
273 final String language = requestLocale.getLanguage();
274 Boolean found = Boolean.FALSE;
276 // Iterate over whole map
277 for (final Map.Entry<String, Locale> entry : this.getSupportedLocales().entrySet()) {
278 final String languageCode = entry.getKey();
279 final Locale foundLocale = entry.getValue();
281 // Does the language match?
282 if (languageCode.startsWith(language)) {
283 // Is found, take it as request locale
284 requestLocale = foundLocale;
285 found = Boolean.TRUE;
292 // Then set default locale
293 requestLocale = defaultLocale;
297 // Change locale, may set same back in faces context, but triggers event
298 this.changeLocale(requestLocale, Boolean.FALSE);
300 // Initial formatting, may change when user chooses other locale
301 NUMBER_FORMAT = NumberFormat.getNumberInstance(this.locale);
305 * Changes current locale in this controller and faces context to given.
306 * This method makes sure that locales with at least language and country
307 * information are being changed to.
309 * @param locale New locale to set
310 * @param notifyBeans Whether to notify other beans
312 private void changeLocale (final Locale locale, final Boolean notifyBeans) {
313 // Is the locale language_country at least?
314 if (null == locale) {
316 throw new NullPointerException("locale is null"); //NOI18N
317 } else if (!locale.toString().contains("_")) { //NOI18N
319 throw new IllegalArgumentException(MessageFormat.format("locale={0} does not have country information set.", locale)); //NOI18N
322 // Set locale + code here
323 this.setLocale(locale);
324 this.setLocaleCode(locale.toString());
326 // Inform faces context
327 FacesContext.getCurrentInstance().getViewRoot().setLocale(locale);
329 // Notify other beans?
332 this.localeChangeEvent.fire(new LocaleChangeEvent(locale));
339 private void clear () {
341 this.setLocaleCode(null);
342 this.setLocale(null);