com.dahua.eco.base.spring.i18n.DahuaResource Maven / Gradle / Ivy
package com.dahua.eco.base.spring.i18n;
import com.dahua.eco.base.spring.utils.RequestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.NoSuchMessageException;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.util.StringUtils;
import java.io.IOException;
import java.util.*;
public class DahuaResource extends ReloadableResourceBundleMessageSource {
private Logger logger = LoggerFactory.getLogger(DahuaResource.class);
// 国际化资源文件基础目录(基于classpath)
private final static String I18N_RESOURCE_BASE_DIR = "i18n";
/**
* 国际化资源文件,时间参数为s,如果配置为-1 则为永不刷新,需要项目重启刷新
*/
private final static int CACHESECONDS = -1;
/**
* 配置国际化参数-文件路径和刷新时间
*/
public DahuaResource() {
super();
I18nResourceProcessor processor = new I18nResourceProcessor();
String[] baseNames = null;
try {
baseNames = processor.getAllBaseNames(I18N_RESOURCE_BASE_DIR);
this.setBasenames(baseNames);
} catch (IOException e) {
logger.error("parse i18n resource failed", e);
}
this.setCacheSeconds(CACHESECONDS);
}
/**
* 获取国际化后信息
*
* Locale信息默认从请求request中获取
*
* @param messageKey
* @param args
* @return
*/
public String getLocalMessage(String messageKey, Object... args) {
String localMessage = "";
try {
localMessage = getMessage(messageKey, args, RequestUtils.getLocale());
} catch (NoSuchMessageException e) {
logger.error("get i18n resource failed: key = {}", messageKey);
}
return StringUtils.isEmpty(localMessage) ? messageKey : localMessage;
}
/**
* 获取国际化后信息
*
* @param messageKey
* @param locale
* @param args
* @return
*/
public String getLocalMessage(String messageKey, Locale locale, Object... args) {
String localMessage = "";
try {
localMessage = getMessage(messageKey, args, locale);
} catch (NoSuchMessageException e) {
logger.error("get i18n resource failed: key = {}", messageKey);
}
return StringUtils.isEmpty(localMessage) ? messageKey : localMessage;
}
/**
* 获取properties 文件
*
* @param locale
* @return
*/
public Properties getProperties(Locale locale) {
return super.getMergedProperties(locale).getProperties();
}
public Map getPropertiesFlip(Locale locale) {
Map stringMap = new HashMap<>(16);
Properties properties = this.getProperties(locale);
Set> maps = properties.entrySet();
for (Map.Entry