Skip to content

Commit

Permalink
optimize notice template (#1301)
Browse files Browse the repository at this point in the history
  • Loading branch information
Eden4701 authored and ruanliang-hualun committed Oct 26, 2023
1 parent 0436aef commit 21e16f2
Show file tree
Hide file tree
Showing 37 changed files with 231 additions and 293 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,8 @@
import static io.swagger.v3.oas.annotations.media.Schema.AccessMode.READ_WRITE;

/**
* Notification strategy entity
* 通知策略
* Notification template entity
* 通知模版
*
* @author eden4701
*/
Expand Down Expand Up @@ -78,9 +78,8 @@ public class NoticeTemplate {
@Schema(title = "Is it a preset template: true- preset template false- custom template.",
description = "是否为预设模板: true-预设模板 false-自定义模板",
accessMode = READ_WRITE)
@NotNull
private Boolean presetTemplate;

@Column(columnDefinition = "boolean default false")
private boolean preset = false;

@Schema(title = "Template content",
description = "模板内容",
Expand All @@ -93,8 +92,8 @@ public class NoticeTemplate {
"${contentLabel} : ${content}", accessMode = READ_WRITE)
@Length(max = 100000)
@NotBlank
@Column(name = "template_content", columnDefinition = "MEDIUMTEXT")
private String templateContent;
@Column(name = "content", columnDefinition = "MEDIUMTEXT")
private String content;

@Schema(title = "The creator of this record", description = "此条记录创建者", example = "tom", accessMode = READ_ONLY)
@CreatedBy
Expand Down
Empty file modified home/static/img/home/3.png
100755 → 100644
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Empty file modified home/static/img/home/5.png
100755 → 100644
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Original file line number Diff line number Diff line change
Expand Up @@ -27,12 +27,12 @@
import org.dromara.hertzbeat.common.support.event.SystemConfigChangeEvent;
import org.dromara.hertzbeat.common.util.ResourceBundleUtil;
import org.dromara.hertzbeat.manager.component.alerter.AlertNotifyHandler;
import org.dromara.hertzbeat.manager.service.NoticeConfigService;
import org.springframework.context.event.EventListener;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.time.Instant;
import java.time.ZoneId;
Expand All @@ -54,16 +54,17 @@ abstract class AbstractAlertNotifyHandlerImpl implements AlertNotifyHandler {
protected ResourceBundle bundle = ResourceBundleUtil.getBundle("alerter");
@Resource
protected RestTemplate restTemplate;

@Resource
protected AlerterProperties alerterProperties;
@Resource
protected NoticeConfigService noticeConfigService;


protected String renderContent(NoticeTemplate noticeTemplate, Alert alert) throws TemplateException, IOException {

StringTemplateLoader stringLoader = new StringTemplateLoader();
freemarker.template.Template templateRes = null;
Configuration cfg = new Configuration();
freemarker.template.Template templateRes;
Configuration cfg = new Configuration(Configuration.VERSION_2_3_0);
Map<String, String> model = new HashMap<>(16);
model.put("title", bundle.getString("alerter.notify.title"));

Expand All @@ -89,16 +90,16 @@ protected String renderContent(NoticeTemplate noticeTemplate, Alert alert) throw
model.put("contentLabel", bundle.getString("alerter.notify.content"));
model.put("content", alert.getContent());
if (noticeTemplate == null) {
String path = this.getClass().getResource("/").getPath();
cfg.setDirectoryForTemplateLoading(new File(path + "templates/"));
cfg.setDefaultEncoding("utf-8");
templateRes = cfg.getTemplate(templateName() + ".txt");
} else {
String templateName = "freemakerTemplate";
stringLoader.putTemplate(templateName, noticeTemplate.getTemplateContent());
cfg.setTemplateLoader(stringLoader);
templateRes = cfg.getTemplate(templateName, Locale.CHINESE);
noticeTemplate = noticeConfigService.getDefaultNoticeTemplateByType(type());
}
if (noticeTemplate == null) {
log.error("{} does not have mapping default notice template. type: {}.", templateName(), type());
throw new NullPointerException(type() + " does not have mapping default notice template");
}
String templateName = "freeMakerTemplate";
stringLoader.putTemplate(templateName, noticeTemplate.getContent());
cfg.setTemplateLoader(stringLoader);
templateRes = cfg.getTemplate(templateName, Locale.CHINESE);
String template = FreeMarkerTemplateUtils.processTemplateIntoString(templateRes, model);
return template.replaceAll("((\r\n)|\n)[\\s\t ]*(\\1)+", "$1");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@
import org.dromara.hertzbeat.common.entity.manager.NoticeReceiver;
import org.dromara.hertzbeat.common.entity.manager.NoticeRule;
import org.dromara.hertzbeat.common.entity.manager.NoticeTemplate;
import org.dromara.hertzbeat.common.util.Pair;
import org.dromara.hertzbeat.manager.service.NoticeConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
Expand All @@ -33,13 +32,7 @@

import javax.persistence.criteria.Predicate;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import static org.dromara.hertzbeat.common.constants.CommonConstants.FAIL_CODE;
Expand Down Expand Up @@ -171,7 +164,7 @@ public ResponseEntity<Message<Void>> deleteNoticeTemplate(
// Returns success if it does not exist or if the deletion is successful
// todo 不存在或删除成功都返回成功
Optional<NoticeTemplate> noticeTemplate = noticeConfigService.getNoticeTemplatesById(templateId);
if (noticeTemplate == null) {
if (noticeTemplate.isEmpty()) {
return ResponseEntity.ok(Message.success("The specified notification template could not be queried, please check whether the parameters are correct"));
}
noticeConfigService.deleteNoticeTemplate(templateId);
Expand All @@ -182,7 +175,7 @@ public ResponseEntity<Message<Void>> deleteNoticeTemplate(
@Operation(summary = "Get a list of message notification templates based on query filter items",
description = "根据查询过滤项获取消息通知模板列表")
public ResponseEntity<Message<List<NoticeTemplate>>> getTemplates(
@Parameter(description = "en: Template name,zh: 模板名称,模糊查询", example = "rule1") @RequestParam(required = false) final String name) {
@Parameter(description = "Template name | 模板名称,模糊查询", example = "rule1") @RequestParam(required = false) final String name) {

Specification<NoticeTemplate> specification = (root, query, criteriaBuilder) -> {
Predicate predicate = criteriaBuilder.conjunction();
Expand All @@ -197,30 +190,6 @@ public ResponseEntity<Message<List<NoticeTemplate>>> getTemplates(
return ResponseEntity.ok(message);
}

@GetMapping(path = "/default_templates")
@Operation(summary = "Get a list of message notification templates based on query filter items",
description = "根据查询过滤项获取预设消息通知模板列表")
public ResponseEntity<Message<List<NoticeTemplate> >> getDefaultTemplates(
@Parameter(description = "en: Template name,zh: 模板名称,模糊查询", example = "rule1") @RequestParam(required = false) final String name) throws IOException {
List<NoticeTemplate> defaultTemplatePage=new ArrayList<>();
Long intitId=1000L;
String path="manager/src/main/resources/templates/";
File file = new File(path);
String[] fs=file.list();
for(String f:fs){
NoticeTemplate tmp=new NoticeTemplate();
tmp.setId(intitId);
tmp.setName(f.replace(".txt", "").replace(".html", ""));
tmp.setPresetTemplate(true);
tmp.setTemplateContent(Files.readString(Paths.get(path+f)));
intitId++;
defaultTemplatePage.add(tmp);
}

Message<List<NoticeTemplate> > message = Message.success(defaultTemplatePage);
return ResponseEntity.ok(message);
}

@PostMapping(path = "/receiver/send-test-msg")
@Operation(summary = "Send test msg to receiver", description = "给指定接收人发送测试消息")
public ResponseEntity<Message<Void>> sendTestMsg(@Valid @RequestBody NoticeReceiver noticeReceiver) {
Expand All @@ -230,4 +199,4 @@ public ResponseEntity<Message<Void>> sendTestMsg(@Valid @RequestBody NoticeRecei
}
return ResponseEntity.ok(Message.fail(FAIL_CODE, "Notify service not available, please check config!"));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,14 +27,6 @@
* @author Eden
*/
public interface NoticeTemplateDao extends JpaRepository<NoticeTemplate, Long>, JpaSpecificationExecutor<NoticeTemplate> {
/**
* 通过模板类型和预设模板标识查找通知模板
*
* @param type Byte type 模板类型
* @param defaultTemplate Boolean defaultTemplate 预设模板标识
* @return 通知模板
*/
NoticeTemplate findNoticeTemplateByTypeAndPresetTemplate(Byte type, Boolean defaultTemplate);



}
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,6 @@ public interface NoticeConfigService {
* @return Search result 查询结果
*/
List<NoticeReceiver> getNoticeReceivers(Specification<NoticeReceiver> specification);
// Map<NoticeReceiver,NoticeTemplate> getNoticeReceiversAndTemplate(Specification<NoticeReceiver> specification);

/**
* Dynamic conditional query
Expand Down Expand Up @@ -190,16 +189,14 @@ public interface NoticeConfigService {
Optional<NoticeTemplate> getNoticeTemplatesById(Long templateId);

/**
* Query specific notification templates according to the template type and default
* 根据模板类型和预设模板标识查询具体通知规则
* Query specific notification templates according to the template type
* 根据模板类型查询具体模版
*
* @param type Template type 模板类型
* @param defaultTemplate Preset template identification 预设模板标识
* @return Notification Template Entity 通知模板实体
*/
NoticeTemplate findNoticeTemplateByTypeAndDefault(Byte type, Boolean defaultTemplate);


NoticeTemplate getDefaultNoticeTemplateByType(Byte type);

/**
* alert Send test message
* 告警 发送测试消息
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,16 +24,16 @@
import org.dromara.hertzbeat.common.entity.alerter.Alert;
import org.dromara.hertzbeat.common.constants.CommonConstants;
import org.dromara.hertzbeat.common.entity.manager.NoticeTemplate;
import org.dromara.hertzbeat.common.support.event.SystemConfigChangeEvent;
import org.dromara.hertzbeat.common.util.ResourceBundleUtil;
import org.dromara.hertzbeat.manager.service.MailService;
import lombok.extern.slf4j.Slf4j;
import org.dromara.hertzbeat.manager.service.NoticeConfigService;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
Expand All @@ -44,7 +44,6 @@
*
* @author 花城
* @version 1.0
*
*/
@Slf4j
@Service
Expand All @@ -53,53 +52,59 @@ public class MailServiceImpl implements MailService {
@Resource
private AlerterProperties alerterProperties;

@Resource
protected NoticeConfigService noticeConfigService;

private ResourceBundle bundle = ResourceBundleUtil.getBundle("alerter");

@Override
public String buildAlertHtmlTemplate(final Alert alert, NoticeTemplate noticeTemplate) throws IOException, TemplateException {
freemarker.template.Template templateMail=null;
Configuration cfg = new Configuration();
freemarker.template.Template templateMail = null;
Configuration cfg = new Configuration(Configuration.VERSION_2_3_0);
String monitorId = null;
String monitorName = null;
if (alert.getTags() != null) {
monitorId = alert.getTags().get(CommonConstants.TAG_MONITOR_ID);
monitorName = alert.getTags().get(CommonConstants.TAG_MONITOR_NAME);
}
monitorId = monitorId == null? "External Alarm, No ID" : monitorId;
monitorName = monitorName == null? "External Alarm, No Name" : monitorName;
monitorId = monitorId == null ? "External Alarm, No ID" : monitorId;
monitorName = monitorName == null ? "External Alarm, No Name" : monitorName;
// Introduce thymeleaf context parameters to render pages
Map<String, String> model = new HashMap<>(16);
model.put("nameTitle", bundle.getString("alerter.notify.title"));
model.put("nameMonitorId", bundle.getString("alerter.notify.monitorId"));
model.put("nameMonitorName", bundle.getString("alerter.notify.monitorName"));
model.put("target", alert.getTarget());
model.put("nameTitle", bundle.getString("alerter.notify.title"));
model.put("nameMonitorId", bundle.getString("alerter.notify.monitorId"));
model.put("nameMonitorName", bundle.getString("alerter.notify.monitorName"));
model.put("target", alert.getTarget());
model.put("monitorId", monitorId);
model.put("monitorName", monitorName);
model.put("nameTarget", bundle.getString("alerter.notify.target"));
model.put("nameConsole", bundle.getString("alerter.notify.console"));
model.put("namePriority", bundle.getString("alerter.notify.priority"));
model.put("priority", bundle.getString("alerter.priority." + alert.getPriority()));
model.put("monitorName", monitorName);
model.put("nameTarget", bundle.getString("alerter.notify.target"));
model.put("nameConsole", bundle.getString("alerter.notify.console"));
model.put("namePriority", bundle.getString("alerter.notify.priority"));
model.put("priority", bundle.getString("alerter.priority." + alert.getPriority()));
model.put("nameTriggerTime", bundle.getString("alerter.notify.triggerTime"));
model.put("consoleUrl", alerterProperties.getConsoleUrl());
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String triggerTime = simpleDateFormat.format(new Date(alert.getLastAlarmTime()));
model.put("lastTriggerTime",triggerTime);
model.put("lastTriggerTime", triggerTime);
model.put("nameContent", bundle.getString("alerter.notify.content"));
model.put("content", alert.getContent());
if(noticeTemplate==null){
String path = this.getClass().getResource("/").getPath();
cfg.setDirectoryForTemplateLoading(new File(path+"templates/"));
cfg.setDefaultEncoding("utf-8");
templateMail = cfg.getTemplate("mailAlarm.html");
if (noticeTemplate == null) {
noticeTemplate = noticeConfigService.getDefaultNoticeTemplateByType((byte)1);
}
else {
StringTemplateLoader stringLoader = new StringTemplateLoader();
String templateName = "mailTemplate";
stringLoader.putTemplate(templateName, noticeTemplate.getTemplateContent());
cfg.setTemplateLoader(stringLoader);
templateMail= cfg.getTemplate(templateName, Locale.CHINESE);
if (noticeTemplate == null) {
throw new NullPointerException("email does not have mapping default notice template");
}
String template = FreeMarkerTemplateUtils.processTemplateIntoString(templateMail, model);
return template;
StringTemplateLoader stringLoader = new StringTemplateLoader();
String templateName = "mailTemplate";
stringLoader.putTemplate(templateName, noticeTemplate.getContent());
cfg.setTemplateLoader(stringLoader);
templateMail = cfg.getTemplate(templateName, Locale.CHINESE);
return FreeMarkerTemplateUtils.processTemplateIntoString(templateMail, model);
}

@EventListener(SystemConfigChangeEvent.class)
public void onEvent(SystemConfigChangeEvent event) {
log.info("{} receive system config change event: {}.", this.getClass().getName(), event.getSource());
this.bundle = ResourceBundleUtil.getBundle("alerter");
}
}
Loading

0 comments on commit 21e16f2

Please sign in to comment.