refactor: 优化消息通知里的变量替换

This commit is contained in:
CaptainB 2021-12-22 16:37:34 +08:00 committed by 刘瑞斌
parent aa7a4c03e0
commit 77602e8122
1 changed files with 22 additions and 21 deletions

View File

@ -19,11 +19,10 @@ import io.metersphere.track.service.TestCaseReviewService;
import io.metersphere.track.service.TestCaseService; import io.metersphere.track.service.TestCaseService;
import io.metersphere.track.service.TestPlanService; import io.metersphere.track.service.TestPlanService;
import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.RegExUtils;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils; import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.text.StringSubstitutor;
import org.springframework.context.annotation.Lazy; import org.springframework.context.annotation.Lazy;
import javax.annotation.Resource; import javax.annotation.Resource;
@ -128,29 +127,31 @@ public abstract class AbstractNoticeSender implements NoticeSender {
} }
protected String getContent(String template, Map<String, Object> context) { protected String getContent(String template, Map<String, Object> context) {
if (MapUtils.isNotEmpty(context)) { // 处理 null
for (String k : context.keySet()) { context.forEach((k, v) -> {
if (context.get(k) != null) { if (v == null) {
String value = handleTime(k, context); context.put(k, "");
template = RegExUtils.replaceAll(template, "\\$\\{" + k + "}", value);
} else {
template = RegExUtils.replaceAll(template, "\\$\\{" + k + "}", "");
}
} }
} });
return template; // 处理时间格式的数据
handleTime(context);
StringSubstitutor sub = new StringSubstitutor(context);
return sub.replace(template);
} }
private String handleTime(String k, Map<String, Object> context) { private void handleTime(Map<String, Object> context) {
String value = context.get(k).toString(); context.forEach((k, v) -> {
if (StringUtils.endsWithIgnoreCase(k, "Time")) { if (StringUtils.endsWithIgnoreCase(k, "Time")) {
try { try {
long time = Long.parseLong(value); String value = v.toString();
value = DateFormatUtils.format(time, "yyyy-MM-dd HH:mm:ss"); long time = Long.parseLong(value);
} catch (Exception ignore) { v = DateFormatUtils.format(time, "yyyy-MM-dd HH:mm:ss");
context.put(k, v);
} catch (Exception ignore) {
}
} }
} });
return value;
} }
protected List<UserDetail> getUserDetails(List<String> userIds) { protected List<UserDetail> getUserDetails(List<String> userIds) {