I18NAction.java
package com.mycim.webapp.actions.i18n;
import com.fa.sesa.i18n.I18nService;
import com.fa.sesa.i18n.I18nUtils;
import com.fa.sesa.i18n.Languages;
import com.mycim.framework.cache.utils.CacheUtils;
import com.mycim.framework.context.spring.SpringContext;
import com.mycim.framework.utils.lang.StringUtils;
import com.mycim.framework.utils.lang.collections.CollectionUtils;
import com.mycim.framework.utils.lang.collections.MapUtils;
import com.mycim.webapp.actions.AbstractAction;
import com.mycim.webapp.forms.I18nForm;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author Johnson Wang
* @date 2019/8/10 15:51
**/
public class I18NAction extends AbstractAction {
private I18nService i18nService = SpringContext.getBean(I18nService.class);
@Override
public ActionForward init(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) {
return null;
}
public Map<String, String> initLabelsForJs(I18nForm theForm) {
Languages language = I18nUtils.getCurrentLanguage();
Map<String, String> result;
ServletContext context = this.getServlet().getServletContext();
String version = StringUtils.toString(context.getAttribute("version"));
String cacheKey = "I18N_" + language.name() + "_" + version;
result = (Map<String, String>) CacheUtils.get(cacheKey);
Map labels = theForm.getLabels();
int size = MapUtils.getIntValue(result, "size");
if (size != labels.size()) {
result = i18nService.getLabelsMap(language, labels);
CacheUtils.put(cacheKey, result);
}
return result;
}
public Map<String, String> getMessage(Map<String, Object> params) {
String messageId = MapUtils.getString(params, "id");
String defaultMessage = MapUtils.getString(params, "defaultMessage");
List<Object> args = (List<Object>) MapUtils.getObject(params, "args");
String msg = "";
String originalMsg = "";
msg = I18nUtils.getMessage(messageId, defaultMessage);
originalMsg = msg;
if (CollectionUtils.isNotEmpty(args)) {
msg = I18nUtils.getMessage(messageId, defaultMessage, args.toArray());
}
if (StringUtils.isEmpty(msg) || StringUtils.equals(StringUtils.STRING_NA, msg)) {
msg = "[" + messageId + "] Please configure the message!";
}
Map<String, String> data = new HashMap<>();
data.put("msg", msg);
data.put("originalMsg", originalMsg);
return data;
}
public String getLabelContent(I18nForm theForm) {
String labelId = theForm.getMessageId();
return I18nUtils.getLabel(labelId);
}
}