fi.evolver.ai.vaadin.translations.SessionLocaleConfigurator Maven / Gradle / Ivy
package fi.evolver.ai.vaadin.translations;
import java.io.Serial;
import java.util.Locale;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.vaadin.flow.i18n.I18NProvider;
import com.vaadin.flow.server.UIInitEvent;
import com.vaadin.flow.server.UIInitListener;
import com.vaadin.flow.server.VaadinService;
import fi.evolver.ai.vaadin.UserProfileService;
import fi.evolver.ai.vaadin.entity.UserProfile;
import fi.evolver.utils.string.StringUtils;
@Component
public class SessionLocaleConfigurator implements UIInitListener {
@Serial
private static final long serialVersionUID = 1L;
private static final Logger LOG = LoggerFactory.getLogger(SessionLocaleConfigurator.class);
@Value("${vaadin.default-language:AUTO}")
private String defaultLanguageCode;
@Autowired
private I18NProvider i18nProvider;
@Autowired
private UserProfileService userProfileService;
@Override
public void uiInit(UIInitEvent event) {
LOG.trace("Initializing UI");
String langCode = defaultLanguageCode;
// Check if a user is logged in and has a language set
UserProfile user = userProfileService.fetchUserProfile();
if (user != null && StringUtils.hasText(user.getLanguage()))
langCode = user.getLanguage();
Locale locale = null;
if ("AUTO".equals(langCode)) {
LOG.trace("Trying to get requested locale");
try {
// Try to get the Accept-Language header
locale = VaadinService.getCurrentRequest().getLocale();
LOG.trace("Got {} from request", locale.toString());
if (!isLocaleSupported(locale))
locale = null; // Don't use unsupported languages
}
catch (Exception e) {
locale = null;
}
if (locale == null) {
LOG.trace("Trying to get browser locale");
try {
// Try to get the browser locale
locale = event.getUI().getSession().getBrowser().getLocale();
LOG.trace("Got {} from browser", locale.toString());
if (!isLocaleSupported(locale))
locale = null;
}
catch (Exception e) {
locale = null;
}
}
}
else {
try {
locale = Locale.forLanguageTag(langCode);
if (!isLocaleSupported(locale))
locale = null;
}
catch (Exception e) {
locale = null;
}
}
if (locale == null) {
LOG.trace("Defaulting to english");
locale = Locale.ENGLISH;
}
LOG.debug("Setting UI locale to {}", locale.toString());
event.getUI().setLocale(locale);
}
private boolean isLocaleSupported(final Locale locale) {
return locale != null
&& i18nProvider != null
&& i18nProvider.getProvidedLocales()
.stream()
.anyMatch(l -> locale.getLanguage().equals(l.getLanguage()));
}
}