Commit cd25d21c LN

增加资源翻译菜单及相关功能,

1 个父辈 d8145421
......@@ -224,12 +224,14 @@ public class DataInitManager {
Menu sysSetting = new Menu(new ArrayList<Menu>(), 1, "barcode", "条码设置", 1, "barcodeSetting", "system/barcodeSetting/index", "", 0, "database");
Menu outSet = new Menu(new ArrayList<Menu>(), 1, "outSetting", "出库策略", 1, "outSetting", "system/outSetting/index", "", 0, "outSet");
Menu sysSet = new Menu(new ArrayList<Menu>(), 1, "sysSetting", "系统设置", 1, "sysSetting", "system/sysSetting/index", "", 0, "sysSet");
Menu translationSet = new Menu(new ArrayList<Menu>(), 1, "translation", "资源翻译", 1, "translation", "system/translation/index", "", 0, "sysSet");
menuMenu.setHidden(true);
outSet.setHidden(true);
sysSet.setHidden(true);
// menuMenu.setHidden(true);
// sysSetting.setHidden(true);
menus.addAll(createMenus(poutSet, menuStorage, menuStoragePos, menuMenu, sysSetting,outSet,sysSet));
menus.addAll(createMenus(poutSet, menuStorage, menuStoragePos, menuMenu, sysSetting,outSet,sysSet,translationSet));
//用户管理:用户管理,角色管理
......
package com.neotel.smfcore.core.language.rest;
import com.alibaba.fastjson.JSONObject;
import com.neotel.smfcore.common.bean.PageData;
import com.neotel.smfcore.common.bean.ResultBean;
import com.neotel.smfcore.common.exception.ValidateException;
import com.neotel.smfcore.common.utils.FileUtil;
import com.neotel.smfcore.common.utils.QueryHelp;
import com.neotel.smfcore.core.language.rest.bean.dto.LanguageMsgDto;
import com.neotel.smfcore.core.language.rest.bean.mapstruct.LanguageMsgMapper;
import com.neotel.smfcore.core.language.rest.bean.query.LanguageMsgCriteria;
import com.neotel.smfcore.core.language.service.bean.Content;
import com.neotel.smfcore.core.language.service.nanager.ILanguageMsgManager;
import com.neotel.smfcore.core.language.service.po.LanguageMsg;
import com.neotel.smfcore.core.language.util.MessageUtils;
import com.neotel.smfcore.security.bean.FileProperties;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;
@Slf4j
@RestController
@RequiredArgsConstructor
@Api(tags = "设置:资源翻译")
@RequestMapping("api/translation")
public class LanguageMsgController {
@Autowired
ILanguageMsgManager languageMsgManager;
@Autowired
LanguageMsgMapper languageMsgMapper;
@Autowired
private final FileProperties properties;
@ApiOperation("导出数据")
@GetMapping(value = "/download")
public void download(HttpServletResponse response, LanguageMsgCriteria criteria) throws Exception {
Query query = QueryHelp.getQuery(criteria);
if (criteria.getTranslationState() != null) {
if (criteria.getTranslationState() == 1) {
// db.getCollection('languageMsg').find({contentList:{$elemMatch:{lanCode:"en-US"}}})
// query.addCriteria(Criteria.where("contentList").elemMatch(Criteria.where("lanCode").is(MessageUtils.EN_US)));
// db.getCollection('languageMsg').find({contentList:{"$size":4}})
query.addCriteria(Criteria.where("contentList").size(4));
} else if (criteria.getTranslationState() == 2) {
// db.getCollection("Array").find({ $where: "this.vendor.length <= 0" })//数组length<= 0
query.addCriteria(Criteria.where("this.contentList.length").lt(4));
}
}
List<LanguageMsg> list = languageMsgManager.findByQuery(query);
//下载
languageMsgManager.download(list, response);
}
@ApiOperation("查询列表")
@GetMapping
@PreAuthorize("@el.check('translation')")
public PageData<LanguageMsgDto> query(LanguageMsgCriteria criteria, Pageable pageable){
List<String> typeList=languageMsgManager.findTypeList();
Query query= QueryHelp.getQuery(criteria);
if (criteria.getTranslationState() != null) {
if (criteria.getTranslationState() == 1) {
query.addCriteria(Criteria.where("contentList").size(4));
} else if (criteria.getTranslationState() == 2) {
query.addCriteria(Criteria.where("this.contentList.length").lte(3));
}
}
PageData<LanguageMsg> barcodes=languageMsgManager.findByPage(query,pageable);
List<LanguageMsgDto> barcodeDtos=languageMsgMapper.toDto(barcodes.getContent());
return new PageData(barcodeDtos,barcodes.getTotalElements());
}
@ApiOperation("新增资源")
@PostMapping
@PreAuthorize("@el.check('translation')")
public ResponseEntity<Object> create(@Validated @RequestBody LanguageMsgDto resources) {
LanguageMsg msg=languageMsgMapper.toEntity(resources);
languageMsgManager.saveMsg(msg);
return new ResponseEntity<>(HttpStatus.CREATED);
}
@ApiOperation("修改资源")
@PutMapping
@PreAuthorize("@el.check('translation')")
public ResponseEntity<Object> update(@Validated @RequestBody LanguageMsgDto resources) {
LanguageMsg msg=languageMsgMapper.toEntity(resources);
if (msg.getId() == null) {
throw new ValidateException("smfcode.valueCanotNull","{0}不能为空",new String[]{"ID"});
}
languageMsgManager.saveMsg(msg);
return new ResponseEntity<>(HttpStatus.OK);
}
@ApiOperation("删除资源")
@DeleteMapping
@PreAuthorize("@el.check('translation')")
public ResponseEntity<Object> delete(@RequestBody Set<String> ids) {
for (String id : ids) {
if (id == null) {
throw new ValidateException("smfcode.valueCanotNull","{0}不能为空",new String[]{"ID"} );
}
}
languageMsgManager.deleteMsgs(ids);
return new ResponseEntity<>(HttpStatus.OK);
}
@ApiOperation("获取资源类型集合")
@GetMapping(value = "/typeList")
@PreAuthorize("@el.check('translation')")
public List<String> getTypeList( ) {
List<String> typeList=languageMsgManager.findTypeList();
return typeList;
}
@ApiOperation("上传资源列表")
@PostMapping(value = "/upload")
public ResultBean upload(@RequestParam MultipartFile uploadFile) throws Exception {
// 验证文件上传的格式
String smfcodeType = "properties";
String smfclientType = "js";
String fileType = FileUtil.getExtensionName(uploadFile.getOriginalFilename());
if (fileType == null) {
throw new ValidateException("smfcode.feleFormatError", "文件格式错误!, 仅支持{0}格式", new String[]{smfclientType + "/" + smfcodeType});
}
if ((!smfclientType.contains(fileType)) && !smfcodeType.contains(fileType)) {
throw new ValidateException("smfcode.feleFormatError", "文件格式错误!, 仅支持{0}格式", new String[]{smfclientType + "/" + smfcodeType});
}
File folder = new File(properties.getPath(), "resource");
File file = FileUtil.upload(uploadFile, folder.getAbsolutePath());
String resultMsg = "";
String lanType = getLanTypeByFileName(uploadFile.getOriginalFilename());
if (smfclientType.contains(fileType)) {
//客户端js文件处理
Map<String, String> proMap = readJsFile(file);
resultMsg = ResourceUpload(uploadFile.getOriginalFilename(), proMap, lanType, "smfclient");
} else if (smfcodeType.contains(fileType)) {
Map<String, String> proMap = MessageUtils.ReadPropertiesFile(file);
resultMsg = ResourceUpload(uploadFile.getOriginalFilename(), proMap, lanType, "");
}
return ResultBean.newOkResult(resultMsg);
}
private String getLanTypeByFileName(String orgFilename) {
String tname = orgFilename.replace('_', '-');
if (tname.contains(MessageUtils.EN_US)) {
return MessageUtils.EN_US;
} else if (tname.contains(MessageUtils.JA_JP)) {
return MessageUtils.JA_JP;
} else if (tname.contains(MessageUtils.ZH_CH)) {
return MessageUtils.ZH_CH;
} else if (tname.contains(MessageUtils.ZH_TW)) {
return MessageUtils.ZH_TW;
}
return "";
}
private String ResourceUpload(String orgFileName,Map<String, String> proMap ,String lanCode, String type) {
List<LanguageMsg> newLanguageList = new ArrayList<>();
List<LanguageMsg> updateLanguageList = new ArrayList<>();
if (proMap != null && proMap.size() > 0) {
for (String key :
proMap.keySet()) {
String msgStr = proMap.get(key);
LanguageMsg msg = MessageUtils.getMsg(key);
if (msg == null) {
msg = new LanguageMsg(key, msgStr,"smfclient");
msg.setContent(lanCode, msgStr);
newLanguageList.add(msg);
} else {
String oldMsg = msg.getContent(lanCode);
if (!oldMsg.equals(msgStr)) {
msg.setContent(lanCode, msgStr);
updateLanguageList.add(msg);
languageMsgManager.save(msg);
MessageUtils.updateMsg(msg);
}
}
}
}
if (newLanguageList.size() > 0) {
languageMsgManager.insertAll(newLanguageList);
for (LanguageMsg msg :
newLanguageList) {
MessageUtils.updateMsg(msg);
}
}
log.info("导入资源文件[" + orgFileName + "]共更新[" + updateLanguageList.size() + "]条资源,新增[" + newLanguageList.size() + "]条资源");
return "ok";
}
private Map<String,String> readJsFile(File file){
Map<String,String> map=new HashMap<>();
// Long fileLengthLong = file.length();
// byte[] fileContent = new byte[fileLengthLong.intValue()];
// try {
// FileInputStream inputStream = new FileInputStream(file);
// inputStream.read(fileContent);
// inputStream.close();
// String string = new String(fileContent);
// JSONObject jsonObject= JSONObject.parseObject(string);
// for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
// System.out.println("key值="+entry.getKey());
// System.out.println("对应key值的value="+entry.getValue());
// }
// } catch (Exception e) {
// log.error("readJsFile 出错:"+e.toString());
// e.printStackTrace();
// }
try (FileInputStream fis = new FileInputStream(file.getPath());
InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
BufferedReader br = new BufferedReader(isr)
) {
String line;
//网友推荐更加简洁的写法
int lineIndex=0;
while ((line = br.readLine()) != null) {
if(lineIndex==0){
continue;
}
}
// JSONObject jsonObject= JSONObject.parseObject(br.toString());
// for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
// System.out.println("key值="+entry.getKey());
// System.out.println("对应key值的value="+entry.getValue());
// }
} catch (IOException e) {
log.error("readJsFile 出错:"+e.toString());
e.printStackTrace();
}
return map;
}
// //服务端properties文件处理
// private String propertiesResourceUpload(String orgFileName,File file) {
//
// String lanType = getLanTypeByFileName(orgFileName);
// List<LanguageMsg> newLanguageList = new ArrayList<>();
// List<LanguageMsg> updateLanguageList = new ArrayList<>();
//
// Map<String, String> proMap = MessageUtils.ReadPropertiesFile(file);
// if (proMap != null && proMap.size() > 0) {
// for (String key :
// proMap.keySet()) {
// String msgStr = proMap.get(key);
//
// LanguageMsg msg = MessageUtils.getMsg(key);
// if (msg == null) {
// msg = new LanguageMsg(key, msgStr,"");
// msg.setContent(lanType, msgStr);
// newLanguageList.add(msg);
// } else {
// String oldMsg = msg.getContent(lanType);
// if (!oldMsg.equals(msgStr)) {
// msg.setContent(lanType, msgStr);
// updateLanguageList.add(msg);
// languageMsgManager.save(msg);
// MessageUtils.updateMsg(msg);
// }
// }
// }
// }
//
// if (newLanguageList.size() > 0) {
// languageMsgManager.insertAll(newLanguageList);
// for (LanguageMsg msg :
// newLanguageList) {
// MessageUtils.updateMsg(msg);
// }
// }
// log.info("导入资源文件[" + orgFileName + "]共更新[" + updateLanguageList.size() + "]条资源,新增[" + newLanguageList.size() + "]条资源");
// return "ok";
// }
}
package com.neotel.smfcore.core.language.rest.bean.dto;
import com.google.common.collect.Lists;
import com.neotel.smfcore.core.language.service.bean.Content;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Data
public class LanguageMsgDto implements Serializable {
@ApiModelProperty(value = "ID")
private String id;
@ApiModelProperty("资源code")
private String code;
@ApiModelProperty("默认值,文本内容")
private String msg;
@ApiModelProperty("设备类型,一般为code的第一个单词,smfcode:服务器")
private String type;
@ApiModelProperty("存放翻译内容List")
private List<Content> contentList = Lists.newArrayList();
// private Map<String,String> contentMap=new HashMap<>();
//
//
// public List<Content> GetContentList(){
// List<Content> list=new ArrayList<>();
// for (String key :
// contentMap.keySet()) {
// list.add(new Content(key,contentMap.get(key)));
// }
// return list;
// }
}
package com.neotel.smfcore.core.language.rest.bean.mapstruct;
import com.neotel.smfcore.common.base.BaseMapper;
import com.neotel.smfcore.core.language.rest.bean.dto.LanguageMsgDto;
import com.neotel.smfcore.core.language.service.po.LanguageMsg;
import org.mapstruct.Mapper;
import org.mapstruct.ReportingPolicy;
@Mapper(componentModel = "spring" ,unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface LanguageMsgMapper extends BaseMapper<LanguageMsgDto, LanguageMsg> {
}
package com.neotel.smfcore.core.language.rest.bean.query;
import com.neotel.smfcore.common.annotation.QueryCondition;
import com.neotel.smfcore.common.bean.BetweenData;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;
import java.util.Date;
@Data
public class LanguageMsgCriteria {
@QueryCondition(blurry = "code,type,msg")
private String blurry;
@QueryCondition(type = QueryCondition.Type.BETWEEN, propName = "updateDate")
@DateTimeFormat(pattern = "yyyy-MM-dd")
private BetweenData<Date> createDate;
@QueryCondition
@ApiModelProperty("编号")
private String code;
@QueryCondition
@ApiModelProperty("类型")
private String type;
@QueryCondition
@ApiModelProperty("默认内容")
private String msg;
@ApiModelProperty("翻译状态,全部时不发,1=已完成,2=未完成")
private Integer translationState;
}
package com.neotel.smfcore.core.language.service.bean;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* Created by sunke on 2021/7/29.
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Content {
/**
......
package com.neotel.smfcore.core.language.service.dao;
import com.neotel.smfcore.common.base.IBaseDao;
public interface ILanguageMsgDao extends IBaseDao {
}
package com.neotel.smfcore.core.language.service.dao.impl;
import com.neotel.smfcore.common.base.AbstractBaseDao;
import com.neotel.smfcore.core.language.service.dao.ILanguageMsgDao;
import com.neotel.smfcore.core.language.service.po.LanguageMsg;
import org.springframework.stereotype.Service;
@Service
public class LanguageMsgDao extends AbstractBaseDao implements ILanguageMsgDao {
@Override
public Class getEntityClass() {
return LanguageMsg.class;
}
}
package com.neotel.smfcore.core.language.service.nanager;
import com.neotel.smfcore.common.base.IBaseManager;
import com.neotel.smfcore.core.language.service.po.LanguageMsg;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Set;
public interface ILanguageMsgManager extends IBaseManager<LanguageMsg> {
void download(List<LanguageMsg> list, HttpServletResponse response) throws IOException;
LanguageMsg saveMsg(LanguageMsg msg);
void deleteMsgs(Set<String> ids);
void insertAll(List<LanguageMsg> languageMsgs);
List<String> findTypeList();
}
package com.neotel.smfcore.core.language.service.nanager.impl;
import cn.hutool.core.util.ObjectUtil;
import com.neotel.smfcore.common.bean.PageData;
import com.neotel.smfcore.common.exception.ValidateException;
import com.neotel.smfcore.common.utils.FileUtil;
import com.neotel.smfcore.core.barcode.bean.PlateSizeBean;
import com.neotel.smfcore.core.barcode.service.po.Barcode;
import com.neotel.smfcore.core.language.service.bean.Content;
import com.neotel.smfcore.core.language.service.dao.ILanguageMsgDao;
import com.neotel.smfcore.core.language.service.nanager.ILanguageMsgManager;
import com.neotel.smfcore.core.language.service.po.LanguageMsg;
import com.neotel.smfcore.core.language.util.MessageUtils;
import com.neotel.smfcore.core.storage.service.po.StoragePos;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.KPropertyPathExtensionsKt;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
@Service
@Slf4j
public class LanguageMsgManagerImpl implements ILanguageMsgManager {
@Autowired
private ILanguageMsgDao languageMsgDao;
@Override
public LanguageMsg get(String id) {
return languageMsgDao.findOneById(id);
}
@Override
public LanguageMsg save(LanguageMsg object) throws ValidateException {
return languageMsgDao.save(object);
}
@Override
public void delete(LanguageMsg object) throws ValidateException {
languageMsgDao.removeOneById(object.getId());
}
@Override
public PageData<LanguageMsg> findByPage(Query query, Pageable pageable) {
int totalCount = languageMsgDao.countByQuery(query);
List<Barcode> barcodes = languageMsgDao.findByQuery(query, pageable);
return new PageData(barcodes, totalCount);
}
@Override
public List<LanguageMsg> findByQuery(Query query) {
return languageMsgDao.findByQuery(query);
}
@Override
public void download(List<LanguageMsg> msgList, HttpServletResponse response) throws IOException {
List<Map<String, Object>> list = new ArrayList<>();
for (LanguageMsg msg : msgList) {
Map<String, Object> map = new LinkedHashMap<>();
map.put("编号", msg.getCode());
map.put("类型", msg.getType());
map.put("默认值", msg.getMsg());
map.put("简体中文", msg.getContent(MessageUtils.ZH_CH));
map.put("繁体中文", msg.getContent(MessageUtils.ZH_TW));
map.put("英文", msg.getContent(MessageUtils.EN_US));
map.put("日文", msg.getContent(MessageUtils.JA_JP));
list.add(map);
}
FileUtil.downloadExcel(list, response);
}
@Override
public LanguageMsg saveMsg(LanguageMsg resources) {
if (resources.getCode() == null) {
throw new ValidateException("smfcode.valueCanotNull", "{0}不能为空", new String[]{"code"});
}
if (resources.getMsg() == null) {
throw new ValidateException("smfcode.valueCanotNull", "{0}不能为空", new String[]{"msg"});
}
if (resources.getType() == null) {
throw new ValidateException("smfcode.valueCanotNull", "{0}不能为空", new String[]{"type"});
}
if (resources.getContentList() == null) {
resources.setContentList(new ArrayList<>());
}
Criteria c = Criteria.where("code").is(resources.getCode());
String logName = "新增资源:";
if (resources.getId() != null) {
logName = "修改资源:";
c.and("id").ne(resources.getId());
} //code不能重复
LanguageMsg result = languageMsgDao.findOne(new Query(c));
if (result != null) {
throw new ValidateException("smfcode.resourcesExist", "资源[" + resources.getCode() + "]已存在");
}
Query query = new Query(c);
List<Content> list = new ArrayList<>();
for (Content con :
resources.getContentList()) {
if (ObjectUtil.isEmpty(con.getLanCode()) || ObjectUtil.isEmpty(con.getMsg())) {
continue;
}
list.add(con);
}
resources.setContentList(list);
LanguageMsg saveResult = languageMsgDao.save(resources);
MessageUtils.updateMsg(saveResult);
return saveResult;
}
@Override
public void deleteMsgs(Set<String> ids) {
Query query = new Query(Criteria.where("id").in(ids));
List<LanguageMsg> languageMsgs = languageMsgDao.findByQuery(query);
String delnames = "";
for (LanguageMsg msg :
languageMsgs) {
delnames += "[" + msg.getCode() + "_" + msg.getMsg() + "]";
MessageUtils.removeMsg(msg);
}
languageMsgDao.removeByQuery(query);
log.info("手动删除资源:" + delnames + "完成");
}
@Override
public void insertAll(List<LanguageMsg> languageMsgs) {
languageMsgDao.insertAll(languageMsgs);
}
@Override
public List<String> findTypeList() {
Aggregation agg = Aggregation.newAggregation(
Aggregation.match(Criteria.where("type").exists(true)),
Aggregation.group("type").first("type").as("type")
);
AggregationResults<MsgType> results = languageMsgDao.getMongoTemplate().aggregate(agg, LanguageMsg.class, MsgType.class);
List<MsgType> types = results.getMappedResults();
List<String> result = new ArrayList<>();
for (MsgType type :
types) {
result.add(type.getType());
}
return result;
}
@Data
private class MsgType {
private String type;
}
}
package com.neotel.smfcore.core.language.service.po;
import cn.hutool.core.util.ObjectUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.neotel.smfcore.common.base.BasePo;
......@@ -11,6 +12,7 @@ import org.springframework.data.annotation.Transient;
import org.springframework.data.mongodb.core.mapping.Document;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
......@@ -18,17 +20,37 @@ import java.util.Map;
@Document
public class LanguageMsg extends BasePo implements Serializable {
public LanguageMsg(){
}
public LanguageMsg(String code,String msg,String type) {
if (ObjectUtil.isEmpty(type)) {
int index = code.indexOf('.');
type = code.substring(0, index);
}
this.setUpdateDate(getCreateDate());
this.setCode(code);
this.setType(type);
this.setMsg(msg);
}
private String name;
/**
* 资源 code
*/
private String code;
/**
* 消息key,第一个.之前为设备名称
* 设备类型,一般为code的第一个单词
* smfcode:服务器
*
*/
private String key;
private String type;
/**
* 默认值
* 默认值,文本内容
*/
private String msg;
......@@ -37,4 +59,47 @@ public class LanguageMsg extends BasePo implements Serializable {
*/
private List<Content> contentList = Lists.newArrayList();
/**
* 查找指定语言的内容
* @param lanCode
* @return
*/
public String getContent(String lanCode) {
if(ObjectUtil.isEmpty(lanCode)){
return getMsg();
}
for (Content con :
contentList) {
if(con.getLanCode().equals(lanCode)){
return con.getMsg();
}
}
return "";
}
public void setContent(String lanCode, String lanMsg) {
if(ObjectUtil.isEmpty(lanCode)){
setMsg(lanCode);
return;
}
for (Content con :
contentList) {
if (con.getLanCode().equals(lanCode)) {
con.setMsg(lanMsg);
return;
}
}
Content content = new Content(lanCode, lanMsg);
contentList.add(content);
}
public Map<String,String> GetContentMap(){
HashMap<String,String> map=new HashMap<>();
for (Content c :
contentList) {
map.put(c.getLanCode(),c.getMsg());
}
return map;
}
}
package com.neotel.smfcore.core.language.util;
import cn.hutool.core.util.ObjectUtil;
import com.neotel.smfcore.core.language.service.bean.Content;
import com.neotel.smfcore.core.language.service.nanager.ILanguageMsgManager;
import com.neotel.smfcore.core.language.service.nanager.impl.LanguageMsgManagerImpl;
import com.neotel.smfcore.core.language.service.po.LanguageMsg;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.jni.Directory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.stereotype.Repository;
import javax.annotation.PostConstruct;
import java.io.*;
import java.text.MessageFormat;
import java.util.Locale;
import java.util.*;
/**
* 国际化工具类
* Created by sunke on 2021/7/30.
* 资源缓存
*/
@Component
@Slf4j
public class MessageUtils {
//-----------------以下为从配置文件读取资源-------------------------------------
public static Locale getDefaultLocal(){
return new Locale("zh-CH");
}
......@@ -47,4 +56,187 @@ public class MessageUtils {
}
}
//-------------------------------------------------------------------------------
/**
* key=code
*/
private static Map<String, LanguageMsg> msgMap = new HashMap<>();
@Autowired
ILanguageMsgManager languageMsgManager;
public static final String ZH_CH = "zh-CH";
public static final String ZH_TW = "zh-TW";
public static final String EN_US = "en-US";
public static final String JA_JP = "ja-JP";
@PostConstruct
public void initialize() {
initLanguageMsgList();
}
// public static Locale getDefaultLocal(){
// return new Locale("zh-CH");
// }
// public static String getText(String msgKey, Locale locale,String defaultMsg) {
// return getText(msgKey,null, locale,defaultMsg);
// }
//
// public static String getText(String msgKey, String[] params, Locale locale, String defaultMsg) {
// try{
// String msg=getMessage(msgKey,locale.toLanguageTag(),defaultMsg);
// if (params == null) {
// return msg;
// } else {
// return MessageFormat.format(msg,params);
// }
// }catch (Exception ex){
// log.error("获取资源["+msgKey+"]["+defaultMsg+"]["+locale.getLanguage()+"]出错:"+ex.toString());
// if(defaultMsg != null){
// return defaultMsg;
// }
// return msgKey;
// }
// }
private static String getMessage(String msgKey, String lanType, String defaultMsg) {
if (msgMap != null) {
LanguageMsg msg = msgMap.get(msgKey);
if (msg != null) {
for (Content con :
msg.getContentList()) {
String lanT = con.getLanCode();
if (lanT.equals(lanType)) {
return con.getMsg();
}
}
log.info("获取资源[" + msgKey + "][" + defaultMsg + "][" + lanType + "]失败:未找到code[" + msgKey + "]对应语言[" + lanType + "]");
return msg.getMsg();
}
log.info("获取资源[" + msgKey + "][" + defaultMsg + "][" + lanType + "]失败:未找到code[" + msgKey + "]");
}
return defaultMsg;
}
public static void updateMsg(LanguageMsg msg) {
msgMap.put(msg.getCode(), msg);
}
public static void removeMsg(LanguageMsg msg) {
msgMap.remove(msg.getCode());
}
public static LanguageMsg getMsg(String code) {
return msgMap.get(code);
}
private Map<String, LanguageMsg> loadMsgMap() {
Map<String, LanguageMsg> msgMap = new HashMap<>();
List<LanguageMsg> msgs = languageMsgManager.findByQuery(new Query());
for (LanguageMsg msg :
msgs) {
msgMap.put(msg.getCode(), msg);
}
log.info("MessageCache共加载到" + msgMap.size() + "条Msg");
return msgMap;
}
private void initLanguageMsgList() {
msgMap = loadMsgMap();
if (msgMap.size() > 0) {
return;
}
String fielPath = "D:\\resources";
File file = new File(fielPath); //需要获取的文件的路径
if (file.exists() && file.isDirectory()) {
String[] fileNameLists = file.list(); //存储文件名的String数组
File[] filePathLists = file.listFiles(); //存储文件路径的String数组
Map<String, String> defaultLanMap = new HashMap<>();
Map<String, Map<String, String>> lanMsgMap = new HashMap<>();
for (int i = 0; i < filePathLists.length; i++) {
if (filePathLists[i].isFile()) {
String fileName = filePathLists[i].getName();
if (fileName.endsWith(".properties")) {
String lanType = fileName.replace("messages", "").replace(".properties", "");
if (ObjectUtil.isEmpty(lanType)) {
defaultLanMap = ReadPropertiesFile(filePathLists[i]);
log.info("MessageCache 从文件[" + fileName + "]中导入[" + defaultLanMap.size() + "]条默认资源");
} else {
String lan = lanType.substring(1);
lan = lan.replace('_', '-');
Map<String, String> map = ReadPropertiesFile(filePathLists[i]);
lanMsgMap.put(lan, map);
log.info("MessageCache 从文件[" + fileName + "]中导入[" + defaultLanMap.size() + "]条[" + lan + "]资源");
}
}
}
}
List<LanguageMsg> languageMsgs = new ArrayList<>();
for (String code :
defaultLanMap.keySet()) {
String defMsg = defaultLanMap.get(code);
// int index = code.indexOf('.');
// String type = code.substring(0, index);
// LanguageMsg msg = new LanguageMsg();
// msg.setUpdateDate(msg.getCreateDate());
// msg.setCode(code);
// msg.setType(type);
// msg.setMsg(defMsg);
LanguageMsg msg = new LanguageMsg(code, defMsg, "");
for (String lan :
lanMsgMap.keySet()) {
if (lanMsgMap.get(lan).containsKey(code)) {
String lanMsg = lanMsgMap.get(lan).get(code);
msg.setContent(lan, lanMsg);
}
}
languageMsgs.add(msg);
}
languageMsgManager.insertAll(languageMsgs);
}
msgMap = loadMsgMap();
}
public static Map<String, String> ReadPropertiesFile(File file) {
Map<String, String> map = new HashMap<>();
try (FileInputStream fis = new FileInputStream(file.getPath());
InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
BufferedReader br = new BufferedReader(isr)
) {
String line;
//网友推荐更加简洁的写法
while ((line = br.readLine()) != null) {
// 一次读入一行数据
// System.out.println(line);
String[] array = line.split("=");
if (array.length == 2) {
map.put(array[0].trim(), array[1].trim());
}
}
} catch (IOException e) {
log.error("ReadPropertiesFile 出错:" + e.toString());
e.printStackTrace();
}
return map;
}
}
支持 Markdown 格式
你添加了 0 到此讨论。请谨慎行事。
Finish editing this message first!