LocaleContextHelper.java

package org.gringlobal.util;

import java.util.Locale;
import java.util.TimeZone;
import java.util.concurrent.Callable;

import org.gringlobal.model.SysUser;
import org.springframework.context.i18n.LocaleContextHolder;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class LocaleContextHelper {
  
	/** Run something with a custom locale and timezone */
	public static <X> X withLocaleAndTimezone(Locale locale, TimeZone timeZone, Callable<X> callable) throws Exception {
		var prevLocale = LocaleContextHolder.getLocale();
		var prevTz = LocaleContextHolder.getTimeZone();
		try {
			log.debug("Using {} {}", locale.getLanguage(), timeZone.getDisplayName());
			LocaleContextHolder.setLocale(locale);
			LocaleContextHolder.setTimeZone(timeZone);
			return callable.call();
		} finally {
			log.debug("Restoring {} {}", prevLocale.getLanguage(), prevTz.getDisplayName());
			LocaleContextHolder.setLocale(prevLocale);
			LocaleContextHolder.setTimeZone(prevTz);
		}
	}

  /** Get sysUser's locale */
  public static Locale getLocale(SysUser sysUser) {
		if (sysUser.getCooperator() == null) return LocaleContextHolder.getLocale();
		if (sysUser.getCooperator().getSysLang() == null) return LocaleContextHolder.getLocale();
		return sysUser.getCooperator().getSysLang().toLocale();
	}

}