Commit 6d70a0dc authored by 黎博's avatar 黎博

Merge branch 'master' into auto

# Conflicts:
#	pom.xml
parents 992765bf 3132ba91
......@@ -116,13 +116,6 @@
<version>4.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.testng/testng -->
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.3.0</version>
</dependency>
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
......
......@@ -28,7 +28,7 @@ public class HttpLogAspect {
private static final Logger logger = LoggerFactory.getLogger(HttpLogAspect.class);
@Pointcut("execution(public * cn.qg.holmes.controller..*.*(..))")
@Pointcut("execution(public * cn.qg.holmes.controller.mock..*(..))")
public void httpRequestLog() {}
/**
......
package cn.qg.holmes.config;
import cn.qg.holmes.interceptor.RuleEngineInterceptor;
import cn.qg.holmes.interceptor.YeebaoInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
......@@ -17,8 +18,14 @@ public class InterceptorConfig implements WebMvcConfigurer {
return new YeebaoInterceptor();
}
@Bean
public RuleEngineInterceptor ruleEngineInterceptor() {
return new RuleEngineInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(yeebaoInterceptor()).addPathPatterns("/mock/tzt-api/**", "/mock/balance-board/**");
registry.addInterceptor(ruleEngineInterceptor()).addPathPatterns("/rule_engine/**");
}
}
package cn.qg.holmes.controller.jira;
import cn.qg.holmes.common.JsonResult;
import cn.qg.holmes.entity.jira.DingRobot;
import cn.qg.holmes.service.jira.DingRobotService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.util.HashMap;
import java.util.Map;
@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/jira")
public class JiraWebhookController {
@Autowired
DingRobotService dingRobotService;
/**
* jira webhook
* @param request
*/
@PostMapping("/webhook")
public void jiraWebhook(HttpServletRequest request) {
try {
BufferedReader br = request.getReader();
StringBuilder jiraData = new StringBuilder();
String str = "";
while((str = br.readLine()) != null){
jiraData.append(str);
}
br.close();
dingRobotService.sendMsgToDing(String.valueOf(jiraData));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 项目机器人列表
* @param pageNum 第几页
* @param pageSize 每页多少个
* @return
*/
@GetMapping("/list/robot")
public JsonResult getProjectRobotList(Integer pageNum, Integer pageSize) {
IPage<DingRobot> page = new Page<>(pageNum, pageSize);
IPage<DingRobot> projectRobotIPage = dingRobotService.page(page);
Map<String, Object> map = new HashMap<>();
map.put("total", projectRobotIPage.getTotal());
map.put("list", projectRobotIPage.getRecords());
return JsonResult.buildSuccessResult(map);
}
/**
* 新增项目机器人
* @param dingRobot 项目机器人实体
* @return
*/
@PostMapping("/add/robot")
public JsonResult addProjectRobot(@RequestBody DingRobot dingRobot) {
if (dingRobot.getProjectName() == null) {
return JsonResult.buildErrorStateResult("项目名称不能为空!", false);
}
if (dingRobot.getDingUrl() == null) {
return JsonResult.buildErrorStateResult("钉钉url不能为空!", false);
}
return JsonResult.buildSuccessResult(dingRobotService.save(dingRobot));
}
/**
* 修改项目机器人
* @param dingRobot 项目机器人实体
* @return
*/
@PostMapping("/modify/robot")
public JsonResult editProjectRobot(@RequestBody DingRobot dingRobot) {
if (dingRobot.getId() == null) {
return JsonResult.buildErrorStateResult("id不能为空!", false);
}
if (dingRobot.getProjectName() == null) {
return JsonResult.buildErrorStateResult("项目名称不能为空!", false);
}
if (dingRobot.getDingUrl() == null) {
return JsonResult.buildErrorStateResult("钉钉url不能为空!", false);
}
return JsonResult.buildSuccessResult(dingRobotService.updateById(dingRobot));
}
/**
* 删除项目机器人
* @param projectRobotId 项目机器人实体id
* @return
*/
@GetMapping("/delete/robot")
public JsonResult deleteProjectRobot(Integer projectRobotId) {
if (dingRobotService.getById(projectRobotId) == null) {
return JsonResult.buildErrorStateResult("项目机器人不存在!", false);
}
return JsonResult.buildSuccessResult(dingRobotService.removeById(projectRobotId));
}
}
......@@ -43,7 +43,7 @@ public class MockController {
IPage<Mock> page = new Page<>(pageNum, pageSize);
IPage<Mock> pageEntity;
if (module != null) {
QueryWrapper queryWrapper = new QueryWrapper();
QueryWrapper<Mock> queryWrapper = new QueryWrapper();
queryWrapper.eq("module", module);
pageEntity = mockService.page(page, queryWrapper);
} else {
......
package cn.qg.holmes.entity.jira;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import java.util.Date;
@Data
@TableName(value = "ding_robot")
public class DingRobot {
@TableId(type = IdType.AUTO)
private Integer id;
private String projectName;
private String dingUrl;
private String creator;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date createTime;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date updateTime;
}
package cn.qg.holmes.interceptor;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class InterceptorUtils {
/**
* 修改返回响应
* @param response HttpServletResponse
* @param result 返回的json或字符串
*/
public static void constructResponse(HttpServletResponse response, String result) {
PrintWriter writer = null;
response.setCharacterEncoding("UTF-8");
// response.setContentType("application/json; charset=utf-8");
try {
writer = response.getWriter();
writer.print(result);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (writer != null) {
writer.close();
}
}
}
/**
* 修改返回响应
* @param response HttpServletResponse
* @param result 返回的json或字符串
* @param contentType content-type
*/
public static void constructResponse(HttpServletResponse response, String result, String contentType) {
PrintWriter writer = null;
response.setCharacterEncoding("UTF-8");
response.setContentType(contentType);
try {
writer = response.getWriter();
writer.print(result);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (writer != null) {
writer.close();
}
}
}
/**
* 将HttpServletRequest的parameterMap由Map<String, String[]>转换成Map<String, Object>
* @param parameterMap request.getParameterMap()
* @return
*/
public static Map<String, Object> convertParameterMap(Map<String, String[]> parameterMap) {
Map<String, Object> map = new HashMap<>();
for (Map.Entry<String, String[]> entry: parameterMap.entrySet()) {
String key = entry.getKey();
String value = entry.getValue()[0];
map.put(key, value);
}
return map;
}
/**
* 解析从数据库获取的响应,赋对应的值
* @param requestMap 请求Map
* @param responseMap 响应Map
* @return
*/
public static Map<String, Object> disposeResponseMap(Map<String, Object> requestMap, Map<String, Object> responseMap) {
for (Map.Entry<String, Object> entry: responseMap.entrySet()) {
if (entry.getValue() instanceof List) {
List<Map> list = (List) entry.getValue();
for (Map<String, Object> map: list) {
for (Map.Entry<String, Object> entry2: map.entrySet()) {
String value2 = entry2.getValue().toString();
if (value2.startsWith("$request")) {
entry2.setValue(requestMap.get(value2.split("\\.")[1]));
}
}
}
} else if (entry.getValue() instanceof String) {
String value = entry.getValue().toString();
if (value.startsWith("$request")) {
entry.setValue(requestMap.get(value.split("\\.")[1]));
}
if (value.equals("true")) {
entry.setValue(true);
}
if (value.equals("false")) {
entry.setValue(false);
}
}
}
return responseMap;
}
}
package cn.qg.holmes.mapper.jira;
import cn.qg.holmes.entity.jira.DingRobot;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
public interface DingRobotMapper extends BaseMapper<DingRobot> {
}
package cn.qg.holmes.service.jira;
import cn.qg.holmes.entity.jira.DingRobot;
import com.baomidou.mybatisplus.extension.service.IService;
public interface DingRobotService extends IService<DingRobot> {
Boolean sendMsgToDing(String jiraData);
}
package cn.qg.holmes.service.jira.impl;
import cn.qg.holmes.entity.jira.DingRobot;
import cn.qg.holmes.mapper.jira.DingRobotMapper;
import cn.qg.holmes.service.jira.DingRobotService;
import cn.qg.holmes.utils.DingdingUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jayway.jsonpath.JsonPath;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
@Slf4j
public class DingRobotServiceImpl extends ServiceImpl<DingRobotMapper, DingRobot> implements DingRobotService {
@Autowired
DingRobotMapper dingRobotMapper;
@Override
public Boolean sendMsgToDing(String jiraData) {
log.info("收到jira bug提交:{}", jiraData);
String webhookEvent = JsonPath.read(jiraData, "$.webhookEvent");
if (StringUtils.equals(webhookEvent, "jira:issue_created")) {
String creator = JsonPath.read(jiraData, "$.issue.fields.creator.displayName");
String assignee = JsonPath.read(jiraData, "$.issue.fields.assignee.displayName");
String key = JsonPath.read(jiraData, "$.issue.key");
String summary = JsonPath.read(jiraData, "$.issue.fields.summary");
String priority = JsonPath.read(jiraData, "$.issue.fields.priority.name");
String module = JsonPath.read(jiraData, "$.issue.fields.components[0].name");
String robotUrl = null;
List<DingRobot> dingRobots = dingRobotMapper.selectList(null);
for (DingRobot dingRobot : dingRobots) {
String projectName = "【" + dingRobot.getProjectName() + "】";
if (summary.contains(projectName)) {
robotUrl = dingRobot.getDingUrl();
break;
}
}
if (robotUrl != null) {
String markdownMsg = DingdingUtils.buildMarkdownMsg(key, summary, creator, assignee, priority, module);
return DingdingUtils.sendToDingding(markdownMsg, robotUrl);
}
}
return false;
}
}
package cn.qg.holmes.utils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import java.util.HashMap;
import java.util.Map;
@Slf4j
public class DingdingUtils {
public static boolean sendToDingding(String jsonString, String webhook) {
Map<String, Object> headers = new HashMap<>();
headers.put("Content-Type", "application/json; charset=utf-8");
JSONObject result = HttpClientUtils.doPostJson(webhook, jsonString, headers);
log.info("发送给钉钉: {}, 内容:{}, 钉钉返回结果:{}", webhook, jsonString, result);
return result.get("errmsg").equals("ok");
}
public static String buildMarkdownMsg(String key, String summary, String creator, String assignee, String priority, String module) {
Map<String, Object> markdown = new HashMap<>();
Map<String, String> content = new HashMap<>();
markdown.put("msgtype", "markdown");
String title = creator + "提交了BUG:" + key;
String issueUrl = "http://jira2.quantgroup.cn/browse/" + key;
content.put("title", title);
content.put("text", "### " + title + "\n"
+ "#### 概要:[" + summary + "](" + issueUrl + ")"+ "\n"
+ "- 优先级:" + priority + "\n"
+ "- 模块:" + module + "\n"
+ "- 经办人:" + assignee);
markdown.put("markdown", content);
return JSON.toJSONString(markdown);
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment