初次提交代码
This commit is contained in:
@@ -0,0 +1,4 @@
|
||||
package com.Modules.Device;
|
||||
|
||||
public class deviceInfo {
|
||||
}
|
||||
+568
@@ -0,0 +1,568 @@
|
||||
package com.Modules.NormalData;
|
||||
import cn.hutool.core.date.DateTime;
|
||||
import com.common.entity.XdrHoneypot;
|
||||
import com.common.mapper.XdrHoneypotMapper;
|
||||
import com.common.service.SyslogNonNormalMessageService;
|
||||
import com.common.util.*;
|
||||
import com.config.AppConfig;
|
||||
import org.apache.ibatis.session.SqlSession;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import com.common.entity.SyslogMessage;
|
||||
import com.influx.SyslogToInfluxApp;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import com.common.service.DmNormalizeRuleService;
|
||||
import com.common.service.DmColumnService;
|
||||
import com.common.service.SyslogNormalDataService;
|
||||
import com.common.entity.DmColumn;
|
||||
import com.common.service.impl.DmColumnServiceImpl;
|
||||
import com.common.mapper.DmColumnMapper;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import com.common.mapper.DmColumnMapper;
|
||||
import com.common.mapper.DmNormalizeRuleMapper;
|
||||
import java.sql.Timestamp;
|
||||
import java.util.*;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
import org.json.JSONObject;
|
||||
import com.common.entity.RuleContent.*;
|
||||
import com.common.entity.SyslogNonNormalMessage;
|
||||
import org.joda.time.LocalDateTime;
|
||||
import com.common.service.LogDataFilterService;
|
||||
import com.common.service.LogDataCompleteService;
|
||||
import com.common.service.DeviceCollectTaskService;
|
||||
import com.common.entity.DeviceCollectTask;
|
||||
|
||||
public class LogNormalProcessor {
|
||||
private static final Logger logger = LoggerFactory.getLogger(LogNormalProcessor.class);
|
||||
|
||||
private String strLogMsg ;
|
||||
private String strKafkaMessage;
|
||||
private String strDeviceInfo;
|
||||
private String strDataType ="json" ;
|
||||
private Map<String, Object> messageMap ;
|
||||
private Map<String, String> deviceInfoMap ;
|
||||
private String strSyslogUUID ;
|
||||
private String strSyslogTopic ;
|
||||
private boolean isSaveNonNormal =false ;
|
||||
|
||||
@Autowired
|
||||
public DmNormalizeRuleService dmNormalizeRuleService ;
|
||||
@Autowired
|
||||
public DmColumnService dmColumnService ;
|
||||
@Autowired
|
||||
public SyslogNormalDataService syslogNormalDataService =SpringContextUtil.getBean(SyslogNormalDataService.class);
|
||||
@Autowired
|
||||
private SyslogNonNormalMessageService messageService =SpringContextUtil.getBean(SyslogNonNormalMessageService.class);
|
||||
@Autowired
|
||||
private LogDataFilterService logDataFilterService= SpringContextUtil.getBean(LogDataFilterService.class);
|
||||
|
||||
@Autowired
|
||||
private LogDataCompleteService logDataCompleteService= SpringContextUtil.getBean(LogDataCompleteService.class);
|
||||
@Autowired
|
||||
private DeviceCollectTaskService deviceCollectTaskService= SpringContextUtil.getBean(DeviceCollectTaskService.class);
|
||||
|
||||
|
||||
@Autowired
|
||||
SyslogNonNormalMessage syslogNonNormalMessage=new SyslogNonNormalMessage();
|
||||
|
||||
@Autowired
|
||||
DmColumnMapper dmColumnMapper;
|
||||
@Autowired
|
||||
DmNormalizeRuleMapper dmNormalizeRuleMapper;
|
||||
|
||||
private static List<Map<String, Object>> dmNormalizeRuleList;
|
||||
private static List<Map<String, Object>> dmColumnList;
|
||||
private static LinkedHashMap<String, Object> OrginalColumnMap ;
|
||||
|
||||
public LogNormalProcessor( String LogMsg, String syslogUUID,String syslogTopic) {
|
||||
|
||||
/** 标准化数据处理步骤 */
|
||||
//初始化 (获取syslog_normal_data 表全部字段的属性、设备ID对应的规则设置、转化成JSON)
|
||||
//判断数据解析类型(json、键值、xml、正则表达式、分割符)解析syslogMessage 字段转成 HashMAP
|
||||
//匹配规则内容,获取字段映射关系配置,抽取命中的字段名称、数值
|
||||
//判断字段内容及类型,根据数据类型属性,进行内容转换。
|
||||
//生成insert SQL语句、执行入库操作。
|
||||
strKafkaMessage=LogMsg;
|
||||
strSyslogUUID=syslogUUID;
|
||||
strSyslogTopic=syslogTopic;
|
||||
|
||||
if(!LogMsg.isEmpty()) {
|
||||
strLogMsg = SyslogParser.substringAfterFirstCloseBracket(LogMsg);
|
||||
strDeviceInfo=SyslogParser.substringBeforeFirstChar(LogMsg,']');
|
||||
}
|
||||
else{
|
||||
LogMsg="[receive_time=20251118165909470 device_id=1 device_name=honeypot vendor=changting data_type=json device_collect_id=1]<14>1 2025-09-24T11:52:26Z 5f46d3be75e1 supermario 128 honeypot_event - {\"source\":\"honeypot1\",\"id\":\"f6a13c35-bf9d-4da6-a181-50ce23e7ef6a\",\"start_time\":\"2023-09-03T11:07:02.50167643Z\",\"time\":\"2023-09-03T11:16:18.883885281Z\",\"risk_level\":4,\"connection\":\"b18f3fbe-3fbf-4495-815f-ff26f6fb0bdf\",\"file_info\":null,\"extra\":{\"payload\":{\"format\":\"line\",\"name\":{\"cn\":\"攻击载荷\",\"en\":\"payload\"},\"value\":\"\"},\"uid\":{\"format\":\"line\",\"name\":{\"cn\":\"\",\"en\":\"\"},\"uid\":\"b4cbc73c-25d0-4429-ae1b-a856cdf1a651\",\"value\":\"\"}},\"type\":\"WEB_ATTACK_SCANNER\",\"agent_sn\":\"caa7da42-0cca-4cb1-b501-1f1eb2b588d5\",\"agent_name\":\" 教育局蜜罐探针\",\"honeypot_id\":\"11a9ac6bdf38ae2aaa49ec4f1b4a921bff71952cb9f175bdd8ee1f0497057bc6\",\"honeypot_name\":\"茂名市中小学管理平台管理后台\",\"src_ip\":\"117.50.189.7\",\"src_port\":58512,\"src_mac\":\"\",\"dest_ip\":\"192.168.222.2\",\"dest_port\":9200,\"proxy_ip\":null,\"node\":\"WRx3\"}";
|
||||
strLogMsg="<14>1 2025-09-24T11:52:26Z 5f46d3be75e1 supermario 128 honeypot_event - {\"source\":\"honeypot1\",\"id\":\"f6a13c35-bf9d-4da6-a181-50ce23e7ef6a\",\"start_time\":\"2023-09-03T11:07:02.50167643Z\",\"time\":\"2023-09-03T11:16:18.883885281Z\",\"risk_level\":4,\"connection\":\"b18f3fbe-3fbf-4495-815f-ff26f6fb0bdf\",\"file_info\":null,\"extra\":{\"payload\":{\"format\":\"line\",\"name\":{\"cn\":\"攻击载荷\",\"en\":\"payload\"},\"value\":\"\"},\"uid\":{\"format\":\"line\",\"name\":{\"cn\":\"\",\"en\":\"\"},\"uid\":\"b4cbc73c-25d0-4429-ae1b-a856cdf1a651\",\"value\":\"\"}},\"type\":\"WEB_ATTACK_SCANNER\",\"agent_sn\":\"caa7da42-0cca-4cb1-b501-1f1eb2b588d5\",\"agent_name\":\" 教育局蜜罐探针\",\"honeypot_id\":\"11a9ac6bdf38ae2aaa49ec4f1b4a921bff71952cb9f175bdd8ee1f0497057bc6\",\"honeypot_name\":\"茂名市中小学管理平台管理后台\",\"src_ip\":\"117.50.189.7\",\"src_port\":58512,\"src_mac\":\"\",\"dest_ip\":\"192.168.222.2\",\"dest_port\":9200,\"proxy_ip\":null,\"node\":\"WRx3\"}";
|
||||
strDeviceInfo=SyslogParser.substringBeforeFirstChar(LogMsg,']');
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 初始化数据init()
|
||||
*/
|
||||
public void init()
|
||||
{
|
||||
Map<String,String> mapdev =SyslogParser.parseKeyValuePairs(strDeviceInfo);
|
||||
deviceInfoMap=mapdev;
|
||||
//获取日志对应的设备ID
|
||||
long deviceID=Long.parseLong(mapdev.get("device_id"));
|
||||
System.out.println("device_id:"+deviceID );
|
||||
strDataType=mapdev.get("data_type");
|
||||
//getDeviceID(strLogMsg);
|
||||
try{
|
||||
// 通过工具类获取Service实例
|
||||
dmColumnService= SpringContextUtil.getBean(DmColumnService.class);
|
||||
dmNormalizeRuleService= SpringContextUtil.getBean(DmNormalizeRuleService.class);
|
||||
if(deviceID>0) {
|
||||
dmNormalizeRuleList = dmNormalizeRuleService.selectByDeviceIdAuto(deviceID);
|
||||
}
|
||||
//dmColumnList=dmColumnService.selectAllNormal();
|
||||
//System.out.println("dmColumnList size:"+ dmColumnList.size());
|
||||
|
||||
//OrginalColumnMap=getMessageToMap(strLogMsg);
|
||||
//解析SyslogMessage
|
||||
//SyslogMessage logMsg = SyslogParser.parse(strLogMsg);
|
||||
//设备对应的规则normal rule Map 进行标准化数据处理
|
||||
for (int i = 0; i < dmNormalizeRuleList.size(); i++) {
|
||||
try {
|
||||
Map<String, Object> dmNormalizeRule = dmNormalizeRuleList.get(i);
|
||||
String data_type = dmNormalizeRule.get("data_type").toString();
|
||||
//数据类型及格式不符,则break;
|
||||
System.out.println("索引: " + i + ", 值: " + dmNormalizeRule);
|
||||
System.out.println("normalrule ID: " + dmNormalizeRule.get("id") + ", display_name:" + dmNormalizeRule.get("display_name") + " data_type:" + dmNormalizeRule.get("data_type"));
|
||||
//数据类型不匹配,则跳过规则
|
||||
//if (!data_type.equals(strDataType)) break;
|
||||
|
||||
//获取syslog message 文本解析配置项
|
||||
OrginalColumnMap = getMessageToMap(dmNormalizeRule, strLogMsg, data_type);
|
||||
if ((OrginalColumnMap == null) || (OrginalColumnMap.size()==0)) {
|
||||
logger.error("OrginalColumnMap 对象获取为空");
|
||||
//保存非标日志信息
|
||||
syslogNonNormalMessage.setReason("Log解析异常");
|
||||
syslogNonNormalMessage.setReasonDetail("log解析异常,返回规则名称:"+dmNormalizeRule.get("display_name") +",OrginalColumnMap 对象获取为空");
|
||||
if(isSaveNonNormal==false)
|
||||
SaveNonNormalMessage(deviceID, DateTime.now());
|
||||
continue;
|
||||
}
|
||||
List<HashMap<String, Object>> destColumnList = getRuleContentMappers(dmNormalizeRule);
|
||||
//解析字段匹配已命中的配置规则字段
|
||||
List<HashMap<String, Object>> ruleColumnList = getNormalColumnList(OrginalColumnMap, destColumnList);
|
||||
//System.out.println("ruleColumnList :"+ ruleColumnList);
|
||||
Map<String, Object> destMap = getColumnMap(ruleColumnList);
|
||||
//List<HashMap<String ,Object>> destMap2= getCompleteColumnsList(dmNormalizeRule);
|
||||
|
||||
//数据处理-过滤规则
|
||||
if (logDataFilterService.evaluateFilterRule(dmNormalizeRule.get("rule_content").toString(), destMap))
|
||||
continue;
|
||||
|
||||
//数据处理-补全规则
|
||||
logDataCompleteService.processDataCompletion(dmNormalizeRule.get("rule_content").toString(), destMap);
|
||||
//long ruleid=Long.parseLong(dmNormalizeRule.get("id").toString());
|
||||
SaveNormalData(deviceID, DateTime.now(), destMap, Long.parseLong(dmNormalizeRule.get("id").toString()), dmNormalizeRule.get("name").toString());
|
||||
|
||||
} catch (Exception ex) {
|
||||
logger.error("泛化规则处理失败:" + ex.getMessage());
|
||||
System.out.println(ex.getMessage());
|
||||
/**
|
||||
//保存非标日志信息
|
||||
syslogNonNormalMessage.setReason("泛化规则处理失败");
|
||||
syslogNonNormalMessage.setReasonDetail("泛化规则处理失败,失败详情:"+ ex.getMessage());
|
||||
SaveNonNormalMessage(deviceID,DateTime.now());
|
||||
**/
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.error("处理初始化异常:"+ex.getMessage());
|
||||
System.out.println(ex.getMessage());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
//获取数据泛化规则的列表字段,提取 Cropper_params
|
||||
public Cropper_paramsType getCropperParams( Map<String, Object> dmNormalizeRule )
|
||||
{
|
||||
Cropper_paramsType cropperParams = new Cropper_paramsType();
|
||||
try {
|
||||
JSONObject jsonObject = new JSONObject( dmNormalizeRule.get("rule_content").toString());
|
||||
if (jsonObject.isEmpty()) return null;
|
||||
|
||||
cropperParams.sethead_key(jsonObject.getJSONObject("cropper_params").get("head_key").toString());
|
||||
//需要判断是否字符串head_offset是否空
|
||||
cropperParams.sethead_offset(Integer.parseInt(jsonObject.getJSONObject("cropper_params").get("head_offset").toString()));
|
||||
cropperParams.settail_key(jsonObject.getJSONObject("cropper_params").get("tail_key").toString());
|
||||
//需要判断是否字符串tail_offset是否空
|
||||
cropperParams.settail_offset( Integer.parseInt(jsonObject.getJSONObject("cropper_params").get("tail_offset").toString()));
|
||||
return cropperParams;
|
||||
}catch (Exception ex) {
|
||||
logger.error("getCropperParams:"+ex.getMessage());
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
public List<HashMap<String ,Object>> getRuleContentMappers( Map<String, Object> dmNormalizeRule )
|
||||
{
|
||||
List<HashMap<String, Object>> filedList =null;
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
try {
|
||||
// 转换为list Map
|
||||
//Map<String, Object> rule_contentMap = objectMapper.readValue( dmNormalizeRule.get("rule_content").toString(), Map.class);
|
||||
//if (rule_contentMap.isEmpty()) return null;
|
||||
JSONObject jsonObject = new JSONObject( dmNormalizeRule.get("rule_content").toString());
|
||||
if (jsonObject.isEmpty()) return null;
|
||||
ObjectMapper objectMapper_mappers = new ObjectMapper();
|
||||
filedList =readJsonToList( jsonObject.get("mappers").toString() );
|
||||
|
||||
}catch (Exception ex) {
|
||||
logger.error("getRuleContentMappers异常:"+ex.getMessage());
|
||||
}
|
||||
return filedList;
|
||||
}
|
||||
|
||||
|
||||
|
||||
public List<HashMap<String, Object>> getCompleteColumnsList( Map<String, Object> dmNormalizeRule )
|
||||
{
|
||||
List<HashMap<String, Object>> filedList =null;
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
try {
|
||||
// 转换为list Map
|
||||
//Map<String, Object> rule_contentMap = objectMapper.readValue( dmNormalizeRule.get("rule_content").toString(), Map.class);
|
||||
//if (rule_contentMap.isEmpty()) return null;
|
||||
JSONObject jsonObject = new JSONObject( dmNormalizeRule.get("rule_content").toString());
|
||||
if (jsonObject.isEmpty()) return null;
|
||||
ObjectMapper objectMapper_mappers = new ObjectMapper();
|
||||
filedList =readJsonToList( jsonObject.get("complete_columns").toString() );
|
||||
|
||||
}catch (Exception ex) {
|
||||
logger.error("getCompleteColumnsList:"+ex.getMessage());
|
||||
}
|
||||
return filedList;
|
||||
}
|
||||
/**
|
||||
* 将JSON 字符串转换为 List<HashMap<String, Object>>
|
||||
*/
|
||||
public static List<HashMap<String, Object>> readJsonToList(String jsonStr) {
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
try {
|
||||
return objectMapper.readValue(
|
||||
jsonStr,
|
||||
new TypeReference<List<HashMap<String, Object>>>() {}
|
||||
);
|
||||
} catch (Exception e) {
|
||||
|
||||
logger.error("readJsonToList 解析失败:"+jsonStr);
|
||||
//throw new RuntimeException("JSON 解析失败: " + e.getMessage(), e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
/**\
|
||||
* 判断日志信息的数据类型
|
||||
* @param logMsg
|
||||
* @return
|
||||
*/
|
||||
public String getLogDataType( String logMsg)
|
||||
{
|
||||
//判断日志信息的数据类型(json、regex、kv、sep、xml)
|
||||
//默认返回json
|
||||
return "json";
|
||||
}
|
||||
|
||||
public int getDeviceID( String logMsg)
|
||||
{
|
||||
//解析日志信息头部,获取device_id
|
||||
// 默认返回device_id =1
|
||||
return 1;
|
||||
}
|
||||
//获取log 内容字段及数据值
|
||||
public LinkedHashMap<String, Object> getMessageToMap( String MsgContent )
|
||||
{
|
||||
LinkedHashMap<String, Object> linkMap =null;
|
||||
if(strDataType.equals("json")) {
|
||||
//json 类型
|
||||
//解析SyslogMessage
|
||||
SyslogMessage msg = SyslogParser.parse(MsgContent);
|
||||
System.out.println("解析结果-log content: " + msg.getMessage().toString());
|
||||
String complexJson = "{\"source\":\"honeypot1\",\"id\":\"f6a13c35-bf9d-4da6-a181-50ce23e7ef6a\",\"start_time\":\"2023-09-03T11:07:02.50167643Z\",\"time\":\"2023-09-03T11:16:18.883885281Z\",\"risk_level\":4,\"connection\":\"b18f3fbe-3fbf-4495-815f-ff26f6fb0bdf\",\"file_info\":null,\"extra\":{\"payload\":{\"format\":\"line\",\"name\":{\"cn\":\"攻击载荷\",\"en\":\"payload\"},\"value\":\"\"},\"uid\":{\"format\":\"line\",\"name\":{\"cn\":\"\",\"en\":\"\"},\"uid\":\"b4cbc73c-25d0-4429-ae1b-a856cdf1a651\",\"value\":\"\"}},\"type\":\"WEB_ATTACK_SCANNER\",\"agent_sn\":\"caa7da42-0cca-4cb1-b501-1f1eb2b588d5\",\"agent_name\":\" 教育局蜜罐探针\",\"honeypot_id\":\"11a9ac6bdf38ae2aaa49ec4f1b4a921bff71952cb9f175bdd8ee1f0497057bc6\",\"honeypot_name\":\"茂名市中小学管理平台管理后台\",\"src_ip\":\"117.50.189.7\",\"src_port\":58512,\"src_mac\":\"\",\"dest_ip\":\"192.168.222.2\",\"dest_port\":9200,\"proxy_ip\":null,\"node\":\"WRx3\"}";
|
||||
System.out.println("complexJson content: " + complexJson);
|
||||
//静态字符串、编码有问题,临时用 静态字符串做测试,流程环境没问题
|
||||
if(AppConfig.geRunEnvironment().equals("dev")) {
|
||||
//LinkedHashMap<String, Object> flatMap = JsonParser.parseJsonToFlatMap(complexJson);
|
||||
LinkedHashMap<String, Object> flatMap =JsonParser.jsonToMap(complexJson);
|
||||
flatMap.forEach((key, value) -> System.out.println(key + " = " + value));
|
||||
return flatMap;
|
||||
}
|
||||
else
|
||||
{
|
||||
//LinkedHashMap<String, Object> flatMap = JsonParser.parseJsonToFlatMap(msg.getMessage());
|
||||
LinkedHashMap<String, Object> flatMap =JsonParser.jsonToMap(msg.getMessage());
|
||||
flatMap.forEach((key, value) -> System.out.println(key + " = " + value));
|
||||
return flatMap;
|
||||
}
|
||||
}
|
||||
else if(strDataType.equals("kv")) //key-value 键值类型
|
||||
{
|
||||
return null;
|
||||
}
|
||||
else if(strDataType.equals("sep")) //分隔符
|
||||
{
|
||||
return null;
|
||||
}
|
||||
else if(strDataType.equals("xml")) //类型 xml
|
||||
{
|
||||
return null;
|
||||
}
|
||||
else if(strDataType.equals("regex")) //正则表达式
|
||||
{
|
||||
return null;
|
||||
}
|
||||
// List<Map<String, Object>> rulelst=dmNormalizeRuleService.selectByDeviceId((long)1);
|
||||
return linkMap;
|
||||
}
|
||||
|
||||
|
||||
//获取log message内容字段及数据值
|
||||
public LinkedHashMap<String, Object> getMessageToMap( Map<String, Object> dmNormalizeRule, String MsgContent , String dataType)
|
||||
{
|
||||
LinkedHashMap<String, Object> linkMap = new LinkedHashMap<>();
|
||||
try {
|
||||
//String decode =dmNormalizeRule.get("decode").toString();
|
||||
Cropper_paramsType cropperParams = getCropperParams(dmNormalizeRule);
|
||||
if (dataType.equals("json")) {
|
||||
String strJson = logNormalData.ParserMessageJsonType(MsgContent, cropperParams);
|
||||
LinkedHashMap<String, Object> result1 = NestedJsonParserUtil.safeParseJson(strJson);
|
||||
LinkedHashMap<String, Object> flattened = NestedJsonUtils.flattenNestedJson(result1);
|
||||
return flattened;
|
||||
//parseJsonToFlatMap 复杂的json转换、解析过程有异常
|
||||
//return JsonParser.parseJsonToFlatMap(strJson);
|
||||
// return JsonParser.jsonToMap(strJson);
|
||||
}
|
||||
else if (dataType.equals("kv")) //key-value 键值类型
|
||||
{
|
||||
String strKeyVal = logNormalData.ParserMessageJsonType(MsgContent, cropperParams);
|
||||
KvTextParser kvTextParser =new KvTextParser();
|
||||
kv_paramsType kvparams=logNormalData.getkv_paramsType( dmNormalizeRule);
|
||||
linkMap= kvTextParser.parseKvText(strKeyVal,kvparams);
|
||||
return linkMap;
|
||||
}
|
||||
else if (dataType.equals("sep")) //分隔符
|
||||
{
|
||||
//获取分隔符
|
||||
String SepKey=logNormalData.sepType(dmNormalizeRule);
|
||||
String strSep = logNormalData.ParserMessageJsonType(MsgContent, cropperParams);
|
||||
linkMap= TextParserUtil.parseSeparatedText(strSep, SepKey);
|
||||
return linkMap;
|
||||
}
|
||||
else if (dataType.equals("xml")) //类型 xml
|
||||
{
|
||||
return linkMap;
|
||||
}
|
||||
else if (dataType.equals("regex")) //正则表达式
|
||||
{
|
||||
String strRegex = logNormalData.ParserMessageJsonType(MsgContent, cropperParams);
|
||||
String regexp= logNormalData.Regexp(dmNormalizeRule);
|
||||
linkMap= RegexTextParser.parseWithRegex(strRegex,regexp );
|
||||
return linkMap;
|
||||
}
|
||||
}catch (Exception ex) {
|
||||
logger.error("getMessageToMap:"+ex.getMessage());
|
||||
return null;
|
||||
}
|
||||
return linkMap;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据设备ID获取配置规则
|
||||
* @param device_id
|
||||
* @return List<Map<String, Object>>
|
||||
*/
|
||||
public List<Map<String, Object>> getRuleList( long device_id)
|
||||
{
|
||||
List<Map<String, Object>> rulelst=dmNormalizeRuleService.selectByDeviceId((long)1);
|
||||
if (rulelst!=null)
|
||||
{
|
||||
System.out.println("rulelst: " + rulelst);
|
||||
}
|
||||
else{
|
||||
logger.error(" List<Map<String, Object>> rulelst is null!" );
|
||||
}
|
||||
return rulelst;
|
||||
}
|
||||
|
||||
/**
|
||||
* 查找命中配置规则的字段及数值
|
||||
* @param destColumnList 泛化目标字段list
|
||||
* @param destColumnList 日志源字段及数值list
|
||||
* @return
|
||||
*/
|
||||
public List<HashMap<String,Object>> getNormalColumnList( LinkedHashMap<String, Object> orginColumnMap ,List<HashMap<String, Object>> destColumnList )
|
||||
{
|
||||
List<HashMap<String, Object>> columnlist =new ArrayList<>();
|
||||
// 原始解析字段遍历泛化规则目标字段
|
||||
for (Map.Entry<String, Object > entry : orginColumnMap.entrySet()) {
|
||||
//System.out.println(entry.getKey() + ": " + entry.getValue());
|
||||
for (Map<String, Object> map : destColumnList) {
|
||||
//System.out.println( "origin_field: " + map.get("origin_field").toString());
|
||||
if ( map.get("origin_field").toString().equals(entry.getKey()) ) {
|
||||
System.out.println(map);
|
||||
Map<String, Object> normalColumMap =new LinkedHashMap<>();
|
||||
normalColumMap.put("origin_field",entry.getKey() );
|
||||
normalColumMap.put("dest_field",map.get("dest_field").toString());
|
||||
normalColumMap.put("action",(HashMap<String, Object>)map.get("action") );
|
||||
//normalColumMap.put("mapping ",entry.getKey() );
|
||||
normalColumMap.put("origin_field_value",entry.getValue() );
|
||||
// System.out.println("action: " + map.get("action").toString());
|
||||
if( ((HashMap<String, Object>)map.get("action")).get("type").equals("equal"))
|
||||
//直接赋值
|
||||
normalColumMap.put("dest_field_value",entry.getValue() );
|
||||
else if(((HashMap<String, Object>)map.get("action")).get("type").equals("mapping"))
|
||||
{
|
||||
//mapping 映射枚举值
|
||||
normalColumMap.put("dest_field_value",entry.getValue() );
|
||||
normalColumMap.put("action_param",((HashMap<String, Object>)map.get("action")).get("param") );
|
||||
HashMap<String, Object> action_param=(HashMap<String, Object>)((HashMap<String, Object>)map.get("action")).get("param") ;
|
||||
//匹配并获取映射枚举值
|
||||
normalColumMap.put("dest_field_value",getMappingValue(action_param ,entry.getValue().toString() ));
|
||||
}
|
||||
else if(((HashMap<String, Object>)map.get("action")).get("type").equals("time\""))
|
||||
{
|
||||
//time 类型
|
||||
normalColumMap.put("dest_field_value",entry.getValue() );
|
||||
}
|
||||
columnlist.add((HashMap<String, Object>)normalColumMap);
|
||||
|
||||
//System.out.println( "normalColumMap: " +normalColumMap);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return columnlist;
|
||||
}
|
||||
|
||||
/**
|
||||
* paramMapping Map匹配查找对应的值
|
||||
* @param paramMappingValueMap
|
||||
* @param
|
||||
* @return
|
||||
*/
|
||||
public Object getMappingValue(HashMap<String, Object> paramMappingValueMap,String value)
|
||||
{
|
||||
HashMap<String, Object> Map= (HashMap<String, Object>)paramMappingValueMap.get("mapping");
|
||||
for (Map.Entry<String, Object > entry : Map.entrySet()) {
|
||||
if ( entry.getKey().equals(value) ) {
|
||||
return entry.getValue();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取字段Map,包含字段field及Value值
|
||||
* @param normalColumnList
|
||||
* @return
|
||||
*/
|
||||
public Map<String, Object > getColumnMap( List<HashMap<String,Object>> normalColumnList )
|
||||
{
|
||||
Map<String, Object > columnMap= new HashMap<>();
|
||||
for (Map<String, Object> map : normalColumnList) {
|
||||
columnMap.put(map.get("dest_field").toString(),map.get("dest_field_value"));
|
||||
}
|
||||
return columnMap;
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存数据到标准化表
|
||||
* @param deviceId
|
||||
* @param logtime
|
||||
* @param logColumnMap
|
||||
*/
|
||||
public void SaveNormalData(long deviceId , DateTime logtime, Map<String, Object > logColumnMap, long normalizeRuleId ,String normalizeRuleName)
|
||||
{
|
||||
try {
|
||||
if(logColumnMap.isEmpty() )
|
||||
{
|
||||
logger.error("SaveNormalData ->logColumnMap 为空,syslogUUID:" +this.strSyslogUUID);
|
||||
//保存非标日志信息
|
||||
syslogNonNormalMessage.setReason("未命中规则");
|
||||
syslogNonNormalMessage.setReasonDetail("失败详情:logColumnMap对象字段为空" );
|
||||
if(isSaveNonNormal==false)
|
||||
SaveNonNormalMessage(deviceId,DateTime.now());
|
||||
return ;
|
||||
}
|
||||
Map<String, Object> columnMap = logColumnMap;
|
||||
columnMap.put("device_id", deviceId);
|
||||
columnMap.put("log_time", logtime);
|
||||
columnMap.put("id", UUID.randomUUID().toString());
|
||||
columnMap.put("normalize_rule_id", normalizeRuleId);
|
||||
columnMap.put("normalize_rule_name", normalizeRuleName);
|
||||
columnMap.put("syslog_uuid", this.strSyslogUUID);
|
||||
columnMap.put("syslog_topic", this.strSyslogTopic);
|
||||
System.out.println("columnMap:"+columnMap);
|
||||
syslogNormalDataService.insertDynamic(columnMap);
|
||||
} catch (Exception e) {
|
||||
logger.error("SaveNormalData失败 " );
|
||||
//保存非标日志信息
|
||||
syslogNonNormalMessage.setReason("入库失败");
|
||||
syslogNonNormalMessage.setReasonDetail("入库失败,normalizeRuleName :"+normalizeRuleName+",失败详情:"+ e.getMessage());
|
||||
if(isSaveNonNormal==false)
|
||||
SaveNonNormalMessage(deviceId,DateTime.now());
|
||||
throw new RuntimeException("SaveNormalData 失败: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
public void SaveNonNormalMessage(long deviceId , DateTime logtime)
|
||||
{
|
||||
try {
|
||||
SyslogNonNormalMessage normalMessage =new SyslogNonNormalMessage() ;
|
||||
//获取日志对应的设备ID
|
||||
Integer collect_id= Integer.parseInt(this.deviceInfoMap.get("device_collect_id"));
|
||||
DeviceCollectTask deviceCollectTask=deviceCollectTaskService.getById(collect_id);
|
||||
normalMessage.setId( UUID.randomUUID().toString());
|
||||
normalMessage.setDeviceId((int)deviceId);
|
||||
normalMessage.setLogTime(logtime.toLocalDateTime());
|
||||
normalMessage.setRuleTime(logtime.toLocalDateTime());
|
||||
normalMessage.setSyslogMessage(this.strLogMsg);
|
||||
normalMessage.setSyslogTopic(this.strSyslogTopic);
|
||||
normalMessage.setSyslogUuid(this.strSyslogUUID);
|
||||
normalMessage.setHeaderMessage(this.strDeviceInfo);
|
||||
normalMessage.setEtlNode("etlgo");
|
||||
normalMessage.setReason( syslogNonNormalMessage.getReason());
|
||||
normalMessage.setReasonDetail( syslogNonNormalMessage.getReasonDetail());
|
||||
//采集探针名称
|
||||
normalMessage.setRuleResult("FAIL");
|
||||
normalMessage.setDeviceName(deviceInfoMap.get("device_name"));
|
||||
normalMessage.setCollectTaskId(collect_id);
|
||||
if(deviceCollectTask!=null)
|
||||
normalMessage.setCollectTaskName(deviceCollectTask.getTaskName());
|
||||
this.messageService.saveMessage(normalMessage );
|
||||
isSaveNonNormal=true;
|
||||
|
||||
} catch (Exception e) {
|
||||
logger.error("SaveNonNormalMessage 失败:" );
|
||||
throw new RuntimeException("SaveNonNormalMessage 失败: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
String strlogMessage= "<14>1 2025-09-24T11:52:26Z 5f46d3be75e1 supermario 128 honeypot_event - {\"source\":\"honeypot1\",\"id\":\"f6a13c35-bf9d-4da6-a181-50ce23e7ef6a\",\"start_time\":\"2023-09-03T11:07:02.50167643Z\",\"time\":\"2023-09-03T11:16:18.883885281Z\",\"risk_level\":4,\"connection\":\"b18f3fbe-3fbf-4495-815f-ff26f6fb0bdf\",\"file_info\":null,\"extra\":{\"payload\":{\"format\":\"line\",\"name\":{\"cn\":\"攻击载荷\",\"en\":\"payload\"},\"value\":\"\"},\"uid\":{\"format\":\"line\",\"name\":{\"cn\":\"\",\"en\":\"\"},\"uid\":\"b4cbc73c-25d0-4429-ae1b-a856cdf1a651\",\"value\":\"\"}},\"type\":\"WEB_ATTACK_SCANNER\",\"agent_sn\":\"caa7da42-0cca-4cb1-b501-1f1eb2b588d5\",\"agent_name\":\" 教育局蜜罐探针\",\"honeypot_id\":\"11a9ac6bdf38ae2aaa49ec4f1b4a921bff71952cb9f175bdd8ee1f0497057bc6\",\"honeypot_name\":\"茂名市中小学管理平台管理后台\",\"src_ip\":\"117.50.189.7\",\"src_port\":58512,\"src_mac\":\"\",\"dest_ip\":\"192.168.222.2\",\"dest_port\":9200,\"proxy_ip\":null,\"node\":\"WRx3\"}";
|
||||
String strMsgContent= "{\"source\":\"honeypot1\",\"id\":\"f6a13c35-bf9d-4da6-a181-50ce23e7ef6a\",\"start_time\":\"2023-09-03T11:07:02.50167643Z\",\"time\":\"2023-09-03T11:16:18.883885281Z\",\"risk_level\":4,\"connection\":\"b18f3fbe-3fbf-4495-815f-ff26f6fb0bdf\",\"file_info\":null,\"extra\":{\"payload\":{\"format\":\"line\",\"name\":{\"cn\":\"攻击载荷\",\"en\":\"payload\"},\"value\":\"\"},\"uid\":{\"format\":\"line\",\"name\":{\"cn\":\"\",\"en\":\"\"},\"uid\":\"b4cbc73c-25d0-4429-ae1b-a856cdf1a651\",\"value\":\"\"}},\"type\":\"WEB_ATTACK_SCANNER\",\"agent_sn\":\"caa7da42-0cca-4cb1-b501-1f1eb2b588d5\",\"agent_name\":\" 教育局蜜罐探针\",\"honeypot_id\":\"11a9ac6bdf38ae2aaa49ec4f1b4a921bff71952cb9f175bdd8ee1f0497057bc6\",\"honeypot_name\":\"茂名市中小学管理平台管理后台\",\"src_ip\":\"117.50.189.7\",\"src_port\":58512,\"src_mac\":\"\",\"dest_ip\":\"192.168.222.2\",\"dest_port\":9200,\"proxy_ip\":null,\"node\":\"WRx3\"}";
|
||||
//Map<String, Object> flatMap =(new logNormalData()).getMessageToMap(strMsgContent);
|
||||
//flatMap.forEach((key, value) -> System.out.println(key + " = " + value));
|
||||
//LogNormalProcessor logData =new LogNormalProcessor(strlogMessage,);
|
||||
//logData.init();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
+404
@@ -0,0 +1,404 @@
|
||||
package com.Modules.NormalData;
|
||||
|
||||
import com.influx.InfluxDBClient;
|
||||
import com.common.util.SyslogParser;
|
||||
import com.config.AppConfig;
|
||||
import com.influxdb.client.domain.WritePrecision;
|
||||
import com.influxdb.client.write.Point;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.kafka.clients.consumer.ConsumerRecord;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.kafka.annotation.KafkaListener;
|
||||
import org.springframework.kafka.support.Acknowledgment;
|
||||
import org.springframework.scheduling.annotation.Async;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDate;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
@Slf4j
|
||||
@Component
|
||||
public class SysLogProcessor {
|
||||
|
||||
@Autowired
|
||||
@Qualifier("logNormalProcessorExecutor")
|
||||
private Executor taskExecutor;
|
||||
|
||||
@Value("${app.processor.batch-size:100}")
|
||||
private int batchSize;
|
||||
|
||||
@Value("${app.processor.process-timeout-ms:30000}")
|
||||
private long processTimeoutMs;
|
||||
|
||||
private final AtomicInteger totalProcessed = new AtomicInteger(0);
|
||||
private final AtomicInteger currentBatchCount = new AtomicInteger(0);
|
||||
// 初始化 InfluxDB 客户端
|
||||
private final com.influx.InfluxDBClient influxClient = new InfluxDBClient();
|
||||
/**
|
||||
* 方案一:直接多线程并行处理(推荐)
|
||||
* 单线程消费,每条消息独立提交给线程池处理
|
||||
*/
|
||||
public void listen(List<String> records, Acknowledgment ack) {
|
||||
try {
|
||||
// 处理业务逻辑
|
||||
for (String record : records) {
|
||||
System.out.println(record);
|
||||
}
|
||||
// 手动提交偏移量
|
||||
ack.acknowledge(); // 告诉Kafka这条消息已成功处理
|
||||
} catch (Exception e) {
|
||||
// 不提交偏移量,消息会被重新消费
|
||||
}
|
||||
}
|
||||
@KafkaListener(
|
||||
topics = "${spring.kafka.consumer.topic:agent-syslog-topic}",
|
||||
concurrency = "2" // 多线程消费
|
||||
)
|
||||
public void consumeAndParallelProcess(List<ConsumerRecord<String, String>> records, Acknowledgment ack) {
|
||||
if (records.isEmpty()) {
|
||||
ack.acknowledge();
|
||||
return;
|
||||
}
|
||||
log.info("开始处理批次消息,数量: {}", records.size());
|
||||
currentBatchCount.set(records.size());
|
||||
|
||||
try {
|
||||
List<CompletableFuture<Void>> processingFutures = new ArrayList<>();
|
||||
|
||||
// 为每条消息创建独立的处理任务
|
||||
for (ConsumerRecord<String, String> record : records) {
|
||||
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
|
||||
try {
|
||||
// 异步处理单条消息
|
||||
log.info("收到syslogmessage:"+ record.value());
|
||||
processSingleMessageAsync(record);
|
||||
} catch (Exception e) {
|
||||
log.error("处理消息失败, topic: {}, partition: {}, offset: {}",
|
||||
record.topic(), record.partition(), record.offset(), e);
|
||||
} finally {
|
||||
// 计数器递减
|
||||
if (currentBatchCount.decrementAndGet() == 0) {
|
||||
log.debug("批次所有消息处理完成");
|
||||
}
|
||||
}
|
||||
}, taskExecutor);
|
||||
|
||||
processingFutures.add(future);
|
||||
}
|
||||
|
||||
// 等待所有处理任务完成(带超时)
|
||||
CompletableFuture<Void> allFutures = CompletableFuture.allOf(
|
||||
processingFutures.toArray(new CompletableFuture[0])
|
||||
);
|
||||
|
||||
try {
|
||||
allFutures.get(processTimeoutMs, TimeUnit.MILLISECONDS);
|
||||
log.info("批次处理完成,总数: {}", records.size());
|
||||
} catch (java.util.concurrent.TimeoutException e) {
|
||||
log.warn("批次处理超时,已处理: {}/{}",
|
||||
records.size() - currentBatchCount.get(), records.size());
|
||||
}
|
||||
|
||||
// 提交偏移量
|
||||
ack.acknowledge();
|
||||
totalProcessed.addAndGet(records.size());
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("消费处理异常", e);
|
||||
ack.acknowledge(); // 异常情况下也提交偏移量,避免阻塞
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 方案二:分批多线程处理
|
||||
* 将大批次拆分为小批次进行并行处理
|
||||
*/
|
||||
/**
|
||||
@KafkaListener(
|
||||
topics = "${kafka.topic.log-normal-batch:log-normal-topic-batch}",
|
||||
concurrency = "1"
|
||||
)
|
||||
*/
|
||||
public void consumeAndBatchProcess(List<ConsumerRecord<String, String>> records,
|
||||
Acknowledgment ack) {
|
||||
if (records.isEmpty()) {
|
||||
ack.acknowledge();
|
||||
return;
|
||||
}
|
||||
|
||||
log.info("开始分批处理消息,总数: {}", records.size());
|
||||
|
||||
try {
|
||||
List<CompletableFuture<Void>> batchFutures = new ArrayList<>();
|
||||
|
||||
// 将消息列表拆分为多个批次进行并行处理
|
||||
for (int i = 0; i < records.size(); i += batchSize) {
|
||||
int end = Math.min(i + batchSize, records.size());
|
||||
final List<ConsumerRecord<String, String>> batch = records.subList(i, end);
|
||||
final int batchIndex = i / batchSize + 1;
|
||||
|
||||
CompletableFuture<Void> batchFuture = CompletableFuture.runAsync(() -> {
|
||||
try {
|
||||
processMessageBatch(batch, batchIndex);
|
||||
} catch (Exception e) {
|
||||
log.error("批次处理异常, 批次: {}", batchIndex, e);
|
||||
}
|
||||
}, taskExecutor);
|
||||
|
||||
batchFutures.add(batchFuture);
|
||||
}
|
||||
|
||||
// 等待所有批次处理完成
|
||||
CompletableFuture<Void> allBatches = CompletableFuture.allOf(
|
||||
batchFutures.toArray(new CompletableFuture[0])
|
||||
);
|
||||
|
||||
allBatches.get(processTimeoutMs, TimeUnit.MILLISECONDS);
|
||||
|
||||
// 提交偏移量
|
||||
ack.acknowledge();
|
||||
log.info("全部分批处理完成,总数: {}", records.size());
|
||||
totalProcessed.addAndGet(records.size());
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("分批消费处理异常", e);
|
||||
ack.acknowledge();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 方案三:带优先级的处理
|
||||
* 根据消息内容决定处理优先级
|
||||
*/
|
||||
/**
|
||||
@KafkaListener(
|
||||
topics = "${kafka.topic.log-normal-priority:log-normal-topic-priority}",
|
||||
concurrency = "1"
|
||||
)
|
||||
*/
|
||||
public void consumeWithPriority(List<ConsumerRecord<String, String>> records,
|
||||
Acknowledgment ack) {
|
||||
if (records.isEmpty()) {
|
||||
ack.acknowledge();
|
||||
return;
|
||||
}
|
||||
|
||||
log.info("开始优先级处理消息,数量: {}", records.size());
|
||||
|
||||
try {
|
||||
List<CompletableFuture<Void>> highPriorityFutures = new ArrayList<>();
|
||||
List<CompletableFuture<Void>> normalPriorityFutures = new ArrayList<>();
|
||||
|
||||
// 根据消息内容分类处理
|
||||
for (ConsumerRecord<String, String> record : records) {
|
||||
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
|
||||
processSingleMessageAsync(record);
|
||||
}, taskExecutor);
|
||||
|
||||
// 根据消息内容判断优先级(这里简单根据key判断)
|
||||
if (isHighPriorityMessage(record)) {
|
||||
highPriorityFutures.add(future);
|
||||
} else {
|
||||
normalPriorityFutures.add(future);
|
||||
}
|
||||
}
|
||||
|
||||
// 优先处理高优先级任务
|
||||
if (!highPriorityFutures.isEmpty()) {
|
||||
CompletableFuture.allOf(
|
||||
highPriorityFutures.toArray(new CompletableFuture[0])
|
||||
).get(processTimeoutMs / 2, TimeUnit.MILLISECONDS);
|
||||
log.info("高优先级消息处理完成: {}", highPriorityFutures.size());
|
||||
}
|
||||
|
||||
// 然后处理普通优先级任务
|
||||
if (!normalPriorityFutures.isEmpty()) {
|
||||
CompletableFuture.allOf(
|
||||
normalPriorityFutures.toArray(new CompletableFuture[0])
|
||||
).get(processTimeoutMs / 2, TimeUnit.MILLISECONDS);
|
||||
log.info("普通优先级消息处理完成: {}", normalPriorityFutures.size());
|
||||
}
|
||||
|
||||
ack.acknowledge();
|
||||
totalProcessed.addAndGet(records.size());
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("优先级消费处理异常", e);
|
||||
ack.acknowledge();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 异步处理单条消息
|
||||
*/
|
||||
@Async("logNormalProcessorExecutor")
|
||||
public void processSingleMessageAsync(ConsumerRecord<String, String> record) {
|
||||
long startTime = System.currentTimeMillis();
|
||||
|
||||
try {
|
||||
// 模拟消息解析
|
||||
//String message = parseMessage(record);
|
||||
// 模拟业务处理
|
||||
//processBusinessLogic(message);
|
||||
|
||||
String sysLogUUID =getSysLogUUID();
|
||||
String strDeviceInfo= SyslogParser.substringBeforeFirstChar(record.value(),']');
|
||||
Map<String,String> mapdev =SyslogParser.parseKeyValuePairs(strDeviceInfo);
|
||||
|
||||
// 初始化 InfluxDB 客户端
|
||||
Point point = Point.measurement("syslog_security_"+sysLogUUID.substring(0,8) )
|
||||
.addTag("device_id", mapdev.get("device_id")) // 添加设备ID标签
|
||||
.addTag("device_collect_id", mapdev.get("device_collect_id")) // 添加探针ID标签
|
||||
.addTag("uuid", sysLogUUID) //syslog uuid
|
||||
.addTag("topic", AppConfig.getTopic()) //kafka topic
|
||||
.addField("message", record.value()) // 添加字段
|
||||
.addField("receive_time", mapdev.get("receive_time")) // 添加字段
|
||||
.addField("uuid", sysLogUUID)
|
||||
.time(System.currentTimeMillis(), WritePrecision.MS) ;// 毫秒级时间戳
|
||||
influxClient.writePointBlocking(point);
|
||||
|
||||
System.out.println("influxdb wirte syslog ,value:"+ record.key());
|
||||
// 日志信息插入pg XdrHoneypot 表
|
||||
//insertSingleRecord( record.value());
|
||||
|
||||
//String syslogMessage= AppConfig.geRunEnvironment().equals("test")? record.value().substring(34) : record.value();
|
||||
String syslogMessage= record.value();
|
||||
//剔除测试环境本机syslog新增的头部信息
|
||||
LogNormalProcessor logNormalProcessor = new LogNormalProcessor(syslogMessage,sysLogUUID,AppConfig.getTopic());
|
||||
//LogNormalProcessor logNormalProcessor =new LogNormalProcessor(record.value());
|
||||
logNormalProcessor.init();
|
||||
System.out.println("insert postgres syslog ,value:"+ record.key());
|
||||
long costTime = System.currentTimeMillis() - startTime;
|
||||
log.debug("消息处理完成, offset: {}, 耗时: {}ms", record.offset(), costTime);
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("异步处理消息失败, offset: {}", record.offset(), e);
|
||||
// 这里可以添加重试逻辑或死信队列处理
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 处理消息批次
|
||||
*/
|
||||
private void processMessageBatch(List<ConsumerRecord<String, String>> batch, int batchIndex) {
|
||||
long startTime = System.currentTimeMillis();
|
||||
log.debug("开始处理批次: {}, 数量: {}", batchIndex, batch.size());
|
||||
|
||||
try {
|
||||
List<CompletableFuture<Void>> futures = new ArrayList<>();
|
||||
|
||||
// 批次内并行处理
|
||||
for (ConsumerRecord<String, String> record : batch) {
|
||||
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
|
||||
processSingleMessageAsync(record);
|
||||
}, taskExecutor);
|
||||
futures.add(future);
|
||||
}
|
||||
|
||||
// 等待批次内所有任务完成
|
||||
CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]))
|
||||
.get(processTimeoutMs, TimeUnit.MILLISECONDS);
|
||||
|
||||
long costTime = System.currentTimeMillis() - startTime;
|
||||
log.info("批次处理完成: {}, 数量: {}, 总耗时: {}ms",
|
||||
batchIndex, batch.size(), costTime);
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("批次处理异常: {}", batchIndex, e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断是否为高优先级消息
|
||||
*/
|
||||
private boolean isHighPriorityMessage(ConsumerRecord<String, String> record) {
|
||||
// 简单的优先级判断逻辑
|
||||
// 可以根据key、header、或消息内容来判断
|
||||
return record.key() != null &&
|
||||
(record.key().contains("ERROR") || record.key().contains("URGENT"));
|
||||
}
|
||||
|
||||
/**
|
||||
* 消息解析(模拟)
|
||||
*/
|
||||
private String parseMessage(ConsumerRecord<String, String> record) {
|
||||
// 模拟解析耗时
|
||||
try {
|
||||
Thread.sleep(1);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
return record.value();
|
||||
}
|
||||
|
||||
/**
|
||||
* 业务逻辑处理(模拟)
|
||||
*/
|
||||
private void processBusinessLogic(String message) {
|
||||
// 模拟业务处理耗时
|
||||
try {
|
||||
Thread.sleep(5); // 模拟5ms处理时间
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
|
||||
// 这里可以添加具体的业务逻辑
|
||||
// 例如:数据转换、验证、丰富等
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取处理统计信息
|
||||
*/
|
||||
public ProcessingStats getProcessingStats() {
|
||||
return new ProcessingStats(
|
||||
totalProcessed.get(),
|
||||
currentBatchCount.get()
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理统计信息类
|
||||
*/
|
||||
public static class ProcessingStats {
|
||||
private final int totalProcessed;
|
||||
private final int currentBatchCount;
|
||||
|
||||
public ProcessingStats(int totalProcessed, int currentBatchCount) {
|
||||
this.totalProcessed = totalProcessed;
|
||||
this.currentBatchCount = currentBatchCount;
|
||||
}
|
||||
|
||||
public int getTotalProcessed() { return totalProcessed; }
|
||||
public int getCurrentBatchCount() { return currentBatchCount; }
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取日志信息UUID,格式: yyyyMMddxxxxxxxx
|
||||
* @return
|
||||
*/
|
||||
private static String getSysLogUUID ()
|
||||
{
|
||||
// 获取当前日期
|
||||
LocalDate currentDate = LocalDate.now();
|
||||
// 定义格式 (yyyyMMdd)
|
||||
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
|
||||
// 格式化日期
|
||||
String formattedDate = currentDate.format(formatter);
|
||||
return formattedDate +"-"+ UUID.randomUUID() ;
|
||||
}
|
||||
|
||||
}
|
||||
+163
@@ -0,0 +1,163 @@
|
||||
package com.Modules.NormalData;
|
||||
import com.common.entity.RuleContent.Cropper_paramsType;
|
||||
|
||||
import org.json.JSONObject;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import com.common.entity.SyslogMessage;
|
||||
import com.common.util.JsonParser;
|
||||
import com.common.util.SyslogParser;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import com.common.service.DmNormalizeRuleService;
|
||||
import com.common.service.DmColumnService;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import com.common.util.StringExtractorUtil;
|
||||
import com.common.entity.RuleContent.kv_paramsType;
|
||||
|
||||
|
||||
public class logNormalData {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(logNormalData.class);
|
||||
|
||||
private String strLogMsg ;
|
||||
private Map<String, Object> messageMap ;
|
||||
@Autowired
|
||||
public DmNormalizeRuleService dmNormalizeRuleService =new DmNormalizeRuleService();
|
||||
@Autowired
|
||||
public DmColumnService dmColumnService ;
|
||||
|
||||
public logNormalData( String LogMsg) {
|
||||
|
||||
strLogMsg=LogMsg;
|
||||
/** 处理步骤 */
|
||||
//初始化 (获取syslog_normal_data 表全部字段的属性、设备ID对应的规则设置、转化成JSON)
|
||||
//判断数据解析类型(json、键值、xml、正则表达式、分割符)解析syslogMessage 字段转成 HashMAP
|
||||
//匹配规则内容,获取字段映射关系配置,抽取命中的字段名称、数值
|
||||
//判断字段内容及类型,根据数据类型属性,进行内容转换。
|
||||
//生成insert SQL语句、执行入库操作。
|
||||
}
|
||||
|
||||
public Map<String, Object> getMessageToMap( String MsgContent)
|
||||
{
|
||||
//解析SyslogMessage
|
||||
SyslogMessage msg = SyslogParser.parse(MsgContent);
|
||||
System.out.println("解析结果-log content: " + msg.getMessage().toString());
|
||||
Map<String, Object> flatMap = JsonParser.parseJsonToFlatMap(msg.getMessage().toString());
|
||||
flatMap.forEach((key, value) -> System.out.println(key + " = " + value));
|
||||
List<Map<String, Object>> rulelst=dmNormalizeRuleService.selectByDeviceId((long)1);
|
||||
return flatMap;
|
||||
}
|
||||
|
||||
|
||||
public List<Map<String, Object>> getRuleList( long device_id)
|
||||
{
|
||||
List<Map<String, Object>> rulelst=dmNormalizeRuleService.selectByDeviceId((long)1);
|
||||
if (rulelst!=null)
|
||||
{
|
||||
System.out.println("rulelst: " + rulelst);
|
||||
}
|
||||
return rulelst;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析数据项内容,Json格式类型
|
||||
* @param MsgContent
|
||||
* @param cropperParams
|
||||
* @return
|
||||
*/
|
||||
public static String ParserMessageJsonType(String MsgContent , Cropper_paramsType cropperParams)
|
||||
{
|
||||
System.out.println("ParserMessageJsonType MsgContent:" +MsgContent );
|
||||
if(cropperParams ==null) {
|
||||
return removeBOM(JsonParser.extractJsonFromLogMessage(MsgContent));
|
||||
}
|
||||
String strJson ="";
|
||||
if(cropperParams.gettail_key().equals("") && cropperParams.gettail_offset()==0 ) {
|
||||
strJson = StringExtractorUtil.extractFromStartToEnd(MsgContent, cropperParams.gethead_key(), cropperParams.gethead_offset());
|
||||
System.out.println("ParserMessageJsonType extractFromStartToEnd strJson" +strJson );
|
||||
}
|
||||
else {
|
||||
strJson= StringExtractorUtil.extract(MsgContent,cropperParams.gethead_key(),cropperParams.gethead_offset(),cropperParams.gettail_key(),cropperParams.gettail_offset() );
|
||||
//return removeBOM(MsgContent).trim();
|
||||
}
|
||||
return removeBOM(strJson).trim();
|
||||
}
|
||||
|
||||
public static String removeBOM(String s) {
|
||||
if (s != null && s.startsWith("\uFEFF")) {
|
||||
return s.substring(1);
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
|
||||
//获取数据泛化规则的rule_content列表字段,kv类型提取 kv_params 节点值
|
||||
public static kv_paramsType getkv_paramsType( Map<String, Object> dmNormalizeRule )
|
||||
{
|
||||
kv_paramsType kvParams = new kv_paramsType();
|
||||
try {
|
||||
JSONObject jsonObject = new JSONObject( dmNormalizeRule.get("rule_content").toString());
|
||||
if (jsonObject.isEmpty()) return null;
|
||||
kvParams.setInternal(jsonObject.getJSONObject("kv_params").get("internal").toString());
|
||||
kvParams.setExternal(jsonObject.getJSONObject("kv_params").get("external").toString());
|
||||
kvParams.setL_trim(jsonObject.getJSONObject("kv_params").get("l_trim").toString());
|
||||
kvParams.setR_trim( jsonObject.getJSONObject("kv_params").get("r_trim").toString());
|
||||
return kvParams;
|
||||
}catch (Exception ex) {
|
||||
logger.error("getkv_paramsType:"+ex.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
//获取数据泛化规则的rule_content列表字段,sep类型提取 sep 节点值(分隔符)
|
||||
public static String sepType( Map<String, Object> dmNormalizeRule )
|
||||
{
|
||||
|
||||
try {
|
||||
JSONObject jsonObject = new JSONObject( dmNormalizeRule.get("rule_content").toString());
|
||||
if (jsonObject.isEmpty()) return null;
|
||||
return jsonObject.get("sep").toString();
|
||||
}catch (Exception ex) {
|
||||
logger.error("regexp:"+ex.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
//获取数据泛化规则的rule_content列表字段,regex类型提取 regexp 节点值(分隔符)
|
||||
public static String Regexp ( Map <String, Object> dmNormalizeRule )
|
||||
{
|
||||
|
||||
try {
|
||||
JSONObject jsonObject = new JSONObject( dmNormalizeRule.get("rule_content").toString());
|
||||
if (jsonObject.isEmpty()) return null;
|
||||
return jsonObject.get("regexp").toString();
|
||||
}catch (Exception ex) {
|
||||
logger.error("sepType:"+ex.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
public static void main(String[] args) {
|
||||
|
||||
String strlogMessage= "<14>1 2025-09-24T11:52:26Z 5f46d3be75e1 supermario 128 honeypot_event - {\"source\":\"honeypot1\",\"id\":\"f6a13c35-bf9d-4da6-a181-50ce23e7ef6a\",\"start_time\":\"2023-09-03T11:07:02.50167643Z\",\"time\":\"2023-09-03T11:16:18.883885281Z\",\"risk_level\":4,\"connection\":\"b18f3fbe-3fbf-4495-815f-ff26f6fb0bdf\",\"file_info\":null,\"extra\":{\"payload\":{\"format\":\"line\",\"name\":{\"cn\":\"攻击载荷\",\"en\":\"payload\"},\"value\":\"\"},\"uid\":{\"format\":\"line\",\"name\":{\"cn\":\"\",\"en\":\"\"},\"uid\":\"b4cbc73c-25d0-4429-ae1b-a856cdf1a651\",\"value\":\"\"}},\"type\":\"WEB_ATTACK_SCANNER\",\"agent_sn\":\"caa7da42-0cca-4cb1-b501-1f1eb2b588d5\",\"agent_name\":\" 教育局蜜罐探针\",\"honeypot_id\":\"11a9ac6bdf38ae2aaa49ec4f1b4a921bff71952cb9f175bdd8ee1f0497057bc6\",\"honeypot_name\":\"茂名市中小学管理平台管理后台\",\"src_ip\":\"117.50.189.7\",\"src_port\":58512,\"src_mac\":\"\",\"dest_ip\":\"192.168.222.2\",\"dest_port\":9200,\"proxy_ip\":null,\"node\":\"WRx3\"}";
|
||||
String strMsgContent= "{\"source\":\"honeypot1\",\"id\":\"f6a13c35-bf9d-4da6-a181-50ce23e7ef6a\",\"start_time\":\"2023-09-03T11:07:02.50167643Z\",\"time\":\"2023-09-03T11:16:18.883885281Z\",\"risk_level\":4,\"connection\":\"b18f3fbe-3fbf-4495-815f-ff26f6fb0bdf\",\"file_info\":null,\"extra\":{\"payload\":{\"format\":\"line\",\"name\":{\"cn\":\"攻击载荷\",\"en\":\"payload\"},\"value\":\"\"},\"uid\":{\"format\":\"line\",\"name\":{\"cn\":\"\",\"en\":\"\"},\"uid\":\"b4cbc73c-25d0-4429-ae1b-a856cdf1a651\",\"value\":\"\"}},\"type\":\"WEB_ATTACK_SCANNER\",\"agent_sn\":\"caa7da42-0cca-4cb1-b501-1f1eb2b588d5\",\"agent_name\":\" 教育局蜜罐探针\",\"honeypot_id\":\"11a9ac6bdf38ae2aaa49ec4f1b4a921bff71952cb9f175bdd8ee1f0497057bc6\",\"honeypot_name\":\"茂名市中小学管理平台管理后台\",\"src_ip\":\"117.50.189.7\",\"src_port\":58512,\"src_mac\":\"\",\"dest_ip\":\"192.168.222.2\",\"dest_port\":9200,\"proxy_ip\":null,\"node\":\"WRx3\"}";
|
||||
//Map<String, Object> flatMap =(new logNormalData()).getMessageToMap(strMsgContent);
|
||||
//flatMap.forEach((key, value) -> System.out.println(key + " = " + value));
|
||||
logNormalData logData =new logNormalData( strlogMessage);
|
||||
Cropper_paramsType cropperParams =new Cropper_paramsType();
|
||||
cropperParams.settail_offset(0);
|
||||
cropperParams.settail_key("");
|
||||
cropperParams.sethead_key("{");
|
||||
cropperParams.sethead_offset(-1);
|
||||
String str= ParserMessageJsonType(strlogMessage,cropperParams);
|
||||
System.out.println("parser msg:"+str);
|
||||
|
||||
//List<Map<String, Object>> rulelst= logData.getRuleList(1);
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
package com.Modules.etl;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
|
||||
public class TimeWindowCalculator {
|
||||
|
||||
/**
|
||||
* 获取前一个5分钟完整时间周期的开始时间和结束时间
|
||||
* @param currentTime 当前任务调度时间
|
||||
* @return 包含开始时间和结束时间的数组,[0]=开始时间,[1]=结束时间
|
||||
*/
|
||||
public static LocalDateTime[] getPrevious5MinuteWindow(LocalDateTime currentTime) {
|
||||
// 获取当前时间的分钟数
|
||||
int currentMinute = currentTime.getMinute();
|
||||
|
||||
// 计算前一个5分钟周期的结束分钟数(向下取整到5的倍数)
|
||||
int previousWindowEndMinute = (currentMinute / 5) * 5;
|
||||
|
||||
// 构建前一个周期的结束时间
|
||||
LocalDateTime previousWindowEnd = currentTime
|
||||
.withMinute(previousWindowEndMinute)
|
||||
.withSecond(0)
|
||||
.withNano(0);
|
||||
|
||||
// 前一个周期的开始时间是结束时间减去5分钟
|
||||
LocalDateTime previousWindowStart = previousWindowEnd.minusMinutes(5);
|
||||
|
||||
return new LocalDateTime[]{previousWindowStart, previousWindowEnd};
|
||||
}
|
||||
|
||||
/**
|
||||
* 重载方法:使用当前系统时间
|
||||
*/
|
||||
public static LocalDateTime[] getPrevious5MinuteWindow() {
|
||||
return getPrevious5MinuteWindow(LocalDateTime.now());
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
// 测试用例
|
||||
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
|
||||
|
||||
// 测试1: 15:06:00
|
||||
LocalDateTime testTime1 = LocalDateTime.of(2025, 11, 18, 15, 7, 15);
|
||||
LocalDateTime[] window1 = getPrevious5MinuteWindow(testTime1);
|
||||
System.out.println("当前时间: " + testTime1.format(formatter));
|
||||
System.out.println("前一个5分钟周期: " +
|
||||
window1[0].format(formatter) + " - " +
|
||||
window1[1].format(formatter));
|
||||
System.out.println();
|
||||
|
||||
// 测试2: 15:10:00
|
||||
LocalDateTime testTime2 = LocalDateTime.of(2025, 11, 18, 15, 12, 20);
|
||||
LocalDateTime[] window2 = getPrevious5MinuteWindow(testTime2);
|
||||
System.out.println("当前时间: " + testTime2.format(formatter));
|
||||
System.out.println("前一个5分钟周期: " +
|
||||
window2[0].format(formatter) + " - " +
|
||||
window2[1].format(formatter));
|
||||
System.out.println();
|
||||
|
||||
// 测试3: 整点情况 16:00:00
|
||||
LocalDateTime testTime3 = LocalDateTime.of(2025, 11, 18, 16, 0, 15);
|
||||
LocalDateTime[] window3 = getPrevious5MinuteWindow(testTime3);
|
||||
System.out.println("当前时间: " + testTime3.format(formatter));
|
||||
System.out.println("前一个5分钟周期: " +
|
||||
window3[0].format(formatter) + " - " +
|
||||
window3[1].format(formatter));
|
||||
System.out.println();
|
||||
|
||||
// 测试4: 使用当前系统时间
|
||||
LocalDateTime[] currentWindow = getPrevious5MinuteWindow();
|
||||
System.out.println("当前系统时间的前一个5分钟周期: " +
|
||||
currentWindow[0].format(formatter) + " - " +
|
||||
currentWindow[1].format(formatter));
|
||||
}
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package com.Modules.etl.handler;
|
||||
|
||||
|
||||
|
||||
import org.apache.ibatis.type.BaseTypeHandler;
|
||||
import org.apache.ibatis.type.JdbcType;
|
||||
import org.apache.ibatis.type.MappedJdbcTypes;
|
||||
import org.apache.ibatis.type.MappedTypes;
|
||||
import java.sql.*;
|
||||
|
||||
@MappedTypes(byte[][].class)
|
||||
@MappedJdbcTypes(JdbcType.ARRAY)
|
||||
public class ArrayByteTypeHandler extends BaseTypeHandler<byte[][]> {
|
||||
|
||||
@Override
|
||||
public void setNonNullParameter(PreparedStatement ps, int i, byte[][] parameter, JdbcType jdbcType) throws SQLException {
|
||||
Array array = ps.getConnection().createArrayOf("bytea", parameter);
|
||||
ps.setArray(i, array);
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[][] getNullableResult(ResultSet rs, String columnName) throws SQLException {
|
||||
return getArray(rs.getArray(columnName));
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[][] getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
|
||||
return getArray(rs.getArray(columnIndex));
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[][] getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
|
||||
return getArray(cs.getArray(columnIndex));
|
||||
}
|
||||
|
||||
private byte[][] getArray(Array array) throws SQLException {
|
||||
if (array != null) {
|
||||
Object[] objArray = (Object[]) array.getArray();
|
||||
byte[][] result = new byte[objArray.length][];
|
||||
for (int i = 0; i < objArray.length; i++) {
|
||||
result[i] = (byte[]) objArray[i];
|
||||
}
|
||||
return result;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package com.Modules.etl.handler;
|
||||
|
||||
|
||||
import org.apache.ibatis.type.BaseTypeHandler;
|
||||
import org.apache.ibatis.type.JdbcType;
|
||||
import org.apache.ibatis.type.MappedJdbcTypes;
|
||||
import org.apache.ibatis.type.MappedTypes;
|
||||
import java.sql.*;
|
||||
import java.util.Arrays;
|
||||
|
||||
@MappedTypes(Integer[].class)
|
||||
@MappedJdbcTypes(JdbcType.ARRAY)
|
||||
public class ArrayIntegerTypeHandler extends BaseTypeHandler<Integer[]> {
|
||||
|
||||
@Override
|
||||
public void setNonNullParameter(PreparedStatement ps, int i, Integer[] parameter, JdbcType jdbcType) throws SQLException {
|
||||
Array array = ps.getConnection().createArrayOf("integer", parameter);
|
||||
ps.setArray(i, array);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Integer[] getNullableResult(ResultSet rs, String columnName) throws SQLException {
|
||||
return getArray(rs.getArray(columnName));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Integer[] getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
|
||||
return getArray(rs.getArray(columnIndex));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Integer[] getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
|
||||
return getArray(cs.getArray(columnIndex));
|
||||
}
|
||||
|
||||
private Integer[] getArray(Array array) throws SQLException {
|
||||
if (array != null) {
|
||||
Object[] objArray = (Object[]) array.getArray();
|
||||
return Arrays.copyOf(objArray, objArray.length, Integer[].class);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package com.Modules.etl.handler;
|
||||
|
||||
|
||||
import org.apache.ibatis.type.BaseTypeHandler;
|
||||
import org.apache.ibatis.type.JdbcType;
|
||||
import org.apache.ibatis.type.MappedJdbcTypes;
|
||||
import org.apache.ibatis.type.MappedTypes;
|
||||
import java.sql.*;
|
||||
import java.util.Arrays;
|
||||
|
||||
@MappedTypes(String[].class)
|
||||
@MappedJdbcTypes(JdbcType.ARRAY)
|
||||
public class ArrayStringTypeHandler extends BaseTypeHandler<String[]> {
|
||||
|
||||
@Override
|
||||
public void setNonNullParameter(PreparedStatement ps, int i, String[] parameter, JdbcType jdbcType) throws SQLException {
|
||||
Array array = ps.getConnection().createArrayOf("text", parameter);
|
||||
ps.setArray(i, array);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String[] getNullableResult(ResultSet rs, String columnName) throws SQLException {
|
||||
return getArray(rs.getArray(columnName));
|
||||
}
|
||||
|
||||
@Override
|
||||
public String[] getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
|
||||
return getArray(rs.getArray(columnIndex));
|
||||
}
|
||||
|
||||
@Override
|
||||
public String[] getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
|
||||
return getArray(cs.getArray(columnIndex));
|
||||
}
|
||||
|
||||
private String[] getArray(Array array) throws SQLException {
|
||||
if (array != null) {
|
||||
Object[] objArray = (Object[]) array.getArray();
|
||||
return Arrays.copyOf(objArray, objArray.length, String[].class);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package com.Modules.etl.handler;
|
||||
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.retry.annotation.Backoff;
|
||||
import org.springframework.retry.annotation.Recover;
|
||||
import org.springframework.retry.annotation.Retryable;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
public class ETLRetryHandler {
|
||||
|
||||
/**
|
||||
* 带重试机制的ETL任务执行
|
||||
*/
|
||||
@Retryable(value = Exception.class, maxAttempts = 3, backoff = @Backoff(delay = 5000))
|
||||
public void executeWithRetry(Runnable etlTask) {
|
||||
try {
|
||||
etlTask.run();
|
||||
} catch (Exception e) {
|
||||
log.warn("ETL任务执行失败,准备重试", e);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 重试失败后的恢复处理
|
||||
*/
|
||||
@Recover
|
||||
public void recover(Exception e, Runnable etlTask) {
|
||||
log.error("ETL任务重试多次后仍然失败", e);
|
||||
// 这里可以发送告警通知、记录失败状态等
|
||||
throw new RuntimeException("ETL任务最终执行失败", e);
|
||||
}
|
||||
}
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
package com.Modules.etl.handler;
|
||||
|
||||
|
||||
import org.apache.ibatis.type.BaseTypeHandler;
|
||||
import org.apache.ibatis.type.JdbcType;
|
||||
import org.apache.ibatis.type.MappedTypes;
|
||||
|
||||
import java.sql.*;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZoneOffset;
|
||||
|
||||
@MappedTypes(LocalDateTime.class)
|
||||
public class TimestamptzTypeHandler extends BaseTypeHandler<LocalDateTime> {
|
||||
|
||||
@Override
|
||||
public void setNonNullParameter(PreparedStatement ps, int i,
|
||||
LocalDateTime parameter, JdbcType jdbcType)
|
||||
throws SQLException {
|
||||
if (parameter == null) {
|
||||
ps.setTimestamp(i, null);
|
||||
} else {
|
||||
// 转换为Timestamp
|
||||
ps.setTimestamp(i, Timestamp.valueOf(parameter));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public LocalDateTime getNullableResult(ResultSet rs, String columnName)
|
||||
throws SQLException {
|
||||
Timestamp timestamp = rs.getTimestamp(columnName);
|
||||
return convertToLocalDateTime(timestamp);
|
||||
}
|
||||
|
||||
@Override
|
||||
public LocalDateTime getNullableResult(ResultSet rs, int columnIndex)
|
||||
throws SQLException {
|
||||
Timestamp timestamp = rs.getTimestamp(columnIndex);
|
||||
return convertToLocalDateTime(timestamp);
|
||||
}
|
||||
|
||||
@Override
|
||||
public LocalDateTime getNullableResult(CallableStatement cs, int columnIndex)
|
||||
throws SQLException {
|
||||
Timestamp timestamp = cs.getTimestamp(columnIndex);
|
||||
return convertToLocalDateTime(timestamp);
|
||||
}
|
||||
|
||||
private LocalDateTime convertToLocalDateTime(Timestamp timestamp) {
|
||||
if (timestamp == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
// 方法1: 直接从Timestamp转换
|
||||
return timestamp.toLocalDateTime();
|
||||
|
||||
// 方法2: 通过Instant转换(处理时区)
|
||||
// Instant instant = timestamp.toInstant();
|
||||
// return LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
|
||||
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("Failed to convert TIMESTAMPTZ to LocalDateTime", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package com.common.entity;
|
||||
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
public class Alarm {
|
||||
private String id;
|
||||
private LocalDateTime createdAt;
|
||||
private String alarmName;
|
||||
private String alarmLevel;
|
||||
private String alarmType;
|
||||
private String alarmMajorType;
|
||||
private String alarmMinorType;
|
||||
private Integer alarmAreaId;
|
||||
private String[] attackIp;
|
||||
private String[] victimIp;
|
||||
private String[] victimWebUrl;
|
||||
private Integer[] attackChainPhase;
|
||||
private Integer[] deviceId;
|
||||
private String[] tag;
|
||||
private String comment;
|
||||
private String[] originLogIds;
|
||||
private String queryId;
|
||||
private Integer judgedState;
|
||||
private Integer disposedState;
|
||||
private String dispositionAdvice;
|
||||
private Integer attackResult;
|
||||
private Integer fall;
|
||||
private byte[] payload;
|
||||
private Integer[] operateEvent;
|
||||
private Integer[] attackPort;
|
||||
private Integer[] victimPort;
|
||||
private String attackMethod;
|
||||
private String businessExt;
|
||||
private LocalDateTime logStartAt;
|
||||
private LocalDateTime logEndAt;
|
||||
private String httpStatus;
|
||||
private String dnsInfo;
|
||||
private String accountInfo;
|
||||
private String attackerInfo;
|
||||
private String victimInfo;
|
||||
private String suspiciousAction;
|
||||
private String vulnInfo;
|
||||
private String weakPwd;
|
||||
private String complianceBaseline;
|
||||
private String fileInfo;
|
||||
private String fileTags;
|
||||
private String endpointInfo;
|
||||
private String endpointProtection;
|
||||
private String originInfo;
|
||||
private String protocolInfo;
|
||||
private String emailInfo;
|
||||
private String sensitiveData;
|
||||
private Integer hitIntelligence;
|
||||
private String windowTime;
|
||||
private LocalDateTime updatedAt;
|
||||
private String engineType;
|
||||
private String attackIpPic;
|
||||
private String victimIpPic;
|
||||
private LocalDateTime operationAt;
|
||||
private String attackDirection;
|
||||
private LocalDateTime etlTime;
|
||||
private Integer logCount;
|
||||
private Integer isAssetHit;
|
||||
private Boolean focused;
|
||||
private Boolean baseFocused;
|
||||
private Boolean isUpdated;
|
||||
private int alarmSource;
|
||||
private String[] httpReqHeaders;
|
||||
private String[] httpReqBodys;
|
||||
private String[] httpRespHeaders;
|
||||
private String[] httpRespBodys;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package com.common.entity;
|
||||
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
public class AlarmVisit {
|
||||
private String id;
|
||||
private LocalDateTime createdAt;
|
||||
private String alarmName;
|
||||
private String alarmLevel;
|
||||
private String alarmType;
|
||||
private String alarmMajorType;
|
||||
private String alarmMinorType;
|
||||
private Integer alarmAreaId;
|
||||
private String[] attackIp;
|
||||
private String[] victimIp;
|
||||
private String[] victimWebUrl;
|
||||
private Integer[] attackChainPhase;
|
||||
private Integer[] deviceId;
|
||||
private String[] tag;
|
||||
private String comment;
|
||||
private String[] originLogIds;
|
||||
private String queryId;
|
||||
private Integer judgedState;
|
||||
private Integer disposedState;
|
||||
private String dispositionAdvice;
|
||||
private Integer attackResult;
|
||||
private Integer fall;
|
||||
private byte[] payload;
|
||||
private Integer[] operateEvent;
|
||||
private Integer[] attackPort;
|
||||
private Integer[] victimPort;
|
||||
private String attackMethod;
|
||||
private String businessExt;
|
||||
private LocalDateTime logStartAt;
|
||||
private LocalDateTime logEndAt;
|
||||
private String httpStatus;
|
||||
private String dnsInfo;
|
||||
private String accountInfo;
|
||||
private String attackerInfo;
|
||||
private String victimInfo;
|
||||
private String suspiciousAction;
|
||||
private String vulnInfo;
|
||||
private String weakPwd;
|
||||
private String complianceBaseline;
|
||||
private String fileInfo;
|
||||
private String fileTags;
|
||||
private String endpointInfo;
|
||||
private String endpointProtection;
|
||||
private String originInfo;
|
||||
private String protocolInfo;
|
||||
private String emailInfo;
|
||||
private String sensitiveData;
|
||||
private Integer hitIntelligence;
|
||||
private String windowTime;
|
||||
private LocalDateTime updatedAt;
|
||||
private String engineType;
|
||||
private String attackIpPic;
|
||||
private String victimIpPic;
|
||||
private LocalDateTime operationAt;
|
||||
private String attackDirection;
|
||||
private LocalDateTime etlTime;
|
||||
private Integer logCount;
|
||||
private Integer isAssetHit;
|
||||
private Boolean focused;
|
||||
private Boolean baseFocused;
|
||||
private Boolean isUpdated;
|
||||
private int alarmSource;
|
||||
private String[] httpReqHeaders;
|
||||
private String[] httpReqBodys;
|
||||
private String[] httpRespHeaders;
|
||||
private String[] httpRespBodys;
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package com.common.entity;
|
||||
|
||||
public class ApiResponse<T> {
|
||||
|
||||
private boolean success;
|
||||
private String message;
|
||||
private T data;
|
||||
private String errorCode;
|
||||
|
||||
// 成功响应
|
||||
public static <T> ApiResponse<T> success(T data) {
|
||||
ApiResponse<T> response = new ApiResponse<>();
|
||||
response.setSuccess(true);
|
||||
response.setMessage("操作成功");
|
||||
response.setData(data);
|
||||
return response;
|
||||
}
|
||||
|
||||
public static <T> ApiResponse<T> success(String message, T data) {
|
||||
ApiResponse<T> response = new ApiResponse<>();
|
||||
response.setSuccess(true);
|
||||
response.setMessage(message);
|
||||
response.setData(data);
|
||||
return response;
|
||||
}
|
||||
|
||||
// 失败响应
|
||||
public static <T> ApiResponse<T> error(String message) {
|
||||
ApiResponse<T> response = new ApiResponse<>();
|
||||
response.setSuccess(false);
|
||||
response.setMessage(message);
|
||||
return response;
|
||||
}
|
||||
|
||||
public static <T> ApiResponse<T> error(String message, String errorCode) {
|
||||
ApiResponse<T> response = new ApiResponse<>();
|
||||
response.setSuccess(false);
|
||||
response.setMessage(message);
|
||||
response.setErrorCode(errorCode);
|
||||
return response;
|
||||
}
|
||||
|
||||
// Getter和Setter方法
|
||||
public boolean isSuccess() {
|
||||
return success;
|
||||
}
|
||||
|
||||
public void setSuccess(boolean success) {
|
||||
this.success = success;
|
||||
}
|
||||
|
||||
public String getMessage() {
|
||||
return message;
|
||||
}
|
||||
|
||||
public void setMessage(String message) {
|
||||
this.message = message;
|
||||
}
|
||||
|
||||
public T getData() {
|
||||
return data;
|
||||
}
|
||||
|
||||
public void setData(T data) {
|
||||
this.data = data;
|
||||
}
|
||||
|
||||
public String getErrorCode() {
|
||||
return errorCode;
|
||||
}
|
||||
|
||||
public void setErrorCode(String errorCode) {
|
||||
this.errorCode = errorCode;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package com.common.entity;
|
||||
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.data.annotation.Id;
|
||||
import org.springframework.data.elasticsearch.annotations.Document;
|
||||
import org.springframework.data.elasticsearch.annotations.Field;
|
||||
import org.springframework.data.elasticsearch.annotations.FieldType;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
@Data
|
||||
//@Document(indexName = "applog-#{T(java.time.LocalDate).now().format(T(java.time.format.DateTimeFormatter).ofPattern('yyyyMMdd'))}")
|
||||
public class AppLog {
|
||||
|
||||
// ES元数据字段
|
||||
@Id
|
||||
private String id;
|
||||
|
||||
@Field(type = FieldType.Keyword)
|
||||
private String index;
|
||||
|
||||
@Field(type = FieldType.Keyword)
|
||||
private String type = "_doc";
|
||||
|
||||
@Field(type = FieldType.Float)
|
||||
private Float score = 1.0f;
|
||||
|
||||
// 日志内容字段(对应_source)
|
||||
@Field(name = "dtTime", type = FieldType.Long)
|
||||
private Long dtTime;
|
||||
|
||||
@Field(name = "collecttime", type = FieldType.Long)
|
||||
private Long collectTime;
|
||||
|
||||
@Field(name = "logType", type = FieldType.Keyword)
|
||||
private String logType;
|
||||
|
||||
@Field(name = "traceId", type = FieldType.Keyword)
|
||||
private String traceId;
|
||||
|
||||
@Field(name = "method", type = FieldType.Text)
|
||||
private String method;
|
||||
|
||||
@Field(name = "appName", type = FieldType.Keyword)
|
||||
private String appName;
|
||||
|
||||
@Field(name = "ip", type = FieldType.Keyword)
|
||||
private String ip;
|
||||
|
||||
@Field(name = "className", type = FieldType.Text)
|
||||
private String className;
|
||||
|
||||
@Field(name = "env", type = FieldType.Keyword)
|
||||
private String env;
|
||||
|
||||
@Field(name = "content", type = FieldType.Text)
|
||||
private String content;
|
||||
|
||||
@Field(name = "threadName", type = FieldType.Text)
|
||||
private String threadName;
|
||||
|
||||
@Field(name = "logLevel", type = FieldType.Keyword)
|
||||
private String logLevel;
|
||||
|
||||
@Field(name = "seq", type = FieldType.Keyword)
|
||||
private String seq;
|
||||
|
||||
@Field(name = "_indexed_at", type = FieldType.Long)
|
||||
private Long indexedAt;
|
||||
|
||||
// 系统字段
|
||||
private Date createTime = new Date();
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
package com.common.entity;
|
||||
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
public class AppLogEntity {
|
||||
private Long id;
|
||||
|
||||
// ES元数据字段
|
||||
private String esIndex;
|
||||
private String esType = "_doc";
|
||||
private String esId;
|
||||
private Float esScore = 1.0f;
|
||||
|
||||
// 日志内容字段
|
||||
private Long dtTime;
|
||||
private Long collectTime;
|
||||
private String logType;
|
||||
private String traceId;
|
||||
private String method;
|
||||
private String appName;
|
||||
private String ip;
|
||||
private String className;
|
||||
private String env;
|
||||
private String content;
|
||||
private String threadName;
|
||||
private String logLevel;
|
||||
private String seq;
|
||||
private Long indexedAt;
|
||||
|
||||
// 分区字段
|
||||
private LocalDateTime logDate;
|
||||
|
||||
// 系统字段
|
||||
private LocalDateTime createdAt;
|
||||
private LocalDateTime updatedAt;
|
||||
}
|
||||
+98
@@ -0,0 +1,98 @@
|
||||
package com.common.entity;
|
||||
|
||||
import java.time.OffsetDateTime;
|
||||
|
||||
public class DeviceCollectTask {
|
||||
private Integer id;
|
||||
private OffsetDateTime createdAt;
|
||||
private OffsetDateTime updatedAt;
|
||||
private OffsetDateTime deletedAt;
|
||||
private Integer deviceId;
|
||||
private Integer method;
|
||||
private String taskName;
|
||||
private OffsetDateTime firstTime;
|
||||
private OffsetDateTime lastSuccessTime;
|
||||
private OffsetDateTime lastFailedTime;
|
||||
private Integer detailId;
|
||||
private Integer epm;
|
||||
private Integer epmPeak;
|
||||
private Integer processArchitecture;
|
||||
private Integer taskCount;
|
||||
private OffsetDateTime recentDiscoverTime;
|
||||
private Integer epmUpperLimit;
|
||||
|
||||
// Getter and Setter 方法
|
||||
public Integer getId() { return id; }
|
||||
public void setId(Integer id) { this.id = id; }
|
||||
|
||||
public OffsetDateTime getCreatedAt() { return createdAt; }
|
||||
public void setCreatedAt(OffsetDateTime createdAt) { this.createdAt = createdAt; }
|
||||
|
||||
public OffsetDateTime getUpdatedAt() { return updatedAt; }
|
||||
public void setUpdatedAt(OffsetDateTime updatedAt) { this.updatedAt = updatedAt; }
|
||||
|
||||
public OffsetDateTime getDeletedAt() { return deletedAt; }
|
||||
public void setDeletedAt(OffsetDateTime deletedAt) { this.deletedAt = deletedAt; }
|
||||
|
||||
public Integer getDeviceId() { return deviceId; }
|
||||
public void setDeviceId(Integer deviceId) { this.deviceId = deviceId; }
|
||||
|
||||
public Integer getMethod() { return method; }
|
||||
public void setMethod(Integer method) { this.method = method; }
|
||||
|
||||
public String getTaskName() { return taskName; }
|
||||
public void setTaskName(String taskName) { this.taskName = taskName; }
|
||||
|
||||
public OffsetDateTime getFirstTime() { return firstTime; }
|
||||
public void setFirstTime(OffsetDateTime firstTime) { this.firstTime = firstTime; }
|
||||
|
||||
public OffsetDateTime getLastSuccessTime() { return lastSuccessTime; }
|
||||
public void setLastSuccessTime(OffsetDateTime lastSuccessTime) { this.lastSuccessTime = lastSuccessTime; }
|
||||
|
||||
public OffsetDateTime getLastFailedTime() { return lastFailedTime; }
|
||||
public void setLastFailedTime(OffsetDateTime lastFailedTime) { this.lastFailedTime = lastFailedTime; }
|
||||
|
||||
public Integer getDetailId() { return detailId; }
|
||||
public void setDetailId(Integer detailId) { this.detailId = detailId; }
|
||||
|
||||
public Integer getEpm() { return epm; }
|
||||
public void setEpm(Integer epm) { this.epm = epm; }
|
||||
|
||||
public Integer getEpmPeak() { return epmPeak; }
|
||||
public void setEpmPeak(Integer epmPeak) { this.epmPeak = epmPeak; }
|
||||
|
||||
public Integer getProcessArchitecture() { return processArchitecture; }
|
||||
public void setProcessArchitecture(Integer processArchitecture) { this.processArchitecture = processArchitecture; }
|
||||
|
||||
public Integer getTaskCount() { return taskCount; }
|
||||
public void setTaskCount(Integer taskCount) { this.taskCount = taskCount; }
|
||||
|
||||
public OffsetDateTime getRecentDiscoverTime() { return recentDiscoverTime; }
|
||||
public void setRecentDiscoverTime(OffsetDateTime recentDiscoverTime) { this.recentDiscoverTime = recentDiscoverTime; }
|
||||
|
||||
public Integer getEpmUpperLimit() { return epmUpperLimit; }
|
||||
public void setEpmUpperLimit(Integer epmUpperLimit) { this.epmUpperLimit = epmUpperLimit; }
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "DeviceCollectTask{" +
|
||||
"id=" + id +
|
||||
", createdAt=" + createdAt +
|
||||
", updatedAt=" + updatedAt +
|
||||
", deletedAt=" + deletedAt +
|
||||
", deviceId=" + deviceId +
|
||||
", method=" + method +
|
||||
", taskName='" + taskName + '\'' +
|
||||
", firstTime=" + firstTime +
|
||||
", lastSuccessTime=" + lastSuccessTime +
|
||||
", lastFailedTime=" + lastFailedTime +
|
||||
", detailId=" + detailId +
|
||||
", epm=" + epm +
|
||||
", epmPeak=" + epmPeak +
|
||||
", processArchitecture=" + processArchitecture +
|
||||
", taskCount=" + taskCount +
|
||||
", recentDiscoverTime=" + recentDiscoverTime +
|
||||
", epmUpperLimit=" + epmUpperLimit +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
package com.common.entity;
|
||||
|
||||
import lombok.Data;
|
||||
import java.time.LocalDateTime;
|
||||
@Data
|
||||
public class DeviceCollectTaskTime {
|
||||
private String deviceCollectId;
|
||||
private LocalDateTime firstTime; // 首次成功时间
|
||||
private LocalDateTime lastSuccessTime; // 最后成功时间
|
||||
private LocalDateTime lastFailTime; // 最后失败时间
|
||||
}
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
package com.common.entity;
|
||||
|
||||
import lombok.Data;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Builder;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class DeviceReceiveLog {
|
||||
/**
|
||||
* 主键ID
|
||||
*/
|
||||
private Long id;
|
||||
|
||||
/**
|
||||
* 记录创建时间(UTC时间)
|
||||
*/
|
||||
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
|
||||
private LocalDateTime createdAt;
|
||||
|
||||
/**
|
||||
* 采集探针ID
|
||||
*/
|
||||
private Integer deviceCollectId;
|
||||
|
||||
/**
|
||||
* 设备ID
|
||||
*/
|
||||
private Integer deviceId;
|
||||
|
||||
/**
|
||||
* 设备IP(PostgreSQL inet类型,用String处理)
|
||||
*/
|
||||
private String deviceIp;
|
||||
|
||||
/**
|
||||
* 日志收到时间
|
||||
*/
|
||||
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
|
||||
private LocalDateTime receiveTime;
|
||||
|
||||
/**
|
||||
* 接收时间字符串(冗余字段)
|
||||
*/
|
||||
private String receiveTimeStr;
|
||||
|
||||
/**
|
||||
* 原始syslog消息
|
||||
*/
|
||||
private String syslogMessage;
|
||||
|
||||
// 推送是否成功
|
||||
private Boolean pushSuccess;
|
||||
/**
|
||||
* 分页参数(非表字段)
|
||||
*/
|
||||
private Integer pageNum;
|
||||
private Integer pageSize;
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package com.common.entity;
|
||||
|
||||
|
||||
|
||||
import lombok.Data;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
public class DeviceStatsDTO {
|
||||
private Long deviceId;
|
||||
private LocalDateTime lastReceiveTime;
|
||||
private Integer parseCount;
|
||||
private Integer nonLogCount;
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
package com.common.entity;
|
||||
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
public class DmColumn {
|
||||
private Long id;
|
||||
private LocalDateTime createdAt;
|
||||
private LocalDateTime updatedAt;
|
||||
private LocalDateTime deletedAt;
|
||||
private String name;
|
||||
private String displayName;
|
||||
private Long storageDataType;
|
||||
private Long businessDataType;
|
||||
private Boolean isBuiltIn;
|
||||
private Boolean isHidden;
|
||||
private Boolean isNotNormalizable;
|
||||
private Boolean isRequired;
|
||||
private Integer categoryId;
|
||||
private Integer customAssetCategoryId;
|
||||
private Boolean isVirtual;
|
||||
private Integer tableId;
|
||||
private Integer assetTableId;
|
||||
private Integer columnSetId;
|
||||
private Integer baseType;
|
||||
private Integer userTaskId;
|
||||
private Long createdById;
|
||||
private Long createDept;
|
||||
private Long createBy;
|
||||
private LocalDateTime createTime;
|
||||
private Long updateBy;
|
||||
private LocalDateTime updateTime;
|
||||
|
||||
// 构造方法
|
||||
public DmColumn() {}
|
||||
|
||||
public DmColumn(String name, String displayName) {
|
||||
this.name = name;
|
||||
this.displayName = displayName;
|
||||
}
|
||||
|
||||
// getter 和 setter 方法
|
||||
public Long getId() { return id; }
|
||||
public void setId(Long id) { this.id = id; }
|
||||
|
||||
public LocalDateTime getCreatedAt() { return createdAt; }
|
||||
public void setCreatedAt(LocalDateTime createdAt) { this.createdAt = createdAt; }
|
||||
|
||||
public LocalDateTime getUpdatedAt() { return updatedAt; }
|
||||
public void setUpdatedAt(LocalDateTime updatedAt) { this.updatedAt = updatedAt; }
|
||||
|
||||
public LocalDateTime getDeletedAt() { return deletedAt; }
|
||||
public void setDeletedAt(LocalDateTime deletedAt) { this.deletedAt = deletedAt; }
|
||||
|
||||
public String getName() { return name; }
|
||||
public void setName(String name) { this.name = name; }
|
||||
|
||||
public String getDisplayName() { return displayName; }
|
||||
public void setDisplayName(String displayName) { this.displayName = displayName; }
|
||||
|
||||
public Long getStorageDataType() { return storageDataType; }
|
||||
public void setStorageDataType(Long storageDataType) { this.storageDataType = storageDataType; }
|
||||
|
||||
public Long getBusinessDataType() { return businessDataType; }
|
||||
public void setBusinessDataType(Long businessDataType) { this.businessDataType = businessDataType; }
|
||||
|
||||
public Boolean getIsBuiltIn() { return isBuiltIn; }
|
||||
public void setIsBuiltIn(Boolean isBuiltIn) { this.isBuiltIn = isBuiltIn; }
|
||||
|
||||
public Boolean getIsHidden() { return isHidden; }
|
||||
public void setIsHidden(Boolean isHidden) { this.isHidden = isHidden; }
|
||||
|
||||
public Boolean getIsNotNormalizable() { return isNotNormalizable; }
|
||||
public void setIsNotNormalizable(Boolean isNotNormalizable) { this.isNotNormalizable = isNotNormalizable; }
|
||||
|
||||
public Boolean getIsRequired() { return isRequired; }
|
||||
public void setIsRequired(Boolean isRequired) { this.isRequired = isRequired; }
|
||||
|
||||
public Integer getCategoryId() { return categoryId; }
|
||||
public void setCategoryId(Integer categoryId) { this.categoryId = categoryId; }
|
||||
|
||||
public Integer getCustomAssetCategoryId() { return customAssetCategoryId; }
|
||||
public void setCustomAssetCategoryId(Integer customAssetCategoryId) { this.customAssetCategoryId = customAssetCategoryId; }
|
||||
|
||||
public Boolean getIsVirtual() { return isVirtual; }
|
||||
public void setIsVirtual(Boolean isVirtual) { this.isVirtual = isVirtual; }
|
||||
|
||||
public Integer getTableId() { return tableId; }
|
||||
public void setTableId(Integer tableId) { this.tableId = tableId; }
|
||||
|
||||
public Integer getAssetTableId() { return assetTableId; }
|
||||
public void setAssetTableId(Integer assetTableId) { this.assetTableId = assetTableId; }
|
||||
|
||||
public Integer getColumnSetId() { return columnSetId; }
|
||||
public void setColumnSetId(Integer columnSetId) { this.columnSetId = columnSetId; }
|
||||
|
||||
public Integer getBaseType() { return baseType; }
|
||||
public void setBaseType(Integer baseType) { this.baseType = baseType; }
|
||||
|
||||
public Integer getUserTaskId() { return userTaskId; }
|
||||
public void setUserTaskId(Integer userTaskId) { this.userTaskId = userTaskId; }
|
||||
|
||||
public Long getCreatedById() { return createdById; }
|
||||
public void setCreatedById(Long createdById) { this.createdById = createdById; }
|
||||
|
||||
public Long getCreateDept() { return createDept; }
|
||||
public void setCreateDept(Long createDept) { this.createDept = createDept; }
|
||||
|
||||
public Long getCreateBy() { return createBy; }
|
||||
public void setCreateBy(Long createBy) { this.createBy = createBy; }
|
||||
|
||||
public LocalDateTime getCreateTime() { return createTime; }
|
||||
public void setCreateTime(LocalDateTime createTime) { this.createTime = createTime; }
|
||||
|
||||
public Long getUpdateBy() { return updateBy; }
|
||||
public void setUpdateBy(Long updateBy) { this.updateBy = updateBy; }
|
||||
|
||||
public LocalDateTime getUpdateTime() { return updateTime; }
|
||||
public void setUpdateTime(LocalDateTime updateTime) { this.updateTime = updateTime; }
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "DmColumn{" +
|
||||
"id=" + id +
|
||||
", name='" + name + '\'' +
|
||||
", displayName='" + displayName + '\'' +
|
||||
", isBuiltIn=" + isBuiltIn +
|
||||
", isHidden=" + isHidden +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
+131
@@ -0,0 +1,131 @@
|
||||
package com.common.entity;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
public class DmNormalizeRule {
|
||||
private Long id;
|
||||
private LocalDateTime createdAt;
|
||||
private LocalDateTime updatedAt;
|
||||
private LocalDateTime deletedAt;
|
||||
private String name;
|
||||
private String displayName;
|
||||
private String description;
|
||||
private Boolean isBuiltIn;
|
||||
private Boolean isRunning;
|
||||
private LocalDateTime firstDataSavedAt;
|
||||
private String dataType;
|
||||
private Integer fieldCateId;
|
||||
private String logParsed;
|
||||
private String[] sampleLogs;
|
||||
private Boolean isDataMergeEnabled;
|
||||
private Long dataMergeInterval;
|
||||
private String dataMergeTimeUnit;
|
||||
private Long dataMergeRowLimit;
|
||||
private String dataMergeColumns;
|
||||
private Short dataStorageMedium;
|
||||
private Integer createdById;
|
||||
private Integer groupId;
|
||||
private String ruleContent;
|
||||
private String builtInVersion;
|
||||
private String tenantId;
|
||||
private LocalDateTime createTime;
|
||||
private LocalDateTime updateTime;
|
||||
private Long createBy;
|
||||
private Long updateBy;
|
||||
private String delFlag;
|
||||
private Long createDept;
|
||||
|
||||
// getters and setters
|
||||
public Long getId() { return id; }
|
||||
public void setId(Long id) { this.id = id; }
|
||||
|
||||
public LocalDateTime getCreatedAt() { return createdAt; }
|
||||
public void setCreatedAt(LocalDateTime createdAt) { this.createdAt = createdAt; }
|
||||
|
||||
public LocalDateTime getUpdatedAt() { return updatedAt; }
|
||||
public void setUpdatedAt(LocalDateTime updatedAt) { this.updatedAt = updatedAt; }
|
||||
|
||||
public LocalDateTime getDeletedAt() { return deletedAt; }
|
||||
public void setDeletedAt(LocalDateTime deletedAt) { this.deletedAt = deletedAt; }
|
||||
|
||||
public String getName() { return name; }
|
||||
public void setName(String name) { this.name = name; }
|
||||
|
||||
public String getDisplayName() { return displayName; }
|
||||
public void setDisplayName(String displayName) { this.displayName = displayName; }
|
||||
|
||||
public String getDescription() { return description; }
|
||||
public void setDescription(String description) { this.description = description; }
|
||||
|
||||
public Boolean getIsBuiltIn() { return isBuiltIn; }
|
||||
public void setIsBuiltIn(Boolean isBuiltIn) { this.isBuiltIn = isBuiltIn; }
|
||||
|
||||
public Boolean getIsRunning() { return isRunning; }
|
||||
public void setIsRunning(Boolean isRunning) { this.isRunning = isRunning; }
|
||||
|
||||
public LocalDateTime getFirstDataSavedAt() { return firstDataSavedAt; }
|
||||
public void setFirstDataSavedAt(LocalDateTime firstDataSavedAt) { this.firstDataSavedAt = firstDataSavedAt; }
|
||||
|
||||
public String getDataType() { return dataType; }
|
||||
public void setDataType(String dataType) { this.dataType = dataType; }
|
||||
|
||||
public Integer getFieldCateId() { return fieldCateId; }
|
||||
public void setFieldCateId(Integer fieldCateId) { this.fieldCateId = fieldCateId; }
|
||||
|
||||
public String getLogParsed() { return logParsed; }
|
||||
public void setLogParsed(String logParsed) { this.logParsed = logParsed; }
|
||||
|
||||
public String[] getSampleLogs() { return sampleLogs; }
|
||||
public void setSampleLogs(String[] sampleLogs) { this.sampleLogs = sampleLogs; }
|
||||
|
||||
public Boolean getIsDataMergeEnabled() { return isDataMergeEnabled; }
|
||||
public void setIsDataMergeEnabled(Boolean isDataMergeEnabled) { this.isDataMergeEnabled = isDataMergeEnabled; }
|
||||
|
||||
public Long getDataMergeInterval() { return dataMergeInterval; }
|
||||
public void setDataMergeInterval(Long dataMergeInterval) { this.dataMergeInterval = dataMergeInterval; }
|
||||
|
||||
public String getDataMergeTimeUnit() { return dataMergeTimeUnit; }
|
||||
public void setDataMergeTimeUnit(String dataMergeTimeUnit) { this.dataMergeTimeUnit = dataMergeTimeUnit; }
|
||||
|
||||
public Long getDataMergeRowLimit() { return dataMergeRowLimit; }
|
||||
public void setDataMergeRowLimit(Long dataMergeRowLimit) { this.dataMergeRowLimit = dataMergeRowLimit; }
|
||||
|
||||
public String getDataMergeColumns() { return dataMergeColumns; }
|
||||
public void setDataMergeColumns(String dataMergeColumns) { this.dataMergeColumns = dataMergeColumns; }
|
||||
|
||||
public Short getDataStorageMedium() { return dataStorageMedium; }
|
||||
public void setDataStorageMedium(Short dataStorageMedium) { this.dataStorageMedium = dataStorageMedium; }
|
||||
|
||||
public Integer getCreatedById() { return createdById; }
|
||||
public void setCreatedById(Integer createdById) { this.createdById = createdById; }
|
||||
|
||||
public Integer getGroupId() { return groupId; }
|
||||
public void setGroupId(Integer groupId) { this.groupId = groupId; }
|
||||
|
||||
public String getRuleContent() { return ruleContent; }
|
||||
public void setRuleContent(String ruleContent) { this.ruleContent = ruleContent; }
|
||||
|
||||
public String getBuiltInVersion() { return builtInVersion; }
|
||||
public void setBuiltInVersion(String builtInVersion) { this.builtInVersion = builtInVersion; }
|
||||
|
||||
public String getTenantId() { return tenantId; }
|
||||
public void setTenantId(String tenantId) { this.tenantId = tenantId; }
|
||||
|
||||
public LocalDateTime getCreateTime() { return createTime; }
|
||||
public void setCreateTime(LocalDateTime createTime) { this.createTime = createTime; }
|
||||
|
||||
public LocalDateTime getUpdateTime() { return updateTime; }
|
||||
public void setUpdateTime(LocalDateTime updateTime) { this.updateTime = updateTime; }
|
||||
|
||||
public Long getCreateBy() { return createBy; }
|
||||
public void setCreateBy(Long createBy) { this.createBy = createBy; }
|
||||
|
||||
public Long getUpdateBy() { return updateBy; }
|
||||
public void setUpdateBy(Long updateBy) { this.updateBy = updateBy; }
|
||||
|
||||
public String getDelFlag() { return delFlag; }
|
||||
public void setDelFlag(String delFlag) { this.delFlag = delFlag; }
|
||||
|
||||
public Long getCreateDept() { return createDept; }
|
||||
public void setCreateDept(Long createDept) { this.createDept = createDept; }
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package com.common.entity;
|
||||
import lombok.Data;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
public class GroupedSyslogData {
|
||||
private String logDate;
|
||||
private String srcIp;
|
||||
private String destIp;
|
||||
private String[] attackIps;
|
||||
private String originEventName;
|
||||
private Integer attackResult; // 单个attack_result值
|
||||
private LocalDateTime minLogTime;
|
||||
private LocalDateTime maxLogTime;
|
||||
private Long logCount;
|
||||
private String[] victimIps;
|
||||
private Integer[] deviceIds;
|
||||
private String[] originLogIds;
|
||||
private Integer maxEventLevel;
|
||||
private String firstEventType;
|
||||
private String eventType;
|
||||
private String minEventType;
|
||||
private Integer[] attackPorts;
|
||||
private Integer[] victimPorts;
|
||||
private String[] httpStatusCodes;
|
||||
private byte[][] payloadSamples;
|
||||
private String[] httpReqHeaders;
|
||||
private String[] httpReqBodys;
|
||||
private String[] httpRespHeaders;
|
||||
private String[] httpRespBodys;
|
||||
private String victimIpsStr;
|
||||
private Integer[] allAttackResults; // 所有不同的attack_result值
|
||||
private Integer mostCommonAttackResult; // 最常见的attack_result值
|
||||
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package com.common.entity;
|
||||
|
||||
public class RFC3164Message extends SyslogMessage {
|
||||
private String tag;
|
||||
|
||||
public String getTag() { return tag; }
|
||||
public void setTag(String tag) { this.tag = tag; }
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return String.format("RFC3164 [Facility: %d, Severity: %d, Host: %s, Tag: %s, Time: %s, Msg: %s]",
|
||||
facility, severity, hostname, tag, timestamp, message);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package com.common.entity;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class RFC5424Message extends SyslogMessage {
|
||||
private int version;
|
||||
private Map<String, Map<String, String>> structuredData;
|
||||
|
||||
public RFC5424Message() {
|
||||
this.structuredData = new HashMap<>();
|
||||
}
|
||||
|
||||
public int getVersion() {
|
||||
return version;
|
||||
}
|
||||
|
||||
public void setVersion(int version) {
|
||||
this.version = version;
|
||||
}
|
||||
|
||||
public Map<String, Map<String, String>> getStructuredData() {
|
||||
return structuredData;
|
||||
}
|
||||
|
||||
public void setStructuredData(Map<String, Map<String, String>> structuredData) {
|
||||
this.structuredData = structuredData;
|
||||
}
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
package com.common.entity.RuleContent;
|
||||
|
||||
|
||||
public class ActionType {
|
||||
private String type;
|
||||
private String relation_parser_id;
|
||||
private Object sparser_param;
|
||||
private Object param;
|
||||
|
||||
// Constructors
|
||||
public ActionType() {}
|
||||
|
||||
// Getters and Setters
|
||||
public String gettype() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public void settype(String type) {
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
public String getrelation_parser_id() {
|
||||
return relation_parser_id;
|
||||
}
|
||||
|
||||
public void setrelation_parser_id(String relation_parser_id) {
|
||||
this.relation_parser_id = relation_parser_id;
|
||||
}
|
||||
|
||||
public Object getsparser_param() {
|
||||
return sparser_param;
|
||||
}
|
||||
|
||||
public void setsparser_param(Object sparser_param) {
|
||||
this.sparser_param = sparser_param;
|
||||
}
|
||||
|
||||
public Object getparam() {
|
||||
return param;
|
||||
}
|
||||
|
||||
public void setparam(Object param) {
|
||||
this.param = param;
|
||||
}
|
||||
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package com.common.entity.RuleContent;
|
||||
|
||||
|
||||
import lombok.Data;
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
public class CompleteColumn {
|
||||
private String columnName; // 要补全的字段名
|
||||
private Object value; // 补全的值
|
||||
private String filtersRelation; // 条件关系: "and" 或 "or"
|
||||
private List<Condition> conditions; // 条件列表
|
||||
|
||||
// 导入数据相关字段(扩展功能)
|
||||
private String importedDataTableName;
|
||||
private String filtersImportedRelation;
|
||||
private List<Condition> importedConditions;
|
||||
private List<CompleteColumn> completeImportedColumns;
|
||||
}
|
||||
|
||||
@Data
|
||||
class Condition {
|
||||
private String columnName; // 条件字段名
|
||||
private String op; // 操作符: =, !=, in, zero_len, contain, regexp
|
||||
private Object value; // 条件值
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
package com.common.entity.RuleContent;
|
||||
|
||||
|
||||
public class Complete_paramsType {
|
||||
private String name;
|
||||
private String value;
|
||||
private FiltersType filters;
|
||||
|
||||
// Constructors
|
||||
public Complete_paramsType() {}
|
||||
|
||||
// Getters and Setters
|
||||
public String getname() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setname(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getvalue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
public void setvalue(String value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public FiltersType getfilters() {
|
||||
return filters;
|
||||
}
|
||||
|
||||
public void setfilters(FiltersType filters) {
|
||||
this.filters = filters;
|
||||
}
|
||||
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
package com.common.entity.RuleContent;
|
||||
|
||||
|
||||
public class Cropper_paramsType {
|
||||
private String head_key;
|
||||
private Integer head_offset;
|
||||
private String tail_key;
|
||||
private Integer tail_offset;
|
||||
|
||||
// Constructors
|
||||
public Cropper_paramsType() {}
|
||||
|
||||
// Getters and Setters
|
||||
public String gethead_key() {
|
||||
return head_key;
|
||||
}
|
||||
|
||||
public void sethead_key(String head_key) {
|
||||
this.head_key = head_key;
|
||||
}
|
||||
|
||||
public Integer gethead_offset() {
|
||||
return head_offset;
|
||||
}
|
||||
|
||||
public void sethead_offset(Integer head_offset) {
|
||||
this.head_offset = head_offset;
|
||||
}
|
||||
|
||||
public String gettail_key() {
|
||||
return tail_key;
|
||||
}
|
||||
|
||||
public void settail_key(String tail_key) {
|
||||
this.tail_key = tail_key;
|
||||
}
|
||||
|
||||
public Integer gettail_offset() {
|
||||
return tail_offset;
|
||||
}
|
||||
|
||||
public void settail_offset(Integer tail_offset) {
|
||||
this.tail_offset = tail_offset;
|
||||
}
|
||||
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package com.common.entity.RuleContent;
|
||||
|
||||
import lombok.Data;
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
public class FilterParam {
|
||||
private List<FilterGroup> filtersParams;
|
||||
}
|
||||
|
||||
@Data
|
||||
class FilterGroup {
|
||||
private List<FilterExpression> expressions;
|
||||
private String filtersRelation; // "and" 或 "or"
|
||||
}
|
||||
|
||||
@Data
|
||||
class FilterExpression {
|
||||
private String columnName; // 字段名
|
||||
private String op; // 操作符: =, !=, in, zero_len, contain, regexp
|
||||
private Object value; // 值,可能是字符串、数组等
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package com.common.entity.RuleContent;
|
||||
|
||||
public class FiltersType {
|
||||
|
||||
// Constructors
|
||||
public FiltersType() {}
|
||||
|
||||
// Getters and Setters
|
||||
}
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
package com.common.entity.RuleContent;
|
||||
|
||||
|
||||
public class MappersType {
|
||||
private Integer capture_group_index;
|
||||
private String origin_field;
|
||||
private String src_field;
|
||||
private String dest_field;
|
||||
private String value;
|
||||
private String assigned_value;
|
||||
private Integer strategy;
|
||||
private String mapping_rule_name;
|
||||
private ActionType action;
|
||||
|
||||
// Constructors
|
||||
public MappersType() {}
|
||||
|
||||
// Getters and Setters
|
||||
public Integer getcapture_group_index() {
|
||||
return capture_group_index;
|
||||
}
|
||||
|
||||
public void setcapture_group_index(Integer capture_group_index) {
|
||||
this.capture_group_index = capture_group_index;
|
||||
}
|
||||
|
||||
public String getorigin_field() {
|
||||
return origin_field;
|
||||
}
|
||||
|
||||
public void setorigin_field(String origin_field) {
|
||||
this.origin_field = origin_field;
|
||||
}
|
||||
|
||||
public String getsrc_field() {
|
||||
return src_field;
|
||||
}
|
||||
|
||||
public void setsrc_field(String src_field) {
|
||||
this.src_field = src_field;
|
||||
}
|
||||
|
||||
public String getdest_field() {
|
||||
return dest_field;
|
||||
}
|
||||
|
||||
public void setdest_field(String dest_field) {
|
||||
this.dest_field = dest_field;
|
||||
}
|
||||
|
||||
public String getvalue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
public void setvalue(String value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public String getassigned_value() {
|
||||
return assigned_value;
|
||||
}
|
||||
|
||||
public void setassigned_value(String assigned_value) {
|
||||
this.assigned_value = assigned_value;
|
||||
}
|
||||
|
||||
public Integer getstrategy() {
|
||||
return strategy;
|
||||
}
|
||||
|
||||
public void setstrategy(Integer strategy) {
|
||||
this.strategy = strategy;
|
||||
}
|
||||
|
||||
public String getmapping_rule_name() {
|
||||
return mapping_rule_name;
|
||||
}
|
||||
|
||||
public void setmapping_rule_name(String mapping_rule_name) {
|
||||
this.mapping_rule_name = mapping_rule_name;
|
||||
}
|
||||
|
||||
public ActionType getaction() {
|
||||
return action;
|
||||
}
|
||||
|
||||
public void setaction(ActionType action) {
|
||||
this.action = action;
|
||||
}
|
||||
|
||||
}
|
||||
+140
@@ -0,0 +1,140 @@
|
||||
package com.common.entity.RuleContent;
|
||||
import java.util.List;
|
||||
import java.util.ArrayList;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.common.entity.RuleContent.*;
|
||||
|
||||
|
||||
public class Root {
|
||||
private Integer field_cate_id;
|
||||
private Integer field_cate_table_name;
|
||||
private String rule_name;
|
||||
private String data_type;
|
||||
private String decode;
|
||||
private List<String> keywords;
|
||||
private Cropper_paramsType cropper_params;
|
||||
private Object second_parsers;
|
||||
private Object second_parsers_v2;
|
||||
private List<MappersType> mappers;
|
||||
private String filters_params;
|
||||
private List<Complete_paramsType> complete_params;
|
||||
private String complete_columns;
|
||||
private Integer data_storage_medium;
|
||||
|
||||
// Constructors
|
||||
public Root() {}
|
||||
|
||||
// Getters and Setters
|
||||
public Integer getfield_cate_id() {
|
||||
return field_cate_id;
|
||||
}
|
||||
|
||||
public void setfield_cate_id(Integer field_cate_id) {
|
||||
this.field_cate_id = field_cate_id;
|
||||
}
|
||||
|
||||
public Integer getfield_cate_table_name() {
|
||||
return field_cate_table_name;
|
||||
}
|
||||
|
||||
public void setfield_cate_table_name(Integer field_cate_table_name) {
|
||||
this.field_cate_table_name = field_cate_table_name;
|
||||
}
|
||||
|
||||
public String getrule_name() {
|
||||
return rule_name;
|
||||
}
|
||||
|
||||
public void setrule_name(String rule_name) {
|
||||
this.rule_name = rule_name;
|
||||
}
|
||||
|
||||
public String getdata_type() {
|
||||
return data_type;
|
||||
}
|
||||
|
||||
public void setdata_type(String data_type) {
|
||||
this.data_type = data_type;
|
||||
}
|
||||
|
||||
public String getdecode() {
|
||||
return decode;
|
||||
}
|
||||
|
||||
public void setdecode(String decode) {
|
||||
this.decode = decode;
|
||||
}
|
||||
|
||||
public List<String> getkeywords() {
|
||||
return keywords;
|
||||
}
|
||||
|
||||
public void setkeywords(List<String> keywords) {
|
||||
this.keywords = keywords;
|
||||
}
|
||||
|
||||
public Cropper_paramsType getcropper_params() {
|
||||
return cropper_params;
|
||||
}
|
||||
|
||||
public void setcropper_params(Cropper_paramsType cropper_params) {
|
||||
this.cropper_params = cropper_params;
|
||||
}
|
||||
|
||||
public Object getsecond_parsers() {
|
||||
return second_parsers;
|
||||
}
|
||||
|
||||
public void setsecond_parsers(Object second_parsers) {
|
||||
this.second_parsers = second_parsers;
|
||||
}
|
||||
|
||||
public Object getsecond_parsers_v2() {
|
||||
return second_parsers_v2;
|
||||
}
|
||||
|
||||
public void setsecond_parsers_v2(Object second_parsers_v2) {
|
||||
this.second_parsers_v2 = second_parsers_v2;
|
||||
}
|
||||
|
||||
public List<MappersType> getmappers() {
|
||||
return mappers;
|
||||
}
|
||||
|
||||
public void setmappers(List<MappersType> mappers) {
|
||||
this.mappers = mappers;
|
||||
}
|
||||
|
||||
public String getfilters_params() {
|
||||
return filters_params;
|
||||
}
|
||||
|
||||
public void setfilters_params(String filters_params) {
|
||||
this.filters_params = filters_params;
|
||||
}
|
||||
|
||||
public List<Complete_paramsType> getcomplete_params() {
|
||||
return complete_params;
|
||||
}
|
||||
|
||||
public void setcomplete_params(List<Complete_paramsType> complete_params) {
|
||||
this.complete_params = complete_params;
|
||||
}
|
||||
|
||||
public String getcomplete_columns() {
|
||||
return complete_columns;
|
||||
}
|
||||
|
||||
public void setcomplete_columns(String complete_columns) {
|
||||
this.complete_columns = complete_columns;
|
||||
}
|
||||
|
||||
public Integer getdata_storage_medium() {
|
||||
return data_storage_medium;
|
||||
}
|
||||
|
||||
public void setdata_storage_medium(Integer data_storage_medium) {
|
||||
this.data_storage_medium = data_storage_medium;
|
||||
}
|
||||
|
||||
}
|
||||
+139
@@ -0,0 +1,139 @@
|
||||
package com.common.entity.RuleContent;
|
||||
import java.util.List;
|
||||
import java.util.ArrayList;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.common.entity.RuleContent.*;
|
||||
public class RuleContent {
|
||||
|
||||
private Integer field_cate_id;
|
||||
private Integer field_cate_table_name;
|
||||
private String rule_name;
|
||||
private String data_type;
|
||||
private String decode;
|
||||
private List<String> keywords;
|
||||
private Cropper_paramsType cropper_params;
|
||||
private Object second_parsers;
|
||||
private Object second_parsers_v2;
|
||||
private List<MappersType> mappers;
|
||||
private String filters_params;
|
||||
private List<Complete_paramsType> complete_params;
|
||||
private String complete_columns;
|
||||
private Integer data_storage_medium;
|
||||
|
||||
// Constructors
|
||||
public RuleContent() {}
|
||||
|
||||
// Getters and Setters
|
||||
public Integer getfield_cate_id() {
|
||||
return field_cate_id;
|
||||
}
|
||||
|
||||
public void setfield_cate_id(Integer field_cate_id) {
|
||||
this.field_cate_id = field_cate_id;
|
||||
}
|
||||
|
||||
public Integer getfield_cate_table_name() {
|
||||
return field_cate_table_name;
|
||||
}
|
||||
|
||||
public void setfield_cate_table_name(Integer field_cate_table_name) {
|
||||
this.field_cate_table_name = field_cate_table_name;
|
||||
}
|
||||
|
||||
public String getrule_name() {
|
||||
return rule_name;
|
||||
}
|
||||
|
||||
public void setrule_name(String rule_name) {
|
||||
this.rule_name = rule_name;
|
||||
}
|
||||
|
||||
public String getdata_type() {
|
||||
return data_type;
|
||||
}
|
||||
|
||||
public void setdata_type(String data_type) {
|
||||
this.data_type = data_type;
|
||||
}
|
||||
|
||||
public String getdecode() {
|
||||
return decode;
|
||||
}
|
||||
|
||||
public void setdecode(String decode) {
|
||||
this.decode = decode;
|
||||
}
|
||||
|
||||
public List<String> getkeywords() {
|
||||
return keywords;
|
||||
}
|
||||
|
||||
public void setkeywords(List<String> keywords) {
|
||||
this.keywords = keywords;
|
||||
}
|
||||
|
||||
public Cropper_paramsType getcropper_params() {
|
||||
return cropper_params;
|
||||
}
|
||||
|
||||
public void setcropper_params(Cropper_paramsType cropper_params) {
|
||||
this.cropper_params = cropper_params;
|
||||
}
|
||||
|
||||
public Object getsecond_parsers() {
|
||||
return second_parsers;
|
||||
}
|
||||
|
||||
public void setsecond_parsers(Object second_parsers) {
|
||||
this.second_parsers = second_parsers;
|
||||
}
|
||||
|
||||
public Object getsecond_parsers_v2() {
|
||||
return second_parsers_v2;
|
||||
}
|
||||
|
||||
public void setsecond_parsers_v2(Object second_parsers_v2) {
|
||||
this.second_parsers_v2 = second_parsers_v2;
|
||||
}
|
||||
|
||||
public List<MappersType> getmappers() {
|
||||
return mappers;
|
||||
}
|
||||
|
||||
public void setmappers(List<MappersType> mappers) {
|
||||
this.mappers = mappers;
|
||||
}
|
||||
|
||||
public String getfilters_params() {
|
||||
return filters_params;
|
||||
}
|
||||
|
||||
public void setfilters_params(String filters_params) {
|
||||
this.filters_params = filters_params;
|
||||
}
|
||||
|
||||
public List<Complete_paramsType> getcomplete_params() {
|
||||
return complete_params;
|
||||
}
|
||||
|
||||
public void setcomplete_params(List<Complete_paramsType> complete_params) {
|
||||
this.complete_params = complete_params;
|
||||
}
|
||||
|
||||
public String getcomplete_columns() {
|
||||
return complete_columns;
|
||||
}
|
||||
|
||||
public void setcomplete_columns(String complete_columns) {
|
||||
this.complete_columns = complete_columns;
|
||||
}
|
||||
|
||||
public Integer getdata_storage_medium() {
|
||||
return data_storage_medium;
|
||||
}
|
||||
|
||||
public void setdata_storage_medium(Integer data_storage_medium) {
|
||||
this.data_storage_medium = data_storage_medium;
|
||||
}
|
||||
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
package com.common.entity.RuleContent;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class kv_paramsType {
|
||||
private String internal;
|
||||
private String external;
|
||||
private String l_trim;
|
||||
private String r_trim;
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package com.common.entity;
|
||||
|
||||
import lombok.Data;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
public class SecExceptionAlgorithm {
|
||||
private Long id;
|
||||
private String algorithmName;
|
||||
private String exceptionType;
|
||||
private String dataSource;
|
||||
private Integer status; // 1启用
|
||||
private String description;
|
||||
private String configInfo;
|
||||
private String operatorZipUrl;
|
||||
private String remark;
|
||||
private String createBy;
|
||||
private LocalDateTime createTime;
|
||||
private String updateBy;
|
||||
private LocalDateTime updateTime;
|
||||
private String tenantId;
|
||||
private String delFlag;
|
||||
private Long createDept;
|
||||
private String apiUrl; // API URL
|
||||
private String apiMethod; // GET/POST
|
||||
private String respUrl;
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package com.common.entity;
|
||||
|
||||
import java.time.OffsetDateTime;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
// 基础 Syslog 消息类
|
||||
public abstract class SyslogMessage {
|
||||
protected int priority;
|
||||
protected int facility;
|
||||
protected int severity;
|
||||
protected String hostname;
|
||||
protected String appName;
|
||||
protected String procId;
|
||||
protected String msgId;
|
||||
protected String message;
|
||||
protected OffsetDateTime timestamp;
|
||||
|
||||
// Getters and Setters
|
||||
public int getPriority() { return priority; }
|
||||
public void setPriority(int priority) {
|
||||
this.priority = priority;
|
||||
this.facility = priority / 8;
|
||||
this.severity = priority % 8;
|
||||
}
|
||||
|
||||
public int getFacility() { return facility; }
|
||||
public int getSeverity() { return severity; }
|
||||
public String getHostname() { return hostname; }
|
||||
public void setHostname(String hostname) { this.hostname = hostname; }
|
||||
public String getAppName() { return appName; }
|
||||
public void setAppName(String appName) { this.appName = appName; }
|
||||
public String getProcId() { return procId; }
|
||||
public void setProcId(String procId) { this.procId = procId; }
|
||||
public String getMsgId() { return msgId; }
|
||||
public void setMsgId(String msgId) { this.msgId = msgId; }
|
||||
public String getMessage() { return message; }
|
||||
public void setMessage(String message) { this.message = message; }
|
||||
public OffsetDateTime getTimestamp() { return timestamp; }
|
||||
public void setTimestamp(OffsetDateTime timestamp) { this.timestamp = timestamp; }
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return String.format("Facility: %d, Severity: %d, Host: %s, App: %s, Time: %s, Msg: %s",
|
||||
facility, severity, hostname, appName, timestamp, message);
|
||||
}
|
||||
}
|
||||
+162
@@ -0,0 +1,162 @@
|
||||
package com.common.entity;
|
||||
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.*;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.OffsetDateTime;
|
||||
|
||||
/**
|
||||
* 非标日志实体类
|
||||
*/
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = false)
|
||||
@TableName("syslog_non_normal_message")
|
||||
public class SyslogNonNormalMessage {
|
||||
|
||||
/**
|
||||
* 非标ID
|
||||
*/
|
||||
@TableId(value = "id", type = IdType.INPUT)
|
||||
private String id;
|
||||
|
||||
/**
|
||||
* 记录时间(UTC时区)
|
||||
*/
|
||||
@TableField("created_at")
|
||||
private OffsetDateTime createdAt;
|
||||
|
||||
/**
|
||||
* log处理时间
|
||||
*/
|
||||
@TableField("log_time")
|
||||
private LocalDateTime logTime;
|
||||
|
||||
/**
|
||||
* 设备ID
|
||||
*/
|
||||
@TableField("device_id")
|
||||
private Integer deviceId;
|
||||
|
||||
/**
|
||||
* 原始日志
|
||||
*/
|
||||
@TableField("syslog_message")
|
||||
private String syslogMessage;
|
||||
|
||||
/**
|
||||
* 安全日志ID
|
||||
*/
|
||||
@TableField("syslog_uuid")
|
||||
private String syslogUuid;
|
||||
|
||||
/**
|
||||
* kafka topic
|
||||
*/
|
||||
@TableField("syslog_topic")
|
||||
private String syslogTopic;
|
||||
|
||||
/**
|
||||
* 租户ID
|
||||
*/
|
||||
@TableField("tenant_id")
|
||||
private String tenantId;
|
||||
|
||||
/**
|
||||
* 创建时间
|
||||
*/
|
||||
@TableField("create_time")
|
||||
private LocalDateTime createTime;
|
||||
|
||||
/**
|
||||
* 更新时间
|
||||
*/
|
||||
@TableField("update_time")
|
||||
private LocalDateTime updateTime;
|
||||
|
||||
/**
|
||||
* 创建者
|
||||
*/
|
||||
@TableField("create_by")
|
||||
private Long createBy;
|
||||
|
||||
/**
|
||||
* 更新者
|
||||
*/
|
||||
@TableField("update_by")
|
||||
private Long updateBy;
|
||||
|
||||
/**
|
||||
* 创建部门
|
||||
*/
|
||||
@TableField("create_dept")
|
||||
private Long createDept;
|
||||
|
||||
/**
|
||||
* 采集头部消息
|
||||
*/
|
||||
@TableField("header_message")
|
||||
private String headerMessage;
|
||||
|
||||
/**
|
||||
* 接收时间
|
||||
*/
|
||||
@TableField("receive_time")
|
||||
private LocalDateTime receiveTime;
|
||||
|
||||
/**
|
||||
* 泛化时间
|
||||
*/
|
||||
@TableField("rule_time")
|
||||
private LocalDateTime ruleTime;
|
||||
|
||||
/**
|
||||
* 设备名称
|
||||
*/
|
||||
@TableField("device_name")
|
||||
private String deviceName;
|
||||
|
||||
/**
|
||||
* ETL处理节点
|
||||
*/
|
||||
@TableField("etl_node")
|
||||
private String etlNode;
|
||||
|
||||
/**
|
||||
* 采集任务ID
|
||||
*/
|
||||
@TableField("collect_task_id")
|
||||
private Integer collectTaskId;
|
||||
|
||||
/**
|
||||
* 采集任务名称
|
||||
*/
|
||||
@TableField("collect_task_name")
|
||||
private String collectTaskName;
|
||||
|
||||
/**
|
||||
* 非标原因
|
||||
*/
|
||||
@TableField("reason")
|
||||
private String reason;
|
||||
|
||||
/**
|
||||
* 详细原因
|
||||
*/
|
||||
@TableField("reason_detail")
|
||||
private String reasonDetail;
|
||||
|
||||
/**
|
||||
* 泛化结果
|
||||
*/
|
||||
@TableField("rule_result")
|
||||
private String ruleResult;
|
||||
|
||||
/**
|
||||
* 删除标志
|
||||
*/
|
||||
@TableField("del_flag")
|
||||
private String delFlag;
|
||||
}
|
||||
+383
@@ -0,0 +1,383 @@
|
||||
package com.common.entity;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
public class SyslogNormalAlarm {
|
||||
private String id;
|
||||
private LocalDateTime createdAt;
|
||||
private LocalDateTime logTime;
|
||||
private Integer deviceId;
|
||||
private String webshellType;
|
||||
private String vuirsType;
|
||||
private String vuirsUrl;
|
||||
private String classFilename;
|
||||
private String classPath;
|
||||
private String parentClass;
|
||||
private String jarPath;
|
||||
private String classMd5;
|
||||
private String classLoader;
|
||||
private String classHashcode;
|
||||
private String classLoaderHashcode;
|
||||
private String tcNameip;
|
||||
private String performSql;
|
||||
private String tcAccount;
|
||||
private String tcAppname;
|
||||
private String processUname;
|
||||
private String pProcessUname;
|
||||
private String containerName;
|
||||
private String containerId;
|
||||
private String httpRespServer;
|
||||
private Long srcipId;
|
||||
private String cdnip;
|
||||
private String natip;
|
||||
private String mailSender;
|
||||
private String mailReceiver;
|
||||
private String vpnMac;
|
||||
private String vpnOs;
|
||||
private String vpnUser;
|
||||
private String vpnGroupname;
|
||||
private String vpnAccessIp;
|
||||
private Boolean destIpApt;
|
||||
private String originAttackResult;
|
||||
private String description;
|
||||
private String solution;
|
||||
private String attackCause;
|
||||
private String username;
|
||||
private String tcFlowId;
|
||||
private String loginResult;
|
||||
private String cmdline;
|
||||
private String originAttackAction;
|
||||
private String victimDomain;
|
||||
private String vpnDeviceid;
|
||||
private String vpnAccessAction;
|
||||
private Long fileAccessTime;
|
||||
private String fileName;
|
||||
private String tcClass;
|
||||
private String tcName2;
|
||||
private Long loginLasttime;
|
||||
private String originPermissions;
|
||||
private String beginPermissions;
|
||||
private Long printTime;
|
||||
private String printer;
|
||||
private String printerType;
|
||||
private Long printPages;
|
||||
private Long printCopies;
|
||||
private String srcDevice;
|
||||
private String dstDevice;
|
||||
private String srcFile;
|
||||
private String srcFileType;
|
||||
private String srcFilePath;
|
||||
private String dstFile;
|
||||
private String dstFileType;
|
||||
private String dstFilePath;
|
||||
private String dlpPolicyName;
|
||||
private String dlpPolicyType;
|
||||
private String dstUploadUrl;
|
||||
private String processUuid;
|
||||
private String pProcessUuid;
|
||||
private String env;
|
||||
private String bruteForceService;
|
||||
private String vuirsName;
|
||||
private Long httpReqLength;
|
||||
private String httpReqContentType;
|
||||
private String tcScanPort;
|
||||
private String tcLabels;
|
||||
private String httpRespContentType;
|
||||
private String dnsMsgType;
|
||||
private String dnsAnswerLength;
|
||||
private Boolean dnsIoc;
|
||||
private BigDecimal txBytes;
|
||||
private BigDecimal rxBytes;
|
||||
private BigDecimal allBytes;
|
||||
private Long durationTime;
|
||||
private String mailAttachName;
|
||||
private String mailSubject;
|
||||
private String mailMessage;
|
||||
private String mailSendServer;
|
||||
private String mailAgent;
|
||||
private String tlsVersion;
|
||||
private String tlsServerCert;
|
||||
private String tlsServerSuite;
|
||||
private String tlsClientSuitesLen;
|
||||
private String tlsJa3;
|
||||
private String tlsJa3s;
|
||||
private String vpnAccessPort;
|
||||
private String logTopic;
|
||||
private Long collectTime;
|
||||
private Boolean srcIsIntranetip;
|
||||
private Boolean srcIpIoc;
|
||||
private Boolean srcIpApt;
|
||||
private String srcipName;
|
||||
private String tcClient;
|
||||
private Long srcipOrganizationId;
|
||||
private Boolean destIpIntranetip;
|
||||
private Boolean destIpIoc;
|
||||
private Long desipId;
|
||||
private String desipName;
|
||||
private String tcHostip;
|
||||
private Long desipOrganizationId;
|
||||
private String originConfidence;
|
||||
private String originMalscore;
|
||||
private String attackerIcampaign;
|
||||
private Long attackerHostAssetId;
|
||||
private Long attackerOrganizationId;
|
||||
private Long victimHostAssetId;
|
||||
private Long victimOrganizationId;
|
||||
private Long logoutTime;
|
||||
private String httpReqLine;
|
||||
private String desipSecurityScopeId;
|
||||
private String srcipSecurityScopeId;
|
||||
private Long httpRespLength;
|
||||
private String tcAttackType;
|
||||
private String tcRealip;
|
||||
private String attackerIpLists;
|
||||
private String loginPassword;
|
||||
private String detail;
|
||||
private String attackerCountryCode;
|
||||
private String attackerRegionCode;
|
||||
private String victimRegionCode;
|
||||
private String payload;
|
||||
private String httpReferer;
|
||||
private String httpUserAgent;
|
||||
private String httpSession;
|
||||
private String httpQueryString;
|
||||
private String filePath;
|
||||
private String filePermission;
|
||||
private String loginAbnormalType;
|
||||
private String fileTag;
|
||||
private String filePlatform;
|
||||
private String targetIp;
|
||||
private String collectDate;
|
||||
private String tcClientIp;
|
||||
private String tcServerIp;
|
||||
private String tcExternalip;
|
||||
private Long httpStatusCode;
|
||||
private String deviceDomian;
|
||||
private String srcIpStr;
|
||||
private String srcPortStr;
|
||||
private String destIpStr;
|
||||
private String destPortStr;
|
||||
private String pcap;
|
||||
private String ioc;
|
||||
private String maliciousFamily;
|
||||
private String vulnCve;
|
||||
private String aliyunType;
|
||||
private String attackerHostAssetName;
|
||||
private String attackerOrganizationName;
|
||||
private String ctId;
|
||||
private String cveList;
|
||||
private String desipOrganizationName;
|
||||
private String destIpGroup;
|
||||
private String fileGid;
|
||||
private String fileOwner;
|
||||
private String fileOwnergroup;
|
||||
private String fileUid;
|
||||
private String httpRespCookie;
|
||||
private String originRuleId;
|
||||
private String originRuleName;
|
||||
private String serviceName;
|
||||
private String srcIpAssetGroup;
|
||||
private String srcipOrganizationName;
|
||||
private String victimHostAssetName;
|
||||
private Long httpRespCodes;
|
||||
private String victimOrganizationName;
|
||||
private String tcType;
|
||||
private String direction;
|
||||
private String httpReqCookie;
|
||||
private String httpReqProtocol;
|
||||
private String httpReqHeaderRaw;
|
||||
private String httpUrl;
|
||||
private String uname;
|
||||
private String originHostname;
|
||||
private String originOs;
|
||||
private String originAgentMac;
|
||||
private String originHostId;
|
||||
private String originAgentVersion;
|
||||
private String originAgentId;
|
||||
private String originAgentName;
|
||||
private String originWorkGroup;
|
||||
private String originAssetGroup;
|
||||
private Long originLocalPort;
|
||||
private String originAgentIp;
|
||||
private String originInternalIp;
|
||||
private String originExternalIp;
|
||||
private String originLocalAddr;
|
||||
private Long agentId;
|
||||
private String agentName;
|
||||
private String tcTitle;
|
||||
private String logId;
|
||||
private LocalDateTime eventDate;
|
||||
private Long eventTimeTs;
|
||||
private Integer eventLevel;
|
||||
private String srcIp;
|
||||
private Long srcPort;
|
||||
private String destIp;
|
||||
private Long destPort;
|
||||
private Long eventTime;
|
||||
private String attackerCountry;
|
||||
private String srcMac;
|
||||
private String destMac;
|
||||
private String proto;
|
||||
private Long devId;
|
||||
private Long createdTime;
|
||||
private String srcCountry;
|
||||
private String srcCountryCode;
|
||||
private String srcRegion;
|
||||
private String srcRegionCode;
|
||||
private String srcCity;
|
||||
private String srcLon;
|
||||
private String httpMethod;
|
||||
private String httpHost;
|
||||
private String httpReqHeader;
|
||||
private String httpReqBody;
|
||||
private String httpRespHeader;
|
||||
private String httpRespBody;
|
||||
private String fileType;
|
||||
private String fileMd5;
|
||||
private String fileSize;
|
||||
private String process;
|
||||
private Long startTime;
|
||||
private String action;
|
||||
private String attackerRegion;
|
||||
private Long endTime;
|
||||
private Long fileCreatedTime;
|
||||
private Long fileModifiedTime;
|
||||
private String tcMiguanScanPort;
|
||||
private String processPath;
|
||||
private String parentProcessPath;
|
||||
private String gname;
|
||||
private String exeName;
|
||||
private String exePath;
|
||||
private Long loginTime;
|
||||
private Long loginTimes;
|
||||
private String checkItem;
|
||||
private String checkType;
|
||||
private String attackerIp;
|
||||
private Long attackerPort;
|
||||
private String victimIp;
|
||||
private Long victimPort;
|
||||
private String attackerCity;
|
||||
private String attackerLon;
|
||||
private String attackerLat;
|
||||
private String victimCountry;
|
||||
private String victimRegion;
|
||||
private String victimCity;
|
||||
private String victimLon;
|
||||
private String victimLat;
|
||||
private String originEventId;
|
||||
private String originEventName;
|
||||
private String originEventCategory;
|
||||
private String originEventLevel;
|
||||
private String originAttackChain;
|
||||
private String engineType;
|
||||
private String evilPayload;
|
||||
private String httpRespStatus;
|
||||
private String dnsQuery;
|
||||
private String dnsQueryType;
|
||||
private String dnsTtl;
|
||||
private String dnsAnswer;
|
||||
private String dnsSubdomains;
|
||||
private String fileSha256;
|
||||
private String fileSsdeep;
|
||||
private String victimCountryCode;
|
||||
private String httpXffIp;
|
||||
private String tcMiguanClass;
|
||||
private String pid;
|
||||
private String ppid;
|
||||
private String processName;
|
||||
private String backdoorType;
|
||||
private String tty;
|
||||
private String sudoUser;
|
||||
private String sudoGroup;
|
||||
private String originEventType;
|
||||
private String destDomain;
|
||||
private String shellCmdline;
|
||||
private String parentCmdline;
|
||||
private String attackChain;
|
||||
private String processTree;
|
||||
private String hostFileSha256;
|
||||
private String hostFileMd5;
|
||||
private String hostFileSize;
|
||||
private String hostFileType;
|
||||
private String destCountry;
|
||||
private String destCountryCode;
|
||||
private String logOrigin;
|
||||
private String destRegion;
|
||||
private String srcLat;
|
||||
private String destRegionCode;
|
||||
private String destCity;
|
||||
private String destLon;
|
||||
private String destLat;
|
||||
private Integer eventCategory;
|
||||
private Integer attackResult;
|
||||
private String probeIp;
|
||||
private String deviceIp;
|
||||
private String deviceManufacturer;
|
||||
private String deviceName;
|
||||
private String productName;
|
||||
private String id1;
|
||||
private Long count;
|
||||
private String countReason;
|
||||
private Integer eventType;
|
||||
private String protocol;
|
||||
private String shellCmd;
|
||||
private String parentName;
|
||||
private String hostFilePath;
|
||||
private String uid;
|
||||
private Integer fall;
|
||||
private String tcMiguanServerIp;
|
||||
private Integer devType;
|
||||
private Integer collectMethod;
|
||||
private Integer fieldCateId;
|
||||
private Integer deviceType;
|
||||
private String tcMiguanClientIp;
|
||||
private String tcMiguanName;
|
||||
private Long originTotalPackages;
|
||||
private Long originTotalBytes;
|
||||
private Long originPeakPackagesRate;
|
||||
private Long originPeakBytesRate;
|
||||
private Long originPeakFlowsRate;
|
||||
private String aptOrgname;
|
||||
private String aptOrgmsg;
|
||||
private String mailMessageId;
|
||||
private String mailBcc;
|
||||
private String mailSize;
|
||||
private String mailAttachHashcode;
|
||||
private String mailUrl;
|
||||
private String mailCc;
|
||||
private String algorithm;
|
||||
private String miningpoolIp;
|
||||
private String processMd5;
|
||||
private String pprocessMd5;
|
||||
private String sourceServername;
|
||||
private String originSourceServername;
|
||||
private String mailFilename;
|
||||
private String dstUploadAppname;
|
||||
private Long targetPort;
|
||||
private String gid;
|
||||
private String originUid;
|
||||
private String originGid;
|
||||
private Long targetPorts;
|
||||
private String tcMiguanName1;
|
||||
private String tcMiguanClass1;
|
||||
private Long etlTime;
|
||||
private String tcMiguanScanPort2;
|
||||
private String desipSecurityScope;
|
||||
private String srcipSecurityScope;
|
||||
private Long collectTimeTs;
|
||||
private String tcMiguanScanPort1;
|
||||
private String srcDevName;
|
||||
private String collectProtocol;
|
||||
private String destinationSystemType;
|
||||
private String destinationSystem;
|
||||
private String etlHost;
|
||||
private Integer normalizeRuleId;
|
||||
private String normalizeRuleName;
|
||||
private String syslogUuid;
|
||||
private String syslogTopic;
|
||||
|
||||
}
|
||||
+381
@@ -0,0 +1,381 @@
|
||||
package com.common.entity;
|
||||
|
||||
import lombok.Data;
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
public class SyslogNormalData {
|
||||
private String id;
|
||||
private LocalDateTime createdAt;
|
||||
private LocalDateTime logTime;
|
||||
private Integer deviceId;
|
||||
private String webshellType;
|
||||
private String vuirsType;
|
||||
private String vuirsUrl;
|
||||
private String classFilename;
|
||||
private String classPath;
|
||||
private String parentClass;
|
||||
private String jarPath;
|
||||
private String classMd5;
|
||||
private String classLoader;
|
||||
private String classHashcode;
|
||||
private String classLoaderHashcode;
|
||||
private String tcNameip;
|
||||
private String performSql;
|
||||
private String tcAccount;
|
||||
private String tcAppname;
|
||||
private String processUname;
|
||||
private String pProcessUname;
|
||||
private String containerName;
|
||||
private String containerId;
|
||||
private String httpRespServer;
|
||||
private Long srcipId;
|
||||
private String cdnip;
|
||||
private String natip;
|
||||
private String mailSender;
|
||||
private String mailReceiver;
|
||||
private String vpnMac;
|
||||
private String vpnOs;
|
||||
private String vpnUser;
|
||||
private String vpnGroupname;
|
||||
private String vpnAccessIp;
|
||||
private Boolean destIpApt;
|
||||
private String originAttackResult;
|
||||
private String description;
|
||||
private String solution;
|
||||
private String attackCause;
|
||||
private String username;
|
||||
private String tcFlowId;
|
||||
private String loginResult;
|
||||
private String cmdline;
|
||||
private String originAttackAction;
|
||||
private String victimDomain;
|
||||
private String vpnDeviceid;
|
||||
private String vpnAccessAction;
|
||||
private Long fileAccessTime;
|
||||
private String fileName;
|
||||
private String tcClass;
|
||||
private String tcName2;
|
||||
private Long loginLasttime;
|
||||
private String originPermissions;
|
||||
private String beginPermissions;
|
||||
private Long printTime;
|
||||
private String printer;
|
||||
private String printerType;
|
||||
private Long printPages;
|
||||
private Long printCopies;
|
||||
private String srcDevice;
|
||||
private String dstDevice;
|
||||
private String srcFile;
|
||||
private String srcFileType;
|
||||
private String srcFilePath;
|
||||
private String dstFile;
|
||||
private String dstFileType;
|
||||
private String dstFilePath;
|
||||
private String dlpPolicyName;
|
||||
private String dlpPolicyType;
|
||||
private String dstUploadUrl;
|
||||
private String processUuid;
|
||||
private String pProcessUuid;
|
||||
private String env;
|
||||
private String bruteForceService;
|
||||
private String vuirsName;
|
||||
private Long httpReqLength;
|
||||
private String httpReqContentType;
|
||||
private String tcScanPort;
|
||||
private String tcLabels;
|
||||
private String httpRespContentType;
|
||||
private String dnsMsgType;
|
||||
private String dnsAnswerLength;
|
||||
private Boolean dnsIoc;
|
||||
private BigDecimal txBytes;
|
||||
private BigDecimal rxBytes;
|
||||
private BigDecimal allBytes;
|
||||
private Long durationTime;
|
||||
private String mailAttachName;
|
||||
private String mailSubject;
|
||||
private String mailMessage;
|
||||
private String mailSendServer;
|
||||
private String mailAgent;
|
||||
private String tlsVersion;
|
||||
private String tlsServerCert;
|
||||
private String tlsServerSuite;
|
||||
private String tlsClientSuitesLen;
|
||||
private String tlsJa3;
|
||||
private String tlsJa3s;
|
||||
private String vpnAccessPort;
|
||||
private String logTopic;
|
||||
private Long collectTime;
|
||||
private Boolean srcIsIntranetip;
|
||||
private Boolean srcIpIoc;
|
||||
private Boolean srcIpApt;
|
||||
private String srcipName;
|
||||
private String tcClient;
|
||||
private Long srcipOrganizationId;
|
||||
private Boolean destIpIntranetip;
|
||||
private Boolean destIpIoc;
|
||||
private Long desipId;
|
||||
private String desipName;
|
||||
private String tcHostip;
|
||||
private Long desipOrganizationId;
|
||||
private String originConfidence;
|
||||
private String originMalscore;
|
||||
private String attackerIcampaign;
|
||||
private Long attackerHostAssetId;
|
||||
private Long attackerOrganizationId;
|
||||
private Long victimHostAssetId;
|
||||
private Long victimOrganizationId;
|
||||
private Long logoutTime;
|
||||
private String httpReqLine;
|
||||
private String desipSecurityScopeId;
|
||||
private String srcipSecurityScopeId;
|
||||
private Long httpRespLength;
|
||||
private String tcAttackType;
|
||||
private String tcRealip;
|
||||
private String attackerIpLists;
|
||||
private String loginPassword;
|
||||
private String detail;
|
||||
private String attackerCountryCode;
|
||||
private String attackerRegionCode;
|
||||
private String victimRegionCode;
|
||||
private String payload;
|
||||
private String httpReferer;
|
||||
private String httpUserAgent;
|
||||
private String httpSession;
|
||||
private String httpQueryString;
|
||||
private String filePath;
|
||||
private String filePermission;
|
||||
private String loginAbnormalType;
|
||||
private String fileTag;
|
||||
private String filePlatform;
|
||||
private String targetIp;
|
||||
private String collectDate;
|
||||
private String tcClientIp;
|
||||
private String tcServerIp;
|
||||
private String tcExternalip;
|
||||
private Long httpStatusCode;
|
||||
private String deviceDomian;
|
||||
private String srcIpStr;
|
||||
private String srcPortStr;
|
||||
private String destIpStr;
|
||||
private String destPortStr;
|
||||
private String pcap;
|
||||
private String ioc;
|
||||
private String maliciousFamily;
|
||||
private String vulnCve;
|
||||
private String aliyunType;
|
||||
private String attackerHostAssetName;
|
||||
private String attackerOrganizationName;
|
||||
private String ctId;
|
||||
private String cveList;
|
||||
private String desipOrganizationName;
|
||||
private String destIpGroup;
|
||||
private String fileGid;
|
||||
private String fileOwner;
|
||||
private String fileOwnergroup;
|
||||
private String fileUid;
|
||||
private String httpRespCookie;
|
||||
private String originRuleId;
|
||||
private String originRuleName;
|
||||
private String serviceName;
|
||||
private String srcIpAssetGroup;
|
||||
private String srcipOrganizationName;
|
||||
private String victimHostAssetName;
|
||||
private Long httpRespCodes;
|
||||
private String victimOrganizationName;
|
||||
private String tcType;
|
||||
private String direction;
|
||||
private String httpReqCookie;
|
||||
private String httpReqProtocol;
|
||||
private String httpReqHeaderRaw;
|
||||
private String httpUrl;
|
||||
private String uname;
|
||||
private String originHostname;
|
||||
private String originOs;
|
||||
private String originAgentMac;
|
||||
private String originHostId;
|
||||
private String originAgentVersion;
|
||||
private String originAgentId;
|
||||
private String originAgentName;
|
||||
private String originWorkGroup;
|
||||
private String originAssetGroup;
|
||||
private Long originLocalPort;
|
||||
private String originAgentIp;
|
||||
private String originInternalIp;
|
||||
private String originExternalIp;
|
||||
private String originLocalAddr;
|
||||
private Long agentId;
|
||||
private String agentName;
|
||||
private String tcTitle;
|
||||
private String logId;
|
||||
private LocalDateTime eventDate;
|
||||
private Long eventTimeTs;
|
||||
private Integer eventLevel;
|
||||
private String srcIp;
|
||||
private Long srcPort;
|
||||
private String destIp;
|
||||
private Long destPort;
|
||||
private Long eventTime;
|
||||
private String attackerCountry;
|
||||
private String srcMac;
|
||||
private String destMac;
|
||||
private String proto;
|
||||
private Long devId;
|
||||
private Long createdTime;
|
||||
private String srcCountry;
|
||||
private String srcCountryCode;
|
||||
private String srcRegion;
|
||||
private String srcRegionCode;
|
||||
private String srcCity;
|
||||
private String srcLon;
|
||||
private String httpMethod;
|
||||
private String httpHost;
|
||||
private String httpReqHeader;
|
||||
private String httpReqBody;
|
||||
private String httpRespHeader;
|
||||
private String httpRespBody;
|
||||
private String fileType;
|
||||
private String fileMd5;
|
||||
private String fileSize;
|
||||
private String process;
|
||||
private Long startTime;
|
||||
private String action;
|
||||
private String attackerRegion;
|
||||
private Long endTime;
|
||||
private Long fileCreatedTime;
|
||||
private Long fileModifiedTime;
|
||||
private String tcMiguanScanPort;
|
||||
private String processPath;
|
||||
private String parentProcessPath;
|
||||
private String gname;
|
||||
private String exeName;
|
||||
private String exePath;
|
||||
private Long loginTime;
|
||||
private Long loginTimes;
|
||||
private String checkItem;
|
||||
private String checkType;
|
||||
private String attackerIp;
|
||||
private Long attackerPort;
|
||||
private String victimIp;
|
||||
private Long victimPort;
|
||||
private String attackerCity;
|
||||
private String attackerLon;
|
||||
private String attackerLat;
|
||||
private String victimCountry;
|
||||
private String victimRegion;
|
||||
private String victimCity;
|
||||
private String victimLon;
|
||||
private String victimLat;
|
||||
private String originEventId;
|
||||
private String originEventName;
|
||||
private String originEventCategory;
|
||||
private String originEventLevel;
|
||||
private String originAttackChain;
|
||||
private String engineType;
|
||||
private String evilPayload;
|
||||
private String httpRespStatus;
|
||||
private String dnsQuery;
|
||||
private String dnsQueryType;
|
||||
private String dnsTtl;
|
||||
private String dnsAnswer;
|
||||
private String dnsSubdomains;
|
||||
private String fileSha256;
|
||||
private String fileSsdeep;
|
||||
private String victimCountryCode;
|
||||
private String httpXffIp;
|
||||
private String tcMiguanClass;
|
||||
private String pid;
|
||||
private String ppid;
|
||||
private String processName;
|
||||
private String backdoorType;
|
||||
private String tty;
|
||||
private String sudoUser;
|
||||
private String sudoGroup;
|
||||
private String originEventType;
|
||||
private String destDomain;
|
||||
private String shellCmdline;
|
||||
private String parentCmdline;
|
||||
private String attackChain;
|
||||
private String processTree;
|
||||
private String hostFileSha256;
|
||||
private String hostFileMd5;
|
||||
private String hostFileSize;
|
||||
private String hostFileType;
|
||||
private String destCountry;
|
||||
private String destCountryCode;
|
||||
private String logOrigin;
|
||||
private String destRegion;
|
||||
private String srcLat;
|
||||
private String destRegionCode;
|
||||
private String destCity;
|
||||
private String destLon;
|
||||
private String destLat;
|
||||
private Integer eventCategory;
|
||||
private Integer attackResult;
|
||||
private String probeIp;
|
||||
private String deviceIp;
|
||||
private String deviceManufacturer;
|
||||
private String deviceName;
|
||||
private String productName;
|
||||
private String id1;
|
||||
private Long count;
|
||||
private String countReason;
|
||||
private Integer eventType;
|
||||
private String protocol;
|
||||
private String shellCmd;
|
||||
private String parentName;
|
||||
private String hostFilePath;
|
||||
private String uid;
|
||||
private Integer fall;
|
||||
private String tcMiguanServerIp;
|
||||
private Integer devType;
|
||||
private Integer collectMethod;
|
||||
private Integer fieldCateId;
|
||||
private Integer deviceType;
|
||||
private String tcMiguanClientIp;
|
||||
private String tcMiguanName;
|
||||
private Long originTotalPackages;
|
||||
private Long originTotalBytes;
|
||||
private Long originPeakPackagesRate;
|
||||
private Long originPeakBytesRate;
|
||||
private Long originPeakFlowsRate;
|
||||
private String aptOrgname;
|
||||
private String aptOrgmsg;
|
||||
private String mailMessageId;
|
||||
private String mailBcc;
|
||||
private String mailSize;
|
||||
private String mailAttachHashcode;
|
||||
private String mailUrl;
|
||||
private String mailCc;
|
||||
private String algorithm;
|
||||
private String miningpoolIp;
|
||||
private String processMd5;
|
||||
private String pprocessMd5;
|
||||
private String sourceServername;
|
||||
private String originSourceServername;
|
||||
private String mailFilename;
|
||||
private String dstUploadAppname;
|
||||
private Long targetPort;
|
||||
private String gid;
|
||||
private String originUid;
|
||||
private String originGid;
|
||||
private Long targetPorts;
|
||||
private String tcMiguanName1;
|
||||
private String tcMiguanClass1;
|
||||
private Long etlTime;
|
||||
private String tcMiguanScanPort2;
|
||||
private String desipSecurityScope;
|
||||
private String srcipSecurityScope;
|
||||
private Long collectTimeTs;
|
||||
private String tcMiguanScanPort1;
|
||||
private String srcDevName;
|
||||
private String collectProtocol;
|
||||
private String destinationSystemType;
|
||||
private String destinationSystem;
|
||||
private String etlHost;
|
||||
private Integer normalizeRuleId;
|
||||
private String normalizeRuleName;
|
||||
private String syslogUuid;
|
||||
private String syslogTopic;
|
||||
}
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
package com.common.entity;
|
||||
|
||||
import javax.validation.constraints.NotBlank;
|
||||
import javax.validation.constraints.NotNull;
|
||||
|
||||
public class SyslogRequest {
|
||||
|
||||
@NotBlank(message = "IP地址不能为空")
|
||||
private String ip;
|
||||
|
||||
@NotNull(message = "端口号不能为空")
|
||||
private Integer port;
|
||||
|
||||
@NotBlank(message = "日志内容不能为空")
|
||||
private String logContent;
|
||||
|
||||
private String protocol = "UDP"; // 默认UDP协议
|
||||
private String facility = "USER"; // 设施
|
||||
private String severity = "INFO"; // 严重级别
|
||||
|
||||
// 构造函数
|
||||
public SyslogRequest() {}
|
||||
|
||||
public SyslogRequest(String ip, Integer port, String logContent) {
|
||||
this.ip = ip;
|
||||
this.port = port;
|
||||
this.logContent = logContent;
|
||||
}
|
||||
|
||||
// Getter和Setter方法
|
||||
public String getIp() {
|
||||
return ip;
|
||||
}
|
||||
|
||||
public void setIp(String ip) {
|
||||
this.ip = ip;
|
||||
}
|
||||
|
||||
public Integer getPort() {
|
||||
return port;
|
||||
}
|
||||
|
||||
public void setPort(Integer port) {
|
||||
this.port = port;
|
||||
}
|
||||
|
||||
public String getLogContent() {
|
||||
return logContent;
|
||||
}
|
||||
|
||||
public void setLogContent(String logContent) {
|
||||
this.logContent = logContent;
|
||||
}
|
||||
|
||||
public String getProtocol() {
|
||||
return protocol;
|
||||
}
|
||||
|
||||
public void setProtocol(String protocol) {
|
||||
this.protocol = protocol;
|
||||
}
|
||||
|
||||
public String getFacility() {
|
||||
return facility;
|
||||
}
|
||||
|
||||
public void setFacility(String facility) {
|
||||
this.facility = facility;
|
||||
}
|
||||
|
||||
public String getSeverity() {
|
||||
return severity;
|
||||
}
|
||||
|
||||
public void setSeverity(String severity) {
|
||||
this.severity = severity;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "SyslogRequest{" +
|
||||
"ip='" + ip + '\'' +
|
||||
", port=" + port +
|
||||
", logContent='" + logContent + '\'' +
|
||||
", protocol='" + protocol + '\'' +
|
||||
", facility='" + facility + '\'' +
|
||||
", severity='" + severity + '\'' +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
+260
@@ -0,0 +1,260 @@
|
||||
package com.common.entity;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* XDR Honeypot 实体类
|
||||
* 对应数据库表 xdr_honeypot
|
||||
*/
|
||||
public class XdrHoneypot {
|
||||
private Long id;
|
||||
private String vcsource;
|
||||
private String dstartTime;
|
||||
private String dtime;
|
||||
private String riskLevel;
|
||||
private String vcconnection;
|
||||
private String fileInfo;
|
||||
private String extra;
|
||||
private String vctype;
|
||||
private String agentSn;
|
||||
private String agentName;
|
||||
private String honeypotId;
|
||||
private String honeypotName;
|
||||
private String srcIp;
|
||||
private String srcPort;
|
||||
private String srcMac;
|
||||
private String destIp;
|
||||
private String destPort;
|
||||
private String proxyIp;
|
||||
private String node;
|
||||
private LocalDateTime createTime;
|
||||
|
||||
// 默认构造函数
|
||||
public XdrHoneypot() {
|
||||
this.createTime = LocalDateTime.now();
|
||||
}
|
||||
|
||||
// 带参构造函数
|
||||
public XdrHoneypot(String vcsource, String dstartTime, String dtime, String riskLevel,
|
||||
String vcconnection, String fileInfo, String extra, String vctype,
|
||||
String agentSn, String agentName, String honeypotId, String honeypotName,
|
||||
String srcIp, String srcPort, String srcMac, String destIp,
|
||||
String destPort, String proxyIp, String node) {
|
||||
this();
|
||||
this.vcsource = vcsource;
|
||||
this.dstartTime = dstartTime;
|
||||
this.dtime = dtime;
|
||||
this.riskLevel = riskLevel;
|
||||
this.vcconnection = vcconnection;
|
||||
this.fileInfo = fileInfo;
|
||||
this.extra = extra;
|
||||
this.vctype = vctype;
|
||||
this.agentSn = agentSn;
|
||||
this.agentName = agentName;
|
||||
this.honeypotId = honeypotId;
|
||||
this.honeypotName = honeypotName;
|
||||
this.srcIp = srcIp;
|
||||
this.srcPort = srcPort;
|
||||
this.srcMac = srcMac;
|
||||
this.destIp = destIp;
|
||||
this.destPort = destPort;
|
||||
this.proxyIp = proxyIp;
|
||||
this.node = node;
|
||||
}
|
||||
|
||||
// Getter 和 Setter 方法
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getVcsource() {
|
||||
return vcsource;
|
||||
}
|
||||
|
||||
public void setVcsource(String vcsource) {
|
||||
this.vcsource = vcsource;
|
||||
}
|
||||
|
||||
public String getDstartTime() {
|
||||
return dstartTime;
|
||||
}
|
||||
|
||||
public void setDstartTime(String dstartTime) {
|
||||
this.dstartTime = dstartTime;
|
||||
}
|
||||
|
||||
public String getDtime() {
|
||||
return dtime;
|
||||
}
|
||||
|
||||
public void setDtime(String dtime) {
|
||||
this.dtime = dtime;
|
||||
}
|
||||
|
||||
public String getRiskLevel() {
|
||||
return riskLevel;
|
||||
}
|
||||
|
||||
public void setRiskLevel(String riskLevel) {
|
||||
this.riskLevel = riskLevel;
|
||||
}
|
||||
|
||||
public String getVcconnection() {
|
||||
return vcconnection;
|
||||
}
|
||||
|
||||
public void setVcconnection(String vcconnection) {
|
||||
this.vcconnection = vcconnection;
|
||||
}
|
||||
|
||||
public String getFileInfo() {
|
||||
return fileInfo;
|
||||
}
|
||||
|
||||
public void setFileInfo(String fileInfo) {
|
||||
this.fileInfo = fileInfo;
|
||||
}
|
||||
|
||||
public String getExtra() {
|
||||
return extra;
|
||||
}
|
||||
|
||||
public void setExtra(String extra) {
|
||||
this.extra = extra;
|
||||
}
|
||||
|
||||
public String getVctype() {
|
||||
return vctype;
|
||||
}
|
||||
|
||||
public void setVctype(String vctype) {
|
||||
this.vctype = vctype;
|
||||
}
|
||||
|
||||
public String getAgentSn() {
|
||||
return agentSn;
|
||||
}
|
||||
|
||||
public void setAgentSn(String agentSn) {
|
||||
this.agentSn = agentSn;
|
||||
}
|
||||
|
||||
public String getAgentName() {
|
||||
return agentName;
|
||||
}
|
||||
|
||||
public void setAgentName(String agentName) {
|
||||
this.agentName = agentName;
|
||||
}
|
||||
|
||||
public String getHoneypotId() {
|
||||
return honeypotId;
|
||||
}
|
||||
|
||||
public void setHoneypotId(String honeypotId) {
|
||||
this.honeypotId = honeypotId;
|
||||
}
|
||||
|
||||
public String getHoneypotName() {
|
||||
return honeypotName;
|
||||
}
|
||||
|
||||
public void setHoneypotName(String honeypotName) {
|
||||
this.honeypotName = honeypotName;
|
||||
}
|
||||
|
||||
public String getSrcIp() {
|
||||
return srcIp;
|
||||
}
|
||||
|
||||
public void setSrcIp(String srcIp) {
|
||||
this.srcIp = srcIp;
|
||||
}
|
||||
|
||||
public String getSrcPort() {
|
||||
return srcPort;
|
||||
}
|
||||
|
||||
public void setSrcPort(String srcPort) {
|
||||
this.srcPort = srcPort;
|
||||
}
|
||||
|
||||
public String getSrcMac() {
|
||||
return srcMac;
|
||||
}
|
||||
|
||||
public void setSrcMac(String srcMac) {
|
||||
this.srcMac = srcMac;
|
||||
}
|
||||
|
||||
public String getDestIp() {
|
||||
return destIp;
|
||||
}
|
||||
|
||||
public void setDestIp(String destIp) {
|
||||
this.destIp = destIp;
|
||||
}
|
||||
|
||||
public String getDestPort() {
|
||||
return destPort;
|
||||
}
|
||||
|
||||
public void setDestPort(String destPort) {
|
||||
this.destPort = destPort;
|
||||
}
|
||||
|
||||
public String getProxyIp() {
|
||||
return proxyIp;
|
||||
}
|
||||
|
||||
public void setProxyIp(String proxyIp) {
|
||||
this.proxyIp = proxyIp;
|
||||
}
|
||||
|
||||
public String getNode() {
|
||||
return node;
|
||||
}
|
||||
|
||||
public void setNode(String node) {
|
||||
this.node = node;
|
||||
}
|
||||
|
||||
public LocalDateTime getCreateTime() {
|
||||
return createTime;
|
||||
}
|
||||
|
||||
public void setCreateTime(LocalDateTime createTime) {
|
||||
this.createTime = createTime;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "XdrHoneypot{" +
|
||||
"id=" + id +
|
||||
", vcsource='" + vcsource + '\'' +
|
||||
", dstartTime='" + dstartTime + '\'' +
|
||||
", dtime='" + dtime + '\'' +
|
||||
", riskLevel='" + riskLevel + '\'' +
|
||||
", vcconnection='" + vcconnection + '\'' +
|
||||
", fileInfo='" + fileInfo + '\'' +
|
||||
", extra='" + extra + '\'' +
|
||||
", vctype='" + vctype + '\'' +
|
||||
", agentSn='" + agentSn + '\'' +
|
||||
", agentName='" + agentName + '\'' +
|
||||
", honeypotId='" + honeypotId + '\'' +
|
||||
", honeypotName='" + honeypotName + '\'' +
|
||||
", srcIp='" + srcIp + '\'' +
|
||||
", srcPort='" + srcPort + '\'' +
|
||||
", srcMac='" + srcMac + '\'' +
|
||||
", destIp='" + destIp + '\'' +
|
||||
", destPort='" + destPort + '\'' +
|
||||
", proxyIp='" + proxyIp + '\'' +
|
||||
", node='" + node + '\'' +
|
||||
", createTime=" + createTime +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package com.common.mapper;
|
||||
|
||||
import com.common.entity.Alarm;
|
||||
import org.apache.ibatis.annotations.*;
|
||||
import java.util.List;
|
||||
|
||||
|
||||
@Mapper
|
||||
public interface AlarmMapper {
|
||||
|
||||
/**
|
||||
* 批量插入告警数据
|
||||
*/
|
||||
@Insert({"<script>",
|
||||
"INSERT INTO alarm (",
|
||||
"id, created_at, alarm_name, alarm_level, alarm_type, ",
|
||||
"alarm_major_type, alarm_minor_type,alarm_area_id, attack_ip, victim_ip, ",
|
||||
"device_id, comment,origin_log_ids,log_start_at, log_end_at, http_status, ",
|
||||
"attack_port, victim_port, attack_method, etl_time, log_count, ",
|
||||
"attack_chain_phase, disposition_advice, attack_direction, ",
|
||||
"judged_state, disposed_state, attack_result, fall, payload, " ,
|
||||
"http_req_header , http_req_body,http_resp_header , http_resp_body ",
|
||||
") VALUES ",
|
||||
"<foreach collection='list' item='item' separator=','>",
|
||||
"( #{item.id}, #{item.createdAt}, #{item.alarmName}, #{item.alarmLevel}, ",
|
||||
"#{item.alarmType}, #{item.alarmMajorType}, #{item.alarmMinorType}, #{item.alarmAreaId}, ",
|
||||
"#{item.attackIp, typeHandler=com.Modules.etl.handler.ArrayStringTypeHandler}, ",
|
||||
"#{item.victimIp, typeHandler=com.Modules.etl.handler.ArrayStringTypeHandler}, ",
|
||||
"#{item.deviceId, typeHandler=com.Modules.etl.handler.ArrayIntegerTypeHandler}, ",
|
||||
"#{item.comment}, " ,
|
||||
"#{item.originLogIds, typeHandler=com.Modules.etl.handler.ArrayStringTypeHandler}, ",
|
||||
"#{item.logStartAt}, #{item.logEndAt}, #{item.httpStatus}, ",
|
||||
"#{item.attackPort, typeHandler=com.Modules.etl.handler.ArrayIntegerTypeHandler}, ",
|
||||
"#{item.victimPort, typeHandler=com.Modules.etl.handler.ArrayIntegerTypeHandler}, ",
|
||||
"#{item.attackMethod}, #{item.etlTime}, #{item.logCount}, ",
|
||||
"#{item.attackChainPhase, typeHandler=com.Modules.etl.handler.ArrayIntegerTypeHandler}, ",
|
||||
"#{item.dispositionAdvice}, #{item.attackDirection}, ",
|
||||
"#{item.judgedState}, #{item.disposedState}, #{item.attackResult}, #{item.fall}, ",
|
||||
"#{item.payload}, ",
|
||||
"#{item.httpReqHeaders, typeHandler=com.Modules.etl.handler.ArrayStringTypeHandler}, ",
|
||||
"#{item.httpReqBodys, typeHandler=com.Modules.etl.handler.ArrayStringTypeHandler}, ",
|
||||
"#{item.httpRespHeaders, typeHandler=com.Modules.etl.handler.ArrayStringTypeHandler}, ",
|
||||
"#{item.httpRespBodys, typeHandler=com.Modules.etl.handler.ArrayStringTypeHandler})",
|
||||
"</foreach>",
|
||||
"</script>"})
|
||||
void batchInsert(@Param("list") List<Alarm> alarmList);
|
||||
|
||||
/**
|
||||
* 单条插入告警数据
|
||||
*/
|
||||
@Insert("INSERT INTO alarm (" +
|
||||
"id, created_at, alarm_name, alarm_level, alarm_type, " +
|
||||
"alarm_major_type, alarm_minor_type,alarm_area_id, attack_ip, victim_ip, " +
|
||||
"device_id, comment,origin_log_ids, log_start_at, log_end_at, http_status, " +
|
||||
"attack_port, victim_port, attack_method, etl_time, log_count, " +
|
||||
"attack_chain_phase, disposition_advice, attack_direction, " +
|
||||
"judged_state, disposed_state, attack_result, fall, payload, " +
|
||||
"http_req_header , http_req_body,http_resp_header , http_resp_body " +
|
||||
") VALUES (" +
|
||||
"#{id}, #{createdAt}, #{alarmName}, #{alarmLevel}, " +
|
||||
"#{alarmType}, #{alarmMajorType}, #{alarmMinorType}, #{alarmAreaId}, " +
|
||||
"#{attackIp, typeHandler=com.Modules.etl.handler.ArrayStringTypeHandler}, " +
|
||||
"#{victimIp, typeHandler=com.Modules.etl.handler.ArrayStringTypeHandler}, " +
|
||||
"#{deviceId, typeHandler=com.Modules.etl.handler.ArrayIntegerTypeHandler}, " +
|
||||
"#{comment}, " +
|
||||
"#{originLogIds, typeHandler=com.Modules.etl.handler.ArrayStringTypeHandler}, " +
|
||||
"#{logStartAt}, #{logEndAt}, #{httpStatus}, " +
|
||||
"#{attackPort, typeHandler=com.Modules.etl.handler.ArrayIntegerTypeHandler}, " +
|
||||
"#{victimPort, typeHandler=com.Modules.etl.handler.ArrayIntegerTypeHandler}, " +
|
||||
"#{attackMethod}, #{etlTime}, #{logCount}, " +
|
||||
"#{attackChainPhase, typeHandler=com.Modules.etl.handler.ArrayIntegerTypeHandler}, " +
|
||||
"#{dispositionAdvice}, #{attackDirection}, " +
|
||||
"#{judgedState}, #{disposedState}, #{attackResult}, #{fall}, #{payload}, " +
|
||||
"#{httpReqHeaders, typeHandler=com.Modules.etl.handler.ArrayStringTypeHandler}, " +
|
||||
"#{httpReqBodys, typeHandler=com.Modules.etl.handler.ArrayStringTypeHandler}, " +
|
||||
"#{httpRespHeaders, typeHandler=com.Modules.etl.handler.ArrayStringTypeHandler}, " +
|
||||
"#{httpRespBodys, typeHandler=com.Modules.etl.handler.ArrayStringTypeHandler} " +
|
||||
")")
|
||||
void insert(Alarm alarm);
|
||||
}
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
package com.common.mapper;
|
||||
|
||||
import com.common.entity.Alarm;
|
||||
import com.common.entity.AlarmVisit;
|
||||
import org.apache.ibatis.annotations.Insert;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
|
||||
@Mapper
|
||||
public interface AlarmVisitMapper {
|
||||
|
||||
/**
|
||||
* 批量插入告警数据
|
||||
*/
|
||||
@Insert({"<script>",
|
||||
"INSERT INTO alarm_visit (",
|
||||
"id, created_at, alarm_name, alarm_level, alarm_type, ",
|
||||
"alarm_major_type, alarm_minor_type,alarm_area_id, attack_ip, victim_ip, ",
|
||||
"device_id, comment,origin_log_ids,log_start_at, log_end_at, http_status, ",
|
||||
"attack_port, victim_port, attack_method, etl_time, log_count, ",
|
||||
"attack_chain_phase, disposition_advice, attack_direction, ",
|
||||
"judged_state, disposed_state, attack_result, fall, payload, " ,
|
||||
"http_req_header , http_req_body,http_resp_header , http_resp_body ",
|
||||
") VALUES ",
|
||||
"<foreach collection='list' item='item' separator=','>",
|
||||
"(#{item.id}, #{item.createdAt}, #{item.alarmName}, #{item.alarmLevel}, ",
|
||||
"#{item.alarmType}, #{item.alarmMajorType}, #{item.alarmMinorType}, #{item.alarmAreaId}, ",
|
||||
"#{item.attackIp, typeHandler=com.Modules.etl.handler.ArrayStringTypeHandler}, ",
|
||||
"#{item.victimIp, typeHandler=com.Modules.etl.handler.ArrayStringTypeHandler}, ",
|
||||
"#{item.deviceId, typeHandler=com.Modules.etl.handler.ArrayIntegerTypeHandler}, ",
|
||||
"#{item.comment}, " ,
|
||||
"#{item.originLogIds, typeHandler=com.Modules.etl.handler.ArrayStringTypeHandler}, ",
|
||||
"#{item.logStartAt}, #{item.logEndAt}, #{item.httpStatus}, ",
|
||||
"#{item.attackPort, typeHandler=com.Modules.etl.handler.ArrayIntegerTypeHandler}, ",
|
||||
"#{item.victimPort, typeHandler=com.Modules.etl.handler.ArrayIntegerTypeHandler}, ",
|
||||
"#{item.attackMethod}, #{item.etlTime}, #{item.logCount}, ",
|
||||
"#{item.attackChainPhase, typeHandler=com.Modules.etl.handler.ArrayIntegerTypeHandler}, ",
|
||||
"#{item.dispositionAdvice}, #{item.attackDirection}, ",
|
||||
"#{item.judgedState}, #{item.disposedState}, #{item.attackResult}, #{item.fall}, ",
|
||||
"#{item.payload}, ",
|
||||
"#{item.httpReqHeaders, typeHandler=com.Modules.etl.handler.ArrayStringTypeHandler}, ",
|
||||
"#{item.httpReqBodys, typeHandler=com.Modules.etl.handler.ArrayStringTypeHandler}, ",
|
||||
"#{item.httpRespHeaders, typeHandler=com.Modules.etl.handler.ArrayStringTypeHandler}, ",
|
||||
"#{item.httpRespBodys, typeHandler=com.Modules.etl.handler.ArrayStringTypeHandler}) ",
|
||||
"</foreach>",
|
||||
"</script>"})
|
||||
void batchInsert(@Param("list") List<AlarmVisit> alarmList);
|
||||
|
||||
/**
|
||||
* 单条插入告警数据
|
||||
*/
|
||||
@Insert("INSERT INTO alarm_visit (" +
|
||||
"id, created_at, alarm_name, alarm_level, alarm_type, " +
|
||||
"alarm_major_type, alarm_minor_type,alarm_area_id, attack_ip, victim_ip, " +
|
||||
"device_id, comment,origin_log_ids, log_start_at, log_end_at, http_status, " +
|
||||
"attack_port, victim_port, attack_method, etl_time, log_count, " +
|
||||
"attack_chain_phase, disposition_advice, attack_direction, " +
|
||||
"judged_state, disposed_state, attack_result, fall, payload, " +
|
||||
"http_req_header , http_req_body,http_resp_header , http_resp_body " +
|
||||
") VALUES (" +
|
||||
"#{id}, #{createdAt}, #{alarmName}, #{alarmLevel}, " +
|
||||
"#{alarmType}, #{alarmMajorType}, #{alarmMinorType}, #{alarmAreaId}, " +
|
||||
"#{attackIp, typeHandler=com.Modules.etl.handler.ArrayStringTypeHandler}, " +
|
||||
"#{victimIp, typeHandler=com.Modules.etl.handler.ArrayStringTypeHandler}, " +
|
||||
"#{deviceId, typeHandler=com.Modules.etl.handler.ArrayIntegerTypeHandler}, " +
|
||||
"#{comment}, " +
|
||||
"#{originLogIds, typeHandler=com.Modules.etl.handler.ArrayStringTypeHandler}, " +
|
||||
"#{logStartAt}, #{logEndAt}, #{httpStatus}, " +
|
||||
"#{attackPort, typeHandler=com.Modules.etl.handler.ArrayIntegerTypeHandler}, " +
|
||||
"#{victimPort, typeHandler=com.Modules.etl.handler.ArrayIntegerTypeHandler}, " +
|
||||
"#{attackMethod}, #{etlTime}, #{logCount}, " +
|
||||
"#{attackChainPhase, typeHandler=com.Modules.etl.handler.ArrayIntegerTypeHandler}, " +
|
||||
"#{dispositionAdvice}, #{attackDirection}, " +
|
||||
"#{judgedState}, #{disposedState}, #{attackResult}, #{fall}, #{payload}, " +
|
||||
"#{httpReqHeaders, typeHandler=com.Modules.etl.handler.ArrayStringTypeHandler}, " +
|
||||
"#{httpReqBodys, typeHandler=com.Modules.etl.handler.ArrayStringTypeHandler}, " +
|
||||
"#{httpRespHeaders, typeHandler=com.Modules.etl.handler.ArrayStringTypeHandler}, " +
|
||||
"#{httpRespBodys, typeHandler=com.Modules.etl.handler.ArrayStringTypeHandler} " +
|
||||
")")
|
||||
void insert(AlarmVisit alarm);
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
package com.common.mapper;
|
||||
|
||||
|
||||
import com.common.entity.AppLogEntity;
|
||||
import org.apache.ibatis.annotations.*;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
@Mapper
|
||||
public interface AppLogMapper {
|
||||
|
||||
/**
|
||||
* 插入日志
|
||||
*/
|
||||
@Insert("INSERT INTO applog (es_index, es_type, es_id, es_score, dt_time, collect_time, log_type, " +
|
||||
"trace_id, method, app_name, ip, class_name, env, content, thread_name, log_level, seq, " +
|
||||
"indexed_at, log_date, created_at, updated_at) " +
|
||||
"VALUES (#{esIndex}, #{esType}, #{esId}, #{esScore}, #{dtTime}, #{collectTime}, #{logType}, " +
|
||||
"#{traceId}, #{method}, #{appName}, #{ip}, #{className}, #{env}, #{content}, #{threadName}, " +
|
||||
"#{logLevel}, #{seq}, #{indexedAt}, #{logDate}, #{createdAt}, #{updatedAt})")
|
||||
@Options(useGeneratedKeys = true, keyProperty = "id")
|
||||
int insert(AppLogEntity appLog);
|
||||
|
||||
/**
|
||||
* 批量插入
|
||||
*/
|
||||
int batchInsert(@Param("list") List<AppLogEntity> appLogs);
|
||||
|
||||
/**
|
||||
* 根据ES ID检查是否存在
|
||||
*/
|
||||
@Select("SELECT COUNT(1) FROM applog WHERE es_id = #{esId}")
|
||||
boolean existsByEsId(String esId);
|
||||
|
||||
/**
|
||||
* 根据ES ID和索引检查是否存在
|
||||
*/
|
||||
@Select("SELECT COUNT(1) FROM applog WHERE es_id = #{esId} AND es_index = #{esIndex}")
|
||||
boolean existsByEsIdAndIndex(@Param("esId") String esId, @Param("esIndex") String esIndex);
|
||||
}
|
||||
+192
@@ -0,0 +1,192 @@
|
||||
package com.common.mapper;
|
||||
|
||||
import com.common.entity.DeviceCollectTask;
|
||||
import org.apache.ibatis.annotations.*;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import org.apache.ibatis.annotations.Update;
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
@Mapper
|
||||
public interface DeviceCollectTaskMapper extends BaseMapper<DeviceCollectTask>{
|
||||
|
||||
/**
|
||||
* 根据ID查询采集任务
|
||||
*/
|
||||
@Select("SELECT * FROM device_collect_task WHERE id = #{id}")
|
||||
DeviceCollectTask selectById(Integer id);
|
||||
|
||||
/**
|
||||
* 查询所有采集任务
|
||||
*/
|
||||
@Select("SELECT * FROM device_collect_task")
|
||||
List<DeviceCollectTask> selectAll();
|
||||
|
||||
/**
|
||||
* 根据设备ID查询采集任务
|
||||
*/
|
||||
@Select("SELECT * FROM device_collect_task WHERE device_id = #{deviceId}")
|
||||
List<DeviceCollectTask> selectByDeviceId(Integer deviceId);
|
||||
|
||||
/**
|
||||
* 根据方法类型查询采集任务
|
||||
*/
|
||||
@Select("SELECT * FROM device_collect_task WHERE method = #{method}")
|
||||
List<DeviceCollectTask> selectByMethod(Integer method);
|
||||
|
||||
/**
|
||||
* 根据任务名称模糊查询
|
||||
*/
|
||||
@Select("SELECT * FROM device_collect_task WHERE task_name LIKE CONCAT('%', #{taskName}, '%')")
|
||||
List<DeviceCollectTask> selectByTaskNameLike(String taskName);
|
||||
|
||||
/**
|
||||
* 查询成功的采集任务
|
||||
*/
|
||||
@Select("SELECT * FROM device_collect_task WHERE last_success_time IS NOT NULL")
|
||||
List<DeviceCollectTask> selectSuccessTasks();
|
||||
|
||||
/**
|
||||
* 查询失败的采集任务
|
||||
*/
|
||||
@Select("SELECT * FROM device_collect_task WHERE last_failed_time IS NOT NULL")
|
||||
List<DeviceCollectTask> selectFailedTasks();
|
||||
|
||||
/**
|
||||
* 多条件组合查询
|
||||
*/
|
||||
List<DeviceCollectTask> selectByCondition(DeviceCollectTask condition);
|
||||
|
||||
/**
|
||||
* 插入采集任务
|
||||
*/
|
||||
@Insert("INSERT INTO device_collect_task (created_at, updated_at, device_id, method, task_name, " +
|
||||
"first_time, last_success_time, last_failed_time, detail_id, epm, epm_peak, " +
|
||||
"process_architecture, task_count, recent_discover_time, epm_upper_limit) " +
|
||||
"VALUES (NOW(), NOW(), #{deviceId}, #{method}, #{taskName}, #{firstTime}, " +
|
||||
"#{lastSuccessTime}, #{lastFailedTime}, #{detailId}, #{epm}, #{epmPeak}, " +
|
||||
"#{processArchitecture}, #{taskCount}, #{recentDiscoverTime}, #{epmUpperLimit})")
|
||||
@Options(useGeneratedKeys = true, keyProperty = "id")
|
||||
int insert(DeviceCollectTask task);
|
||||
|
||||
/**
|
||||
* 更新采集任务
|
||||
*/
|
||||
@Update("UPDATE device_collect_task SET " +
|
||||
"updated_at = NOW(), " +
|
||||
"device_id = #{deviceId}, " +
|
||||
"method = #{method}, " +
|
||||
"task_name = #{taskName}, " +
|
||||
"first_time = #{firstTime}, " +
|
||||
"last_success_time = #{lastSuccessTime}, " +
|
||||
"last_failed_time = #{lastFailedTime}, " +
|
||||
"detail_id = #{detailId}, " +
|
||||
"epm = #{epm}, " +
|
||||
"epm_peak = #{epmPeak}, " +
|
||||
"process_architecture = #{processArchitecture}, " +
|
||||
"task_count = #{taskCount}, " +
|
||||
"recent_discover_time = #{recentDiscoverTime}, " +
|
||||
"epm_upper_limit = #{epmUpperLimit} " +
|
||||
"WHERE id = #{id}")
|
||||
int update(DeviceCollectTask task);
|
||||
|
||||
/**
|
||||
* 删除采集任务
|
||||
*/
|
||||
@Delete("DELETE FROM device_collect_task WHERE id = #{id}")
|
||||
int deleteById(Integer id);
|
||||
|
||||
/**
|
||||
* 根据设备ID删除采集任务
|
||||
*/
|
||||
@Delete("DELETE FROM device_collect_task WHERE device_id = #{deviceId}")
|
||||
int deleteByDeviceId(Integer deviceId);
|
||||
|
||||
/**
|
||||
* 更新任务成功状态
|
||||
*/
|
||||
@Update("UPDATE device_collect_task SET " +
|
||||
"last_success_time = NOW(), " +
|
||||
"updated_at = NOW(), " +
|
||||
"task_count = COALESCE(task_count, 0) + 1 " +
|
||||
"WHERE id = #{id}")
|
||||
int updateSuccessStatus(Integer id);
|
||||
|
||||
/**
|
||||
* 更新任务失败状态
|
||||
*/
|
||||
@Update("UPDATE device_collect_task SET " +
|
||||
"last_failed_time = NOW(), " +
|
||||
"updated_at = NOW() " +
|
||||
"WHERE id = #{id}")
|
||||
int updateFailedStatus(Integer id);
|
||||
|
||||
/**
|
||||
* 更新EPM指标
|
||||
*/
|
||||
@Update("UPDATE device_collect_task SET " +
|
||||
"epm = #{epm}, " +
|
||||
"epm_peak = GREATEST(COALESCE(epm_peak, 0), #{epm}), " +
|
||||
"updated_at = NOW() " +
|
||||
"WHERE id = #{id}")
|
||||
int updateEpm(@Param("id") Integer id, @Param("epm") Integer epm);
|
||||
|
||||
/**
|
||||
* 统计设备采集任务数量
|
||||
*/
|
||||
@Select("SELECT COUNT(*) FROM device_collect_task WHERE device_id = #{deviceId}")
|
||||
int countByDeviceId(Integer deviceId);
|
||||
|
||||
/**
|
||||
* 获取设备的最新采集任务
|
||||
*/
|
||||
@Select("SELECT * FROM device_collect_task WHERE device_id = #{deviceId} ORDER BY updated_at DESC LIMIT 1")
|
||||
DeviceCollectTask selectLatestByDeviceId(Integer deviceId);
|
||||
|
||||
|
||||
/**
|
||||
* 批量更新设备采集任务的时间
|
||||
*/
|
||||
@Update("<script>" +
|
||||
"<foreach collection='tasks' item='task' separator=';'>" +
|
||||
"UPDATE device_collect_task SET " +
|
||||
" first_time = CASE " +
|
||||
" WHEN first_time IS NULL AND #{task.firstTime}::TIMESTAMP IS NOT NULL THEN #{task.firstTime}::TIMESTAMP " +
|
||||
" ELSE first_time " +
|
||||
" END, " +
|
||||
" last_success_time = #{task.lastSuccessTime}::TIMESTAMP, " +
|
||||
" last_failed_time = #{task.lastFailedTime}::TIMESTAMP, " +
|
||||
" updated_at = #{task.updatedAt}::TIMESTAMP " +
|
||||
"WHERE id = #{task.id}" +
|
||||
"</foreach>" +
|
||||
"</script>")
|
||||
int batchUpdateTimes(@Param("tasks") List<DeviceCollectTask> tasks);
|
||||
|
||||
/**
|
||||
* 更新单个任务的时间
|
||||
*/
|
||||
@Update("UPDATE device_collect_task " +
|
||||
"SET first_time = CASE " +
|
||||
" WHEN first_time IS NULL AND #{firstTime}::TIMESTAMP IS NOT NULL THEN #{firstTime}::TIMESTAMP " +
|
||||
" ELSE first_time " +
|
||||
" END, " +
|
||||
" last_success_time = #{lastSuccessTime}::TIMESTAMP, " +
|
||||
" last_failed_time = #{lastFailTime}::TIMESTAMP, " +
|
||||
" updated_at = #{updateTime}::TIMESTAMP " +
|
||||
"WHERE id = #{deviceCollectId}")
|
||||
int updateTaskTime(@Param("deviceCollectId") String deviceCollectId,
|
||||
@Param("firstTime") LocalDateTime firstTime,
|
||||
@Param("lastSuccessTime") LocalDateTime lastSuccessTime,
|
||||
@Param("lastFailTime") LocalDateTime lastFailTime,
|
||||
@Param("updateTime") LocalDateTime updateTime);
|
||||
|
||||
/**
|
||||
* 查询所有设备任务
|
||||
*/
|
||||
@Select("SELECT * FROM device_collect_task")
|
||||
List<DeviceCollectTask> selectAllTasks();
|
||||
}
|
||||
+124
@@ -0,0 +1,124 @@
|
||||
package com.common.mapper;
|
||||
|
||||
|
||||
import com.common.entity.DeviceCollectTaskTime;
|
||||
import com.common.entity.DeviceReceiveLog;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import org.apache.ibatis.annotations.Select;
|
||||
@Mapper
|
||||
public interface DeviceReceiveLogMapper {
|
||||
|
||||
/**
|
||||
* 插入单条记录
|
||||
*/
|
||||
int insert(DeviceReceiveLog log);
|
||||
|
||||
/**
|
||||
* 批量插入记录
|
||||
*/
|
||||
int batchInsert(@Param("list") List<DeviceReceiveLog> logs);
|
||||
|
||||
/**
|
||||
* 根据ID查询
|
||||
*/
|
||||
DeviceReceiveLog selectById(@Param("id") Long id);
|
||||
|
||||
/**
|
||||
* 根据设备ID查询
|
||||
*/
|
||||
List<DeviceReceiveLog> selectByDeviceId(@Param("deviceId") Integer deviceId);
|
||||
|
||||
/**
|
||||
* 根据采集探针ID查询
|
||||
*/
|
||||
List<DeviceReceiveLog> selectByCollectId(@Param("collectId") Integer collectId);
|
||||
|
||||
/**
|
||||
* 根据IP地址查询
|
||||
*/
|
||||
List<DeviceReceiveLog> selectByDeviceIp(@Param("deviceIp") String deviceIp);
|
||||
|
||||
/**
|
||||
* 根据时间范围查询
|
||||
*/
|
||||
List<DeviceReceiveLog> selectByTimeRange(
|
||||
@Param("startTime") LocalDateTime startTime,
|
||||
@Param("endTime") LocalDateTime endTime);
|
||||
|
||||
/**
|
||||
* 多条件组合查询
|
||||
*/
|
||||
List<DeviceReceiveLog> selectByCondition(DeviceReceiveLog condition);
|
||||
|
||||
/**
|
||||
* 统计设备接收日志数量
|
||||
*/
|
||||
Long countByCondition(DeviceReceiveLog condition);
|
||||
|
||||
/**
|
||||
* 根据时间范围删除旧数据
|
||||
*/
|
||||
int deleteByTimeRange(
|
||||
@Param("startTime") LocalDateTime startTime,
|
||||
@Param("endTime") LocalDateTime endTime);
|
||||
|
||||
/**
|
||||
* 获取最近N条记录
|
||||
*/
|
||||
List<DeviceReceiveLog> selectRecent(@Param("limit") Integer limit);
|
||||
|
||||
/**
|
||||
* 按设备分组统计日志数量
|
||||
*/
|
||||
List<Map<String, Object>> countByDeviceGroup();
|
||||
|
||||
|
||||
/**
|
||||
* 查询当天每个设备的最新成功时间
|
||||
*/
|
||||
@Select("SELECT device_collect_id, MAX(created_at) AS last_success_time " +
|
||||
"FROM device_receive_log " +
|
||||
"WHERE push_success = true " +
|
||||
"AND created_at >= CURRENT_DATE " +
|
||||
"GROUP BY device_collect_id")
|
||||
List<DeviceCollectTaskTime> selectDailySuccessTimes();
|
||||
|
||||
/**
|
||||
* 查询当天每个设备的最新失败时间
|
||||
*/
|
||||
@Select("SELECT device_collect_id, MAX(created_at) AS last_fail_time " +
|
||||
"FROM device_receive_log " +
|
||||
"WHERE push_success = false " +
|
||||
"AND created_at >= CURRENT_DATE " +
|
||||
"GROUP BY device_collect_id")
|
||||
List<DeviceCollectTaskTime> selectDailyFailTimes();
|
||||
|
||||
/**
|
||||
* 查询每个设备的首次成功时间(历史最早)
|
||||
*/
|
||||
@Select("SELECT device_collect_id, MIN(created_at) AS first_success_time " +
|
||||
"FROM device_receive_log " +
|
||||
"WHERE push_success = true " +
|
||||
"GROUP BY device_collect_id")
|
||||
List<DeviceCollectTaskTime> selectFirstSuccessTimes();
|
||||
|
||||
/**
|
||||
* 查询指定时间范围内的成功记录
|
||||
*/
|
||||
@Select("SELECT device_collect_id, MIN(created_at) AS first_time, " +
|
||||
"MAX(created_at) AS last_success_time " +
|
||||
"FROM device_receive_log " +
|
||||
"WHERE push_success = true " +
|
||||
"AND created_at >= #{startTime} " +
|
||||
"AND created_at < #{endTime} " +
|
||||
"GROUP BY device_collect_id")
|
||||
List<DeviceCollectTaskTime> selectSuccessTimesByRange(
|
||||
@Param("startTime") LocalDateTime startTime,
|
||||
@Param("endTime") LocalDateTime endTime);
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
package com.common.mapper;
|
||||
|
||||
|
||||
import com.common.entity.DmColumn;
|
||||
import org.apache.ibatis.annotations.*;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Mapper
|
||||
public interface DmColumnMapper {
|
||||
|
||||
// 查询所有列
|
||||
@Select("SELECT * FROM dm_column WHERE deleted_at IS NULL")
|
||||
List<DmColumn> findAll();
|
||||
|
||||
// 根据ID查询
|
||||
// @Select("SELECT * FROM dm_column WHERE id = #{id} AND deleted_at IS NULL")
|
||||
DmColumn findById(Long id);
|
||||
|
||||
// 根据名称查询
|
||||
@Select("SELECT * FROM dm_column WHERE name = #{name} AND deleted_at IS NULL")
|
||||
DmColumn findByName(String name);
|
||||
|
||||
// 根据显示名称模糊查询
|
||||
@Select("SELECT * FROM dm_column WHERE display_name LIKE CONCAT('%', #{displayName}, '%') AND deleted_at IS NULL")
|
||||
List<DmColumn> findByDisplayName(String displayName);
|
||||
|
||||
// 根据是否内置查询
|
||||
@Select("SELECT * FROM dm_column WHERE is_built_in = #{isBuiltIn} AND deleted_at IS NULL")
|
||||
List<DmColumn> findByIsBuiltIn(Boolean isBuiltIn);
|
||||
|
||||
// 插入数据
|
||||
@Insert("INSERT INTO dm_column (created_at, updated_at, name, display_name, storage_data_type, " +
|
||||
"business_data_type, is_built_in, is_hidden, is_not_normalizable, is_required, category_id, " +
|
||||
"custom_asset_category_id, is_virtual, table_id, asset_table_id, column_set_id, base_type, " +
|
||||
"user_task_id, created_by_id, create_dept, create_by, create_time, update_by, update_time) " +
|
||||
"VALUES (NOW(), NOW(), #{name}, #{displayName}, #{storageDataType}, #{businessDataType}, " +
|
||||
"#{isBuiltIn}, #{isHidden}, #{isNotNormalizable}, #{isRequired}, #{categoryId}, " +
|
||||
"#{customAssetCategoryId}, #{isVirtual}, #{tableId}, #{assetTableId}, #{columnSetId}, " +
|
||||
"#{baseType}, #{userTaskId}, #{createdById}, #{createDept}, #{createBy}, #{createTime}, " +
|
||||
"#{updateBy}, #{updateTime})")
|
||||
@Options(useGeneratedKeys = true, keyProperty = "id")
|
||||
int insert(DmColumn dmColumn);
|
||||
|
||||
// 批量插入
|
||||
@Insert("<script>" +
|
||||
"INSERT INTO dm_column (created_at, updated_at, name, display_name, is_built_in, is_hidden) " +
|
||||
"VALUES " +
|
||||
"<foreach collection='list' item='item' separator=','>" +
|
||||
"(NOW(), NOW(), #{item.name}, #{item.displayName}, #{item.isBuiltIn}, #{item.isHidden})" +
|
||||
"</foreach>" +
|
||||
"</script>")
|
||||
int batchInsert(List<DmColumn> dmColumns);
|
||||
|
||||
// 查询条件构造(使用XML方式)
|
||||
List<DmColumn> findByCondition(DmColumn condition);
|
||||
|
||||
// 统计数量
|
||||
@Select("SELECT COUNT(*) FROM dm_column WHERE deleted_at IS NULL")
|
||||
Long count();
|
||||
|
||||
|
||||
/**
|
||||
* 查询所有数据标准化字段
|
||||
* @param
|
||||
* @return 数据标准化字段
|
||||
*/
|
||||
List<Map<String, Object>> selectAllNormal();
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
package com.common.mapper;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import com.common.entity.DmNormalizeRule;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Mapper
|
||||
public interface DmNormalizeRuleMapper {
|
||||
|
||||
/**
|
||||
* 根据ID查询数据标准化规则
|
||||
* @param id 主键ID
|
||||
* @return 数据标准化规则对象
|
||||
*/
|
||||
DmNormalizeRule selectById(@Param("id") Long id);
|
||||
|
||||
/**
|
||||
* 根据Device ID查询数据标准化规则
|
||||
* @param id 主键device ID
|
||||
* @return 数据标准化规则对象
|
||||
*/
|
||||
List<Map<String, Object>> selectByDeviceId(@Param("id") Long id);
|
||||
|
||||
/**
|
||||
* 根据ID更新数据标准化规则
|
||||
* @param rule 数据标准化规则对象
|
||||
* @return 更新影响的行数
|
||||
*/
|
||||
int updateById(DmNormalizeRule rule);
|
||||
|
||||
/**
|
||||
* 根据ID和租户ID查询(带租户隔离)
|
||||
* @param id 主键ID
|
||||
* @param tenantId 租户ID
|
||||
* @return 数据标准化规则对象
|
||||
*/
|
||||
DmNormalizeRule selectByIdAndTenant(@Param("id") Long id, @Param("tenantId") String tenantId);
|
||||
|
||||
/**
|
||||
* 根据ID和租户ID更新(带租户隔离)
|
||||
* @param rule 数据标准化规则对象
|
||||
* @return 更新影响的行数
|
||||
*/
|
||||
int updateByIdAndTenant(DmNormalizeRule rule);
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
// SecExceptionAlgorithmMapper.java
|
||||
package com.common.mapper;
|
||||
|
||||
import com.common.entity.SecExceptionAlgorithm;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import org.apache.ibatis.annotations.Select;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import java.util.List;
|
||||
|
||||
@Mapper
|
||||
public interface SecExceptionAlgorithmMapper {
|
||||
|
||||
@Select("SELECT * FROM sec_exception_algorithm WHERE status = 1 AND del_flag = '0'")
|
||||
List<SecExceptionAlgorithm> findEnabledAlgorithms();
|
||||
|
||||
@Select("SELECT * FROM sec_exception_algorithm WHERE id = #{id}")
|
||||
SecExceptionAlgorithm findById(@Param("id") Long id);
|
||||
}
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
package com.common.mapper;
|
||||
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.common.entity.SyslogNonNormalMessage;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import org.apache.ibatis.annotations.Select;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 非标日志Mapper接口
|
||||
*/
|
||||
@Mapper
|
||||
public interface SyslogNonNormalMessageMapper extends BaseMapper<SyslogNonNormalMessage> {
|
||||
|
||||
/**
|
||||
* 批量插入非标日志
|
||||
* @param list 日志列表
|
||||
* @return 插入数量
|
||||
*/
|
||||
int batchInsert(@Param("list") List<SyslogNonNormalMessage> list);
|
||||
|
||||
/**
|
||||
* 根据时间段查询非标日志
|
||||
* @param startTime 开始时间
|
||||
* @param endTime 结束时间
|
||||
* @return 日志列表
|
||||
*/
|
||||
@Select("SELECT * FROM syslog_non_normal_message WHERE log_time BETWEEN #{startTime} AND #{endTime} AND del_flag = '0'")
|
||||
List<SyslogNonNormalMessage> findByTimeRange(@Param("startTime") LocalDateTime startTime,
|
||||
@Param("endTime") LocalDateTime endTime);
|
||||
|
||||
/**
|
||||
* 根据设备ID和状态统计
|
||||
* @param deviceId 设备ID
|
||||
* @param ruleResult 规则结果
|
||||
* @return 统计结果
|
||||
*/
|
||||
@Select("SELECT COUNT(*) as count FROM syslog_non_normal_message " +
|
||||
"WHERE device_id = #{deviceId} AND rule_result = #{ruleResult} AND del_flag = '0'")
|
||||
Map<String, Object> countByDeviceAndResult(@Param("deviceId") Integer deviceId,
|
||||
@Param("ruleResult") String ruleResult);
|
||||
|
||||
/**
|
||||
* 逻辑删除非标日志
|
||||
* @param id 日志ID
|
||||
* @return 更新数量
|
||||
*/
|
||||
@Select("UPDATE syslog_non_normal_message SET del_flag = '1', update_time = NOW() WHERE id = #{id}")
|
||||
int logicalDelete(@Param("id") String id);
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 根据ID和创建时间批量查询非标日志
|
||||
* @param ids ID列表
|
||||
* @param createdAts 创建时间列表
|
||||
* @return 非标日志列表
|
||||
*/
|
||||
List<SyslogNonNormalMessage> getMessagesByIdsAndCreatedAts(
|
||||
@Param("ids") List<String> ids,
|
||||
@Param("createdAts") List<String> createdAts);
|
||||
|
||||
/**
|
||||
* 根据ID列表批量查询非标日志
|
||||
* @param ids ID列表
|
||||
* @return 非标日志列表
|
||||
*/
|
||||
List<SyslogNonNormalMessage> getMessagesByIds(@Param("ids") List<String> ids);
|
||||
|
||||
/**
|
||||
* 批量更新del_flag字段
|
||||
* @param messages 需要更新的非标日志列表
|
||||
* @return 更新记录数
|
||||
*/
|
||||
int updateBatchDelFlag(@Param("messages") List<SyslogNonNormalMessage> messages);
|
||||
|
||||
/**
|
||||
* 批量更新记录
|
||||
* @param messages 需要更新的非标日志列表
|
||||
* @return 更新记录数
|
||||
*/
|
||||
int updateBatch(@Param("messages") List<SyslogNonNormalMessage> messages);
|
||||
}
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
package com.common.mapper;
|
||||
|
||||
import com.common.entity.GroupedSyslogData;
|
||||
import com.common.entity.SyslogNormalData;
|
||||
import com.common.entity.SyslogNormalAlarm;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import org.apache.ibatis.annotations.Select;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Mapper
|
||||
public interface SyslogNormalAlarmMapper {
|
||||
|
||||
/**
|
||||
* 动态插入数据 - 使用 Map
|
||||
*/
|
||||
int insertDynamic(@Param("dataMap") Map<String, Object> dataMap);
|
||||
|
||||
/**
|
||||
* 动态插入数据 - 使用实体类
|
||||
*/
|
||||
int insertByEntity(SyslogNormalAlarm entity);
|
||||
|
||||
/**
|
||||
* 批量插入数据
|
||||
*/
|
||||
int batchInsert(@Param("dataList") List<Map<String, Object>> dataList);
|
||||
|
||||
|
||||
/**
|
||||
* 统计24小时内分组数据量
|
||||
*/
|
||||
@Select("SELECT count(1) as group_count from ( select " +
|
||||
"to_char(log_time, 'YYYYMMDD') || '_' || " +
|
||||
"dest_ip || '_' || " +
|
||||
"origin_event_name " +
|
||||
"FROM syslog_normal_alarm " +
|
||||
"WHERE log_time >= #{startTime} AND log_time < #{endTime} " +
|
||||
"AND event_level >= 1 AND src_ip NOT IN ('127.0.0.1', '127.0.0.2') " +
|
||||
"GROUP BY to_char(log_time, 'YYYYMMDD'),src_ip, dest_ip, origin_event_name )" )
|
||||
Long count24HoursGroupedData(@Param("startTime") LocalDateTime startTime,
|
||||
@Param("endTime") LocalDateTime endTime);
|
||||
|
||||
/**
|
||||
* 分页查询分组数据
|
||||
*/
|
||||
@Select("SELECT " +
|
||||
"to_char(log_time, 'YYYYMMDD') as log_date, " +
|
||||
" MIN(origin_event_type) AS first_event_type, " +
|
||||
"ARRAY_AGG(DISTINCT host(src_ip)::text) as attack_ips, " +
|
||||
"origin_event_name, " +
|
||||
"MIN(log_time) as min_log_time, " +
|
||||
"MAX(log_time) as max_log_time, " +
|
||||
"COUNT(1) as log_count, " +
|
||||
"ARRAY_AGG(DISTINCT host(dest_ip)::text) as victim_ips, " +
|
||||
"ARRAY_AGG(DISTINCT device_id) as device_ids, " +
|
||||
"ARRAY_AGG(DISTINCT id) as origin_log_ids, " +
|
||||
"MAX(event_level) as max_event_level, " +
|
||||
"MAX(origin_event_type) as event_type, " +
|
||||
"MIN(event_type) as min_event_type, " +
|
||||
"ARRAY_AGG(DISTINCT src_port::int4) as attack_ports, " +
|
||||
"ARRAY_AGG(DISTINCT dest_port::int4) as victim_ports, " +
|
||||
"ARRAY_AGG(DISTINCT http_resp_codes::text) as http_status_codes, " +
|
||||
"ARRAY_AGG(DISTINCT payload::BYTEA) as payload_samples, " +
|
||||
"ARRAY_AGG(DISTINCT http_req_header) as httpReqHeaders, " +
|
||||
"ARRAY_AGG(DISTINCT http_req_body) as httpReqBodys, " +
|
||||
"ARRAY_AGG(DISTINCT http_resp_header) as httpRespHeaders, " +
|
||||
"ARRAY_AGG(DISTINCT http_resp_body) as httpRespBodys, " +
|
||||
"STRING_AGG(DISTINCT COALESCE(host(dest_ip)::text, ''), ',') as victim_ips_str " +
|
||||
"FROM syslog_normal_alarm " +
|
||||
"WHERE log_time >= #{startTime} AND log_time < #{endTime} " +
|
||||
"AND event_level >= 1 AND src_ip NOT IN ('127.0.0.1', '127.0.0.2') " +
|
||||
"GROUP BY to_char(log_time, 'YYYYMMDD'), src_ip, dest_ip, origin_event_name " +
|
||||
"ORDER BY log_date, dest_ip, origin_event_name " +
|
||||
"LIMIT #{pageSize} OFFSET #{offset}")
|
||||
List<GroupedSyslogData> select24HoursGroupedDataByPage(
|
||||
@Param("startTime") LocalDateTime startTime,
|
||||
@Param("endTime") LocalDateTime endTime,
|
||||
@Param("offset") int offset,
|
||||
@Param("pageSize") int pageSize);
|
||||
}
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
package com.common.mapper;
|
||||
|
||||
import com.common.entity.GroupedSyslogData;
|
||||
import com.common.entity.SyslogNormalData;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import java.util.Map;
|
||||
import org.apache.ibatis.annotations.Select;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
@Mapper
|
||||
public interface SyslogNormalDataMapper {
|
||||
|
||||
/**
|
||||
* 动态插入数据 - 使用 Map
|
||||
*/
|
||||
int insertDynamic(@Param("dataMap") Map<String, Object> dataMap);
|
||||
|
||||
/**
|
||||
* 动态插入数据 - 使用实体类
|
||||
*/
|
||||
int insertByEntity(SyslogNormalData entity);
|
||||
|
||||
/**
|
||||
* 批量插入数据
|
||||
*/
|
||||
int batchInsert(@Param("dataList") java.util.List<Map<String, Object>> dataList);
|
||||
|
||||
|
||||
/**
|
||||
* 统计24小时内分组数据量
|
||||
*/
|
||||
@Select("SELECT count(1) as group_count from ( select " +
|
||||
"to_char(log_time, 'YYYYMMDD') || '_' || " +
|
||||
"dest_ip || '_' || " +
|
||||
"origin_event_name " +
|
||||
"FROM syslog_normal_data " +
|
||||
"WHERE log_time >= #{startTime} AND log_time < #{endTime} " +
|
||||
"AND http_resp_codes =200 and origin_event_type <> '' and origin_event_name='访问日志' AND src_ip NOT IN ('127.0.0.1', '127.0.0.2') " +
|
||||
"GROUP BY to_char(log_time, 'YYYYMMDD'),src_ip, dest_ip, origin_event_name )" )
|
||||
Long count24HoursGroupedData(@Param("startTime") LocalDateTime startTime,
|
||||
@Param("endTime") LocalDateTime endTime);
|
||||
|
||||
/**
|
||||
* 分页查询分组数据
|
||||
*/
|
||||
@Select("SELECT " +
|
||||
"to_char(log_time, 'YYYYMMDD') as log_date, " +
|
||||
" MIN(origin_event_type) AS first_event_type, " +
|
||||
"ARRAY_AGG(DISTINCT host(src_ip)::text) as attack_ips, " +
|
||||
"origin_event_name, " +
|
||||
"MIN(log_time) as min_log_time, " +
|
||||
"MAX(log_time) as max_log_time, " +
|
||||
"COUNT(1) as log_count, " +
|
||||
"ARRAY_AGG(DISTINCT host(dest_ip)::text) as victim_ips, " +
|
||||
"ARRAY_AGG(DISTINCT device_id) as device_ids, " +
|
||||
"ARRAY_AGG(DISTINCT id) as origin_log_ids, " +
|
||||
"MAX(event_level) as max_event_level, " +
|
||||
"MAX(origin_event_type) as event_type, " +
|
||||
"MIN(event_type) as min_event_type, " +
|
||||
"ARRAY_AGG(DISTINCT src_port::int4) as attack_ports, " +
|
||||
"ARRAY_AGG(DISTINCT dest_port::int4) as victim_ports, " +
|
||||
"ARRAY_AGG(DISTINCT http_resp_codes::text) as http_status_codes, " +
|
||||
"ARRAY_AGG(DISTINCT payload::BYTEA) as payload_samples, " +
|
||||
"ARRAY_AGG(DISTINCT http_req_header) as httpReqHeaders, " +
|
||||
"ARRAY_AGG(DISTINCT http_req_body) as httpReqBodys, " +
|
||||
"ARRAY_AGG(DISTINCT http_resp_header) as httpRespHeaders, " +
|
||||
"ARRAY_AGG(DISTINCT http_resp_body) as httpRespBodys, " +
|
||||
"STRING_AGG(DISTINCT COALESCE(host(dest_ip)::text, ''), ',') as victim_ips_str " +
|
||||
"FROM syslog_normal_data " +
|
||||
"WHERE log_time >= #{startTime} AND log_time < #{endTime} " +
|
||||
"AND http_resp_codes =200 and origin_event_type <> '' and origin_event_name='访问日志' AND src_ip NOT IN ('127.0.0.1', '127.0.0.2') " +
|
||||
"GROUP BY to_char(log_time, 'YYYYMMDD'), src_ip, dest_ip, origin_event_name " +
|
||||
"ORDER BY log_date, dest_ip, origin_event_name " +
|
||||
"LIMIT #{pageSize} OFFSET #{offset}")
|
||||
List<GroupedSyslogData> select24HoursGroupedDataByPage(
|
||||
@Param("startTime") LocalDateTime startTime,
|
||||
@Param("endTime") LocalDateTime endTime,
|
||||
@Param("offset") int offset,
|
||||
@Param("pageSize") int pageSize);
|
||||
|
||||
/**
|
||||
* 查询指定时间后的所需字段(使用XML映射)
|
||||
* 注意:参数类型保持为LocalDateTime,但实际映射时使用类型处理器转换
|
||||
*/
|
||||
List<SyslogNormalData> findRequiredFieldsAfterTime(@Param("startTime") LocalDateTime startTime);
|
||||
|
||||
/**
|
||||
* 分页查询所需字段
|
||||
*/
|
||||
List<SyslogNormalData> findRequiredFieldsByPage(
|
||||
@Param("startTime") LocalDateTime startTime,
|
||||
@Param("limit") int limit,
|
||||
@Param("offset") int offset
|
||||
);
|
||||
@Select("SELECT * FROM syslog_normal_data WHERE created_at >= #{startTime, jdbcType=TIMESTAMP} ORDER BY created_at ASC")
|
||||
List<SyslogNormalData> findAfterTime(@Param("startTime") LocalDateTime startTime);
|
||||
|
||||
@Select("SELECT * FROM syslog_normal_data WHERE id = #{id}")
|
||||
SyslogNormalData findById(@Param("id") String id);
|
||||
}
|
||||
+108
@@ -0,0 +1,108 @@
|
||||
package com.common.mapper;
|
||||
|
||||
import com.common.entity.XdrHoneypot;
|
||||
import org.apache.ibatis.annotations.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* XDR Honeypot Mapper 接口
|
||||
*/
|
||||
public interface XdrHoneypotMapper {
|
||||
|
||||
/**
|
||||
* 插入单条记录
|
||||
*/
|
||||
@Insert("INSERT INTO xdr_honeypot (vcsource, dstart_time, dtime, risk_level, vcconnection, " +
|
||||
"file_info, extra, vctype, agent_sn, agent_name, honeypot_id, honeypot_name, " +
|
||||
"src_ip, src_port, src_mac, dest_ip, dest_port, proxy_ip, node) " +
|
||||
"VALUES (#{vcsource}, #{dstartTime}, #{dtime}, #{riskLevel}, #{vcconnection}, " +
|
||||
"#{fileInfo}, #{extra}, #{vctype}, #{agentSn}, #{agentName}, #{honeypotId}, #{honeypotName}, " +
|
||||
"#{srcIp}, #{srcPort}, #{srcMac}, #{destIp}, #{destPort}, #{proxyIp}, #{node})")
|
||||
@Options(useGeneratedKeys = true, keyProperty = "id")
|
||||
int insert(XdrHoneypot xdrHoneypot);
|
||||
|
||||
/**
|
||||
* 批量插入记录
|
||||
*/
|
||||
int batchInsert(List<XdrHoneypot> xdrHoneypotList);
|
||||
|
||||
/**
|
||||
* 根据ID查询记录
|
||||
*/
|
||||
@Select("SELECT * FROM xdr_honeypot WHERE id = #{id}")
|
||||
@Results({
|
||||
@Result(property = "id", column = "id"),
|
||||
@Result(property = "vcsource", column = "vcsource"),
|
||||
@Result(property = "dstartTime", column = "dstart_time"),
|
||||
@Result(property = "dtime", column = "dtime"),
|
||||
@Result(property = "riskLevel", column = "risk_level"),
|
||||
@Result(property = "vcconnection", column = "vcconnection"),
|
||||
@Result(property = "fileInfo", column = "file_info"),
|
||||
@Result(property = "extra", column = "extra"),
|
||||
@Result(property = "vctype", column = "vctype"),
|
||||
@Result(property = "agentSn", column = "agent_sn"),
|
||||
@Result(property = "agentName", column = "agent_name"),
|
||||
@Result(property = "honeypotId", column = "honeypot_id"),
|
||||
@Result(property = "honeypotName", column = "honeypot_name"),
|
||||
@Result(property = "srcIp", column = "src_ip"),
|
||||
@Result(property = "srcPort", column = "src_port"),
|
||||
@Result(property = "srcMac", column = "src_mac"),
|
||||
@Result(property = "destIp", column = "dest_ip"),
|
||||
@Result(property = "destPort", column = "dest_port"),
|
||||
@Result(property = "proxyIp", column = "proxy_ip"),
|
||||
@Result(property = "node", column = "node")
|
||||
})
|
||||
XdrHoneypot selectById(Long id);
|
||||
|
||||
/**
|
||||
* 查询所有记录
|
||||
*/
|
||||
@Select("SELECT * FROM xdr_honeypot ORDER BY id DESC")
|
||||
@Results({
|
||||
@Result(property = "dstartTime", column = "dstart_time"),
|
||||
@Result(property = "riskLevel", column = "risk_level"),
|
||||
@Result(property = "fileInfo", column = "file_info"),
|
||||
@Result(property = "agentSn", column = "agent_sn"),
|
||||
@Result(property = "agentName", column = "agent_name"),
|
||||
@Result(property = "honeypotId", column = "honeypot_id"),
|
||||
@Result(property = "honeypotName", column = "honeypot_name"),
|
||||
@Result(property = "srcIp", column = "src_ip"),
|
||||
@Result(property = "srcPort", column = "src_port"),
|
||||
@Result(property = "srcMac", column = "src_mac"),
|
||||
@Result(property = "destIp", column = "dest_ip"),
|
||||
@Result(property = "destPort", column = "dest_port"),
|
||||
@Result(property = "proxyIp", column = "proxy_ip")
|
||||
})
|
||||
List<XdrHoneypot> selectAll();
|
||||
|
||||
/**
|
||||
* 根据源IP查询记录
|
||||
*/
|
||||
@Select("SELECT * FROM xdr_honeypot WHERE src_ip = #{srcIp} ORDER BY dtime DESC")
|
||||
List<XdrHoneypot> selectBySrcIp(String srcIp);
|
||||
|
||||
/**
|
||||
* 根据风险等级查询记录
|
||||
*/
|
||||
@Select("SELECT * FROM xdr_honeypot WHERE risk_level = #{riskLevel} ORDER BY dtime DESC")
|
||||
List<XdrHoneypot> selectByRiskLevel(String riskLevel);
|
||||
|
||||
/**
|
||||
* 更新记录
|
||||
*/
|
||||
@Update("UPDATE xdr_honeypot SET risk_level = #{riskLevel}, extra = #{extra} WHERE id = #{id}")
|
||||
int update(XdrHoneypot xdrHoneypot);
|
||||
|
||||
/**
|
||||
* 根据ID删除记录
|
||||
*/
|
||||
@Delete("DELETE FROM xdr_honeypot WHERE id = #{id}")
|
||||
int delete(Long id);
|
||||
|
||||
/**
|
||||
* 统计总记录数
|
||||
*/
|
||||
@Select("SELECT COUNT(*) FROM xdr_honeypot")
|
||||
long count();
|
||||
}
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
package com.common.schedule;
|
||||
|
||||
|
||||
import com.common.service.DataExtractor;
|
||||
import com.Modules.etl.handler.ETLRetryHandler;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Component;
|
||||
import com.Modules.etl.TimeWindowCalculator;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import com.common.service.DeviceReceiveLogService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class ETLOrchestrator {
|
||||
|
||||
@Autowired
|
||||
private DataExtractor dataExtractor;
|
||||
|
||||
@Autowired
|
||||
private ETLRetryHandler retryHandler;
|
||||
|
||||
@Autowired
|
||||
private DeviceReceiveLogService deviceReceiveLogService;
|
||||
/**
|
||||
* 定时任务 - 从每小时第1分钟开始,5分钟间隔执行
|
||||
*/
|
||||
@Scheduled(cron = "0 1/5 * * * ?")
|
||||
public void scheduledETL() {
|
||||
//log.info("开始定时ETL任务");
|
||||
long startTime = System.currentTimeMillis();
|
||||
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
|
||||
LocalDateTime[] currentWindow=TimeWindowCalculator.getPrevious5MinuteWindow();
|
||||
String strStartTime= currentWindow[0].format(formatter);
|
||||
String strEndTime= currentWindow[1].format(formatter);
|
||||
log.info("ETL任务开始执行,开始时间:{},结束时间:{}",strStartTime,strEndTime );
|
||||
try {
|
||||
//retryHandler.executeWithRetry(() -> dataExtractor.extractAndProcess24HoursGroupedData());
|
||||
retryHandler.executeWithRetry(() -> dataExtractor.extractAndProcessQueryHoursGroupedData(strStartTime,strEndTime ));
|
||||
retryHandler.executeWithRetry(() -> dataExtractor.extractAndProcessQueryHoursAlarm(strStartTime,strEndTime ));
|
||||
long endTime = System.currentTimeMillis();
|
||||
long duration = (endTime - startTime) / 1000;
|
||||
log.info("定时ETL任务执行完成,耗时: {} 秒", duration);
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("定时ETL任务执行失败", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 手动触发ETL任务
|
||||
*/
|
||||
public void triggerETLManually() {
|
||||
log.info("手动触发ETL任务");
|
||||
try {
|
||||
//retryHandler.executeWithRetry(() ->
|
||||
//dataExtractor.extractAndProcess24HoursGroupedData());
|
||||
retryHandler.executeWithRetry(() ->
|
||||
dataExtractor.extractAndProcessQueryHoursGroupedData("2025-11-01 00:00:00","2025-11-15 00:00:00"));
|
||||
log.info("手动ETL任务执行完成");
|
||||
} catch (Exception e) {
|
||||
log.error("手动ETL任务执行失败", e);
|
||||
throw new RuntimeException("ETL任务执行失败", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 手动触发ETL任务,参数开始时间,结束时间
|
||||
* @param startTime
|
||||
* @param endTime
|
||||
*/
|
||||
public void triggerETLManuallyByTime(String startTime ,String endTime) {
|
||||
log.info("手动触发ETL任务");
|
||||
try {
|
||||
retryHandler.executeWithRetry(() ->
|
||||
dataExtractor.extractAndProcessQueryHoursGroupedData( startTime , endTime ));
|
||||
retryHandler.executeWithRetry(() -> dataExtractor.extractAndProcessQueryHoursAlarm(startTime,endTime ));
|
||||
log.info("手动ETL任务执行完成");
|
||||
} catch (Exception e) {
|
||||
log.error("手动ETL任务执行失败", e);
|
||||
throw new RuntimeException("ETL任务执行失败", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 每天凌晨3点清理2天前的数据
|
||||
*/
|
||||
//@Scheduled(cron = "0 0 3 * * ?")
|
||||
@Scheduled(cron = "0 * * * * ?")
|
||||
public void cleanupOldLogs() {
|
||||
try {
|
||||
LocalDateTime cutoffTime = LocalDateTime.now().minusDays(2);
|
||||
int deleted = deviceReceiveLogService.deleteOldLogs(cutoffTime);
|
||||
log.info("定时清理任务完成,删除{}条2天前的日志", deleted);
|
||||
} catch (Exception e) {
|
||||
log.error("定时清理日志失败", e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
LocalDateTime befor= LocalDateTime.of(2025, 11, 1, 0, 0 ,0); // 默认2025年11月
|
||||
LocalDateTime cutoffTime = LocalDateTime.now().minusDays(2);
|
||||
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
|
||||
System.out.println(befor.format(formatter).toString());
|
||||
System.out.println(cutoffTime.format(formatter).toString());
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
+122
@@ -0,0 +1,122 @@
|
||||
package com.common.schedule;
|
||||
|
||||
import com.common.service.PartitionTableService;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Component;
|
||||
import com.common.service.PartitionTableService;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Component;
|
||||
import java.util.List;
|
||||
@Component
|
||||
public class PartitionTableSchedule {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(PartitionTableSchedule.class);
|
||||
|
||||
@Autowired
|
||||
private PartitionTableService partitionTableService;
|
||||
|
||||
/**
|
||||
* 每月15日凌晨1点执行
|
||||
* cron表达式: 秒 分 时 日 月 周
|
||||
*/
|
||||
@Scheduled(cron = "0 0 1 15 * ?")
|
||||
public void createNextMonthPartitionTables() {
|
||||
logger.info("开始执行创建下个月分区表任务...");
|
||||
|
||||
try {
|
||||
int partitionCount = partitionTableService.getNextMonthPartitionCount();
|
||||
logger.info("需要创建 {} 个分区表", partitionCount);
|
||||
|
||||
partitionTableService.createNextMonthPartitionTable();
|
||||
|
||||
logger.info("创建下个月分区表任务完成");
|
||||
} catch (Exception e) {
|
||||
logger.error("定时创建分区表任务失败: {}", e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 测试任务 - 每分钟执行一次(开发环境使用)
|
||||
* 生产环境注释或删除此方法
|
||||
*/
|
||||
//@Scheduled(cron = "0 * * * * ?")
|
||||
public void testCreatePartitionTables() {
|
||||
logger.info("测试任务: 开始创建分区表...");
|
||||
partitionTableService.createNextMonthPartitionTable();
|
||||
logger.info("测试任务: 分区表创建完成");
|
||||
}
|
||||
|
||||
/**
|
||||
* 每天检查一次分区表状态(可选)
|
||||
*/
|
||||
@Scheduled(cron = "0 0 2 * * ?")
|
||||
public void checkPartitionTableStatus() {
|
||||
logger.info("开始检查分区表状态...");
|
||||
// 这里可以添加分区表状态检查逻辑
|
||||
logger.info("分区表状态检查完成");
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 每天检查第二天的分区表状态 - 凌晨2点执行
|
||||
*/
|
||||
@Scheduled(cron = "0 0 2 * * ?")
|
||||
public void checkTomorrowPartitionTable() {
|
||||
logger.info("开始检查第二天的分区表状态...");
|
||||
|
||||
try {
|
||||
PartitionTableService.PartitionTableStatus status =
|
||||
partitionTableService.checkTomorrowPartitionTable();
|
||||
|
||||
if (status.isExists()) {
|
||||
logger.info("第二天分区表已存在: {}", status.getTableName());
|
||||
} else if (status.isCreated()) {
|
||||
logger.info("第二天分区表创建成功: {}", status.getTableName());
|
||||
} else {
|
||||
logger.warn("第二天分区表检查异常: {}", status.getMessage());
|
||||
// 这里添加告警通知,比如发送邮件、短信等
|
||||
//sendAlertNotification(status);
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
logger.error("检查第二天分区表失败: {}", e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 每周一检查未来7天的分区表状态
|
||||
*/
|
||||
@Scheduled(cron = "0 0 3 * * MON")
|
||||
public void checkNextWeekPartitionTables() {
|
||||
logger.info("开始检查未来7天的分区表状态...");
|
||||
|
||||
try {
|
||||
List<PartitionTableService.PartitionTableStatus> statusList = partitionTableService.checkFuturePartitionTables(7);
|
||||
|
||||
int missingCount = 0;
|
||||
for (PartitionTableService.PartitionTableStatus status : statusList) {
|
||||
if (!status.isExists()) {
|
||||
missingCount++;
|
||||
logger.warn("未来分区表缺失: {}", status.getTableName());
|
||||
}
|
||||
}
|
||||
|
||||
if (missingCount > 0) {
|
||||
logger.warn("发现 {} 个未来分区表缺失", missingCount);
|
||||
// 可以触发自动创建或发送告警
|
||||
} else {
|
||||
logger.info("未来7天分区表状态正常");
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
logger.error("检查未来分区表失败: {}", e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
package com.common.schedule;
|
||||
|
||||
|
||||
|
||||
|
||||
import com.common.service.EsToDbSyncService;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
|
||||
//众诚运维日志数据计划任务
|
||||
@Slf4j
|
||||
//@Component
|
||||
public class ScheduledTask {
|
||||
|
||||
@Autowired
|
||||
private EsToDbSyncService esToDbSyncService;
|
||||
|
||||
private static final DateTimeFormatter INDEX_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd");
|
||||
|
||||
/**
|
||||
* 每天1点同步昨天的数据
|
||||
*/
|
||||
//c
|
||||
public void syncYesterdayData() {
|
||||
log.info("开始执行昨天数据同步任务");
|
||||
LocalDate yesterday = LocalDate.now().minusDays(1);
|
||||
String indexName = "applog-" + yesterday.format(INDEX_FORMATTER);
|
||||
esToDbSyncService.syncEsLogsByIndexToDatabase(indexName);
|
||||
log.info("昨天数据同步任务完成");
|
||||
}
|
||||
|
||||
/**
|
||||
* 每天1,5,9,13,17,21点同步今天的数据
|
||||
*/
|
||||
// @Scheduled(cron = "0 0 1,5,9,13,17,21 * * ?")
|
||||
public void syncTodayData() {
|
||||
log.info("开始执行今天数据同步任务");
|
||||
LocalDate today = LocalDate.now();
|
||||
String indexName = "applog-" + today.format(INDEX_FORMATTER);
|
||||
esToDbSyncService.syncEsLogsByIndexToDatabase(indexName);
|
||||
log.info("今天数据同步任务完成");
|
||||
}
|
||||
|
||||
/**
|
||||
* 手动同步指定日期的数据(可用于测试)
|
||||
*/
|
||||
public void syncSpecificDateData(LocalDate date) {
|
||||
log.info("开始执行指定日期数据同步任务: {}", date);
|
||||
String indexName = "applog-" + date.format(INDEX_FORMATTER);
|
||||
esToDbSyncService.syncEsLogsByIndexToDatabase(indexName);
|
||||
log.info("指定日期数据同步任务完成: {}", date);
|
||||
}
|
||||
}
|
||||
+397
@@ -0,0 +1,397 @@
|
||||
package com.common.service;
|
||||
|
||||
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.JSONArray;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.common.entity.AlarmVisit;
|
||||
import com.common.entity.SecExceptionAlgorithm;
|
||||
import com.common.entity.SyslogNormalData;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.http.*;
|
||||
import org.springframework.scheduling.annotation.Async;
|
||||
import org.springframework.scheduling.annotation.EnableAsync;
|
||||
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import com.common.mapper.*;
|
||||
import java.net.InetAddress;
|
||||
import com.common.util.AlgorithmResultParser;
|
||||
@Slf4j
|
||||
@Service
|
||||
@EnableScheduling
|
||||
@EnableAsync
|
||||
public class AccessLogAlertService {
|
||||
@Autowired
|
||||
private AlgorithmResultParser algorithmResultParser;
|
||||
@Autowired
|
||||
private RestTemplate restTemplate;
|
||||
|
||||
@Autowired
|
||||
private SyslogNormalDataMapper syslogNormalDataMapper;
|
||||
|
||||
@Autowired
|
||||
private SecExceptionAlgorithmMapper secExceptionAlgorithmMapper;
|
||||
|
||||
@Autowired
|
||||
private AlarmVisitMapper alarmVisitMapper;
|
||||
|
||||
// 记录上次处理的时间戳
|
||||
private LocalDateTime lastProcessTime;
|
||||
|
||||
// 时间格式化器
|
||||
private static final DateTimeFormatter DATE_TIME_FORMATTER =
|
||||
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
|
||||
|
||||
// 存储算法配置的缓存
|
||||
private Map<Long, SecExceptionAlgorithm> algorithmCache = new ConcurrentHashMap<>();
|
||||
|
||||
@PostConstruct
|
||||
public void init() {
|
||||
// 初始化时设置为当前时间减2分钟
|
||||
lastProcessTime = LocalDateTime.now().minusMinutes(2);
|
||||
log.info("初始化AccessLogAlertService,上次处理时间: {}", lastProcessTime);
|
||||
|
||||
// 加载启用的算法配置到缓存
|
||||
loadAlgorithmConfigs();
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载启用的算法配置
|
||||
*/
|
||||
private void loadAlgorithmConfigs() {
|
||||
try {
|
||||
List<SecExceptionAlgorithm> enabledAlgorithms = secExceptionAlgorithmMapper.findEnabledAlgorithms();
|
||||
algorithmCache.clear();
|
||||
for (SecExceptionAlgorithm algorithm : enabledAlgorithms) {
|
||||
algorithmCache.put(algorithm.getId(), algorithm);
|
||||
}
|
||||
log.info("加载了 {} 个启用的算法配置", algorithmCache.size());
|
||||
} catch (Exception e) {
|
||||
log.error("加载算法配置失败: {}", e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 定时任务入口 - 每2分钟执行一次
|
||||
*/
|
||||
@Scheduled(cron = "0 */2 * * * ?")
|
||||
@Async
|
||||
public void processAccessLogAlert() {
|
||||
log.info("开始执行访问日志告警处理任务");
|
||||
|
||||
try {
|
||||
// 1. 刷新算法配置缓存
|
||||
loadAlgorithmConfigs();
|
||||
|
||||
if (algorithmCache.isEmpty()) {
|
||||
log.warn("没有启用的算法配置,跳过本次处理");
|
||||
return;
|
||||
}
|
||||
|
||||
// 2. 获取上次处理时间之后的日志数据
|
||||
LocalDateTime currentTime = LocalDateTime.now();
|
||||
//List<SyslogNormalData> newLogs = syslogNormalDataMapper.findAfterTime(lastProcessTime);
|
||||
List<SyslogNormalData> newLogs = syslogNormalDataMapper.findRequiredFieldsAfterTime(lastProcessTime);
|
||||
//List<SyslogNormalData> newLogs =algorithmResultParser.buildNewLogsFromExample();
|
||||
if (newLogs.isEmpty()) {
|
||||
log.info("没有发现新的日志数据,上次处理时间: {}", lastProcessTime);
|
||||
return;
|
||||
}
|
||||
|
||||
log.info("获取到 {} 条新的日志数据,时间范围: {} 到 {}",
|
||||
newLogs.size(), lastProcessTime, currentTime);
|
||||
|
||||
// 3. 处理每条启用的算法配置
|
||||
for (SecExceptionAlgorithm algorithm : algorithmCache.values()) {
|
||||
try {
|
||||
processAlgorithm(algorithm, newLogs);
|
||||
} catch (Exception e) {
|
||||
log.error("处理算法配置失败 [算法ID: {}, 算法名称: {}]: {}",
|
||||
algorithm.getId(), algorithm.getAlgorithmName(), e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
// 4. 更新处理时间
|
||||
lastProcessTime = currentTime;
|
||||
log.info("访问日志告警处理任务完成,下次将从 {} 开始处理", lastProcessTime);
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("访问日志告警处理任务异常: {}", e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理单个算法配置
|
||||
*/
|
||||
private void processAlgorithm(SecExceptionAlgorithm algorithm, List<SyslogNormalData> logs) {
|
||||
log.info("开始处理算法: {} (ID: {})", algorithm.getAlgorithmName(), algorithm.getId());
|
||||
|
||||
// 1. 构建API请求参数
|
||||
JSONArray requestBody = buildRequestBody(logs);
|
||||
|
||||
if (requestBody.isEmpty()) {
|
||||
log.info("算法 {} 无有效的请求参数,跳过", algorithm.getAlgorithmName());
|
||||
return;
|
||||
}
|
||||
|
||||
// 2. 调用Python算子API
|
||||
ResponseEntity<String> response = callAlgorithmApi(algorithm, requestBody);
|
||||
|
||||
if (response == null || !response.getStatusCode().is2xxSuccessful()) {
|
||||
log.error("调用算法API失败: {} - {}", algorithm.getApiUrl(),
|
||||
response != null ? response.getStatusCode() : "无响应");
|
||||
return;
|
||||
}
|
||||
|
||||
// 直接解析响应体为JSONArray
|
||||
JSONArray results = JSON.parseArray(response.getBody());
|
||||
if (results == null || results.isEmpty()) {
|
||||
log.info("算法 {} 未检测到告警", algorithm.getAlgorithmName());
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
// 3. 解析API响应并写入告警表
|
||||
processApiResponse(algorithm, response.getBody(), logs);
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建API请求体
|
||||
*/
|
||||
private JSONArray buildRequestBody(List<SyslogNormalData> logs) {
|
||||
JSONArray requestArray = new JSONArray();
|
||||
|
||||
for (SyslogNormalData logData : logs) {
|
||||
JSONObject logObject = new JSONObject();
|
||||
|
||||
// 按照要求的格式构建请求参数
|
||||
logObject.put("_id", logData.getId() != null ? logData.getId() : "");
|
||||
logObject.put("_index", "es1:skyeye-file-" +
|
||||
LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy.MM.dd")));
|
||||
logObject.put("_source.@timestamp",
|
||||
ZonedDateTime.of(logData.getLogTime(), ZoneId.systemDefault())
|
||||
.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME));
|
||||
logObject.put("_source.@version", "6");
|
||||
logObject.put("_source.access_time",
|
||||
logData.getLogTime().format(DATE_TIME_FORMATTER));
|
||||
logObject.put("_source.device_ip",
|
||||
logData.getDeviceIp() != null ? logData.getDeviceIp() : "");
|
||||
logObject.put("_source.dip",
|
||||
logData.getDestIp() != null ? logData.getDestIp() : "");
|
||||
logObject.put("_source.dport", logData.getDestPort() != null ? logData.getDestPort() : 0);
|
||||
logObject.put("_source.dst_mac", logData.getDestMac() != null ? logData.getDestMac() : "");
|
||||
logObject.put("_source.file_dir", logData.getHostFilePath() != null ? 1 : 0);
|
||||
logObject.put("_source.file_md5", logData.getFileMd5() != null ? logData.getFileMd5() : "");
|
||||
logObject.put("_source.filename", logData.getFileName() != null ? logData.getFileName() : "");
|
||||
|
||||
// Geo信息
|
||||
JSONObject geoDip = new JSONObject();
|
||||
geoDip.put("city_name", logData.getDestCity() != null ? logData.getDestCity() : "");
|
||||
geoDip.put("continent_code", "");
|
||||
geoDip.put("country_code2", "");
|
||||
geoDip.put("country_name", logData.getDestCountry() != null ? logData.getDestCountry() : "");
|
||||
geoDip.put("latitude", logData.getDestLat() != null ? logData.getDestLat() : "");
|
||||
geoDip.put("longitude", logData.getDestLon() != null ? logData.getDestLon() : "");
|
||||
|
||||
JSONObject geoSip = new JSONObject();
|
||||
geoSip.put("city_name", logData.getSrcCity() != null ? logData.getSrcCity() : "");
|
||||
geoSip.put("continent_code", "");
|
||||
geoSip.put("country_code2", logData.getSrcCountryCode() != null ? logData.getSrcCountryCode() : "");
|
||||
geoSip.put("country_name", logData.getSrcCountry() != null ? logData.getSrcCountry() : "");
|
||||
geoSip.put("latitude", logData.getSrcLat() != null ? logData.getSrcLat() : "");
|
||||
geoSip.put("longitude", logData.getSrcLon() != null ? logData.getSrcLon() : "");
|
||||
|
||||
logObject.put("_source.geo_dip", geoDip);
|
||||
logObject.put("_source.geo_sip", geoSip);
|
||||
|
||||
// HTTP相关字段
|
||||
logObject.put("_source.host", logData.getHttpHost() != null ? logData.getHttpHost() : "");
|
||||
logObject.put("_source.host_md5", logData.getHostFileMd5() != null ? logData.getHostFileMd5() : "");
|
||||
logObject.put("_source.host_raw", logData.getHttpReqHeaderRaw() != null ? logData.getHttpReqHeaderRaw() : "");
|
||||
logObject.put("_source.host_reraw",
|
||||
logData.getHttpReqHeaderRaw() != null ?
|
||||
new StringBuilder(logData.getHttpReqHeaderRaw()).reverse().toString() : "");
|
||||
logObject.put("_source.method", logData.getHttpMethod() != null ? logData.getHttpMethod() : "");
|
||||
logObject.put("_source.mime_type",
|
||||
logData.getHttpRespContentType() != null ? logData.getHttpRespContentType() : "");
|
||||
logObject.put("_source.priv_info", "{\"product_type\": \"sensor\"}");
|
||||
logObject.put("_source.proto", logData.getProto() != null ? logData.getProto() : "");
|
||||
logObject.put("_source.referer", logData.getHttpReferer() != null ? logData.getHttpReferer() : "");
|
||||
logObject.put("_source.serial_num", UUID.randomUUID().toString().substring(0, 9));
|
||||
logObject.put("_source.sess_key", new Random().nextInt());
|
||||
logObject.put("_source.sip",
|
||||
logData.getSrcIp() != null ? logData.getSrcIp() : "");
|
||||
logObject.put("_source.sport", logData.getSrcPort() != null ? logData.getSrcPort() : 0);
|
||||
logObject.put("_source.src_mac", logData.getSrcMac() != null ? logData.getSrcMac() : "");
|
||||
logObject.put("_source.status",
|
||||
logData.getHttpStatusCode() != null ? String.valueOf(logData.getHttpStatusCode()) : "");
|
||||
logObject.put("_source.uri", logData.getHttpUrl() != null ? logData.getHttpUrl() : "");
|
||||
logObject.put("_source.uri_md5",
|
||||
logData.getHttpUrl() != null ?
|
||||
UUID.nameUUIDFromBytes(logData.getHttpUrl().getBytes()).toString() : "");
|
||||
logObject.put("_source.vendor_id", "");
|
||||
logObject.put("_source.vlan_id", "");
|
||||
logObject.put("_type", "skyeye-file");
|
||||
|
||||
requestArray.add(logObject);
|
||||
}
|
||||
|
||||
return requestArray;
|
||||
}
|
||||
|
||||
/**
|
||||
* 调用算法API
|
||||
*/
|
||||
private ResponseEntity<String> callAlgorithmApi(SecExceptionAlgorithm algorithm, JSONArray requestBody) {
|
||||
try {
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.setContentType(MediaType.APPLICATION_JSON);
|
||||
headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);
|
||||
|
||||
HttpEntity<String> requestEntity;
|
||||
if ("GET".equalsIgnoreCase(algorithm.getApiMethod())) {
|
||||
// 对于GET请求,将参数放在URL中
|
||||
String url = algorithm.getApiUrl() + "?data=" + requestBody.toJSONString();
|
||||
requestEntity = new HttpEntity<>(headers);
|
||||
return restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);
|
||||
} else {
|
||||
// POST请求
|
||||
requestEntity = new HttpEntity<>(requestBody.toJSONString(), headers);
|
||||
return restTemplate.exchange(algorithm.getApiUrl(), HttpMethod.POST, requestEntity, String.class);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("调用算法API异常 [URL: {}]: {}", algorithm.getApiUrl(), e.getMessage(), e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理API响应
|
||||
*/
|
||||
@Transactional
|
||||
private void processApiResponse(SecExceptionAlgorithm algorithm, String responseBody, List<SyslogNormalData> logs) {
|
||||
try {
|
||||
//JSONObject responseJson = JSON.parseObject(responseBody);
|
||||
JSONArray results = JSON.parseArray(responseBody);
|
||||
/**
|
||||
if (responseJson == null || !responseJson.containsKey("results")) {
|
||||
log.warn("算法API返回格式异常: {}", responseBody);
|
||||
return;
|
||||
}
|
||||
|
||||
JSONArray results = responseJson.getJSONArray("results");
|
||||
if (results == null || results.isEmpty()) {
|
||||
log.info("算法 {} 未检测到告警", algorithm.getAlgorithmName());
|
||||
return;
|
||||
}
|
||||
**/
|
||||
int alarmCount = 0;
|
||||
for (int i = 0; i < results.size(); i++) {
|
||||
JSONObject alarmResult = results.getJSONObject(i);
|
||||
|
||||
// 创建告警记录
|
||||
AlarmVisit alarmVisit = AlarmVisit.builder()
|
||||
.id(UUID.randomUUID().toString())
|
||||
.createdAt(LocalDateTime.now())
|
||||
.alarmName(alarmResult.getString("dname"))
|
||||
.alarmLevel("未知") // 可根据算法类型设置,默认未知
|
||||
.alarmType(algorithm.getExceptionType())
|
||||
.victimWebUrl(new String[]{alarmResult.getString("url")})
|
||||
.logStartAt(parseDateTime(alarmResult.getString("access_time")))
|
||||
.attackIp(new String[]{alarmResult.getString("sip")})
|
||||
.victimIp(new String[]{alarmResult.getString("dip")})
|
||||
.httpStatus(alarmResult.getString("status_code"))
|
||||
.comment(alarmResult.getString("reason") + " - " + alarmResult.getString("origin_field"))
|
||||
.originLogIds(new String[]{alarmResult.getString("log_id")})
|
||||
.engineType("Python算子")
|
||||
.logCount(1)
|
||||
.alarmSource(2) // 算子告警
|
||||
.attackResult(-1)
|
||||
.fall(0)
|
||||
.attackDirection("other")
|
||||
.etlTime(LocalDateTime.now())
|
||||
.isAssetHit(0)
|
||||
.focused(false)
|
||||
.baseFocused(false)
|
||||
.isUpdated(false)
|
||||
.judgedState(0)
|
||||
.disposedState(0)
|
||||
.dispositionAdvice("研判后处置")
|
||||
.build();
|
||||
|
||||
// 保存告警记录
|
||||
alarmVisitMapper.insert(alarmVisit);
|
||||
alarmCount++;
|
||||
}
|
||||
|
||||
log.info("算法 {} 生成 {} 条告警记录", algorithm.getAlgorithmName(), alarmCount);
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("处理API响应异常: {}", e.getMessage(), e);
|
||||
throw new RuntimeException("处理API响应失败", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析时间字符串
|
||||
*/
|
||||
private LocalDateTime parseDateTime(String timeStr) {
|
||||
try {
|
||||
if (timeStr == null || timeStr.isEmpty()) {
|
||||
return LocalDateTime.now();
|
||||
}
|
||||
|
||||
// 尝试多种时间格式
|
||||
try {
|
||||
return LocalDateTime.parse(timeStr);
|
||||
} catch (Exception e) {
|
||||
LocalDateTime localDateTime = LocalDateTime.parse(
|
||||
timeStr,
|
||||
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS")
|
||||
);
|
||||
return LocalDateTime.now(ZoneId.systemDefault());
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.warn("时间解析失败: {}, 使用当前时间", timeStr);
|
||||
return LocalDateTime.now();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量处理开关 - 避免重复处理
|
||||
*/
|
||||
private AtomicBoolean processing = new AtomicBoolean(false);
|
||||
|
||||
/**
|
||||
* 安全的定时任务入口
|
||||
*/
|
||||
@Scheduled(cron = "0 */2 * * * ?")
|
||||
public void safeProcessTask() {
|
||||
if (processing.compareAndSet(false, true)) {
|
||||
try {
|
||||
processAccessLogAlert();
|
||||
} finally {
|
||||
processing.set(false);
|
||||
}
|
||||
} else {
|
||||
log.warn("上一个任务仍在执行中,跳过本次执行");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package com.common.service;
|
||||
|
||||
|
||||
import com.common.entity.AppLog;
|
||||
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
//@Repository
|
||||
public interface AppLogRepository extends ElasticsearchRepository<AppLog, String> {
|
||||
|
||||
/**
|
||||
* 根据应用名称和日志级别查询
|
||||
*/
|
||||
List<AppLog> findByAppNameAndLogLevel(String appName, String logLevel);
|
||||
|
||||
/**
|
||||
* 根据时间范围查询
|
||||
*/
|
||||
List<AppLog> findByDtTimeBetween(Long startTime, Long endTime);
|
||||
|
||||
/**
|
||||
* 根据索引名称查询
|
||||
*/
|
||||
List<AppLog> findByIndex(String index);
|
||||
}
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
package com.common.service;
|
||||
|
||||
|
||||
import com.common.entity.AppLogEntity;
|
||||
import com.common.mapper.AppLogMapper;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
public class ApplogService {
|
||||
|
||||
@Autowired
|
||||
private AppLogMapper appLogMapper;
|
||||
|
||||
/**
|
||||
* 保存日志到数据库(去重)
|
||||
*/
|
||||
@Transactional
|
||||
public void saveAppLogWithDeduplication(AppLogEntity appLog) {
|
||||
// 检查是否已存在
|
||||
boolean exists = appLogMapper.existsByEsIdAndIndex(appLog.getEsId(), appLog.getEsIndex());
|
||||
|
||||
if (!exists) {
|
||||
appLog.setCreatedAt(LocalDateTime.now());
|
||||
appLog.setUpdatedAt(LocalDateTime.now());
|
||||
appLogMapper.insert(appLog);
|
||||
log.info("保存日志到数据库, ES ID: {}", appLog.getEsId());
|
||||
} else {
|
||||
log.debug("日志已存在,跳过保存, ES ID: {}", appLog.getEsId());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量保存日志到数据库(去重)
|
||||
*/
|
||||
@Transactional
|
||||
public int batchSaveAppLogsWithDeduplication(List<AppLogEntity> appLogs) {
|
||||
if (appLogs == null || appLogs.isEmpty()) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
// 过滤已存在的记录
|
||||
List<AppLogEntity> newLogs = appLogs.stream()
|
||||
.filter(log -> !appLogMapper.existsByEsIdAndIndex(log.getEsId(), log.getEsIndex()))
|
||||
.peek(log -> {
|
||||
log.setCreatedAt(LocalDateTime.now());
|
||||
log.setUpdatedAt(LocalDateTime.now());
|
||||
}).collect(Collectors.toList());
|
||||
|
||||
|
||||
if (!newLogs.isEmpty()) {
|
||||
appLogMapper.batchInsert(newLogs);
|
||||
log.info("批量保存 {} 条日志到数据库,跳过 {} 条重复数据",
|
||||
newLogs.size(), appLogs.size() - newLogs.size());
|
||||
} else {
|
||||
log.info("所有 {} 条日志均已存在,跳过保存", appLogs.size());
|
||||
}
|
||||
|
||||
return newLogs.size();
|
||||
}
|
||||
}
|
||||
+210
@@ -0,0 +1,210 @@
|
||||
package com.common.service;
|
||||
|
||||
|
||||
|
||||
import com.common.entity.AlarmVisit;
|
||||
import com.common.entity.GroupedSyslogData;
|
||||
import com.common.mapper.SyslogNormalDataMapper;
|
||||
import com.common.mapper.SyslogNormalAlarmMapper;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.catalina.mapper.Mapper;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
import com.common.entity.Alarm;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.time.format.DateTimeParseException;
|
||||
@Slf4j
|
||||
@Component
|
||||
public class DataExtractor {
|
||||
|
||||
@Autowired
|
||||
private SyslogNormalDataMapper syslogNormalDataMapper;
|
||||
@Autowired
|
||||
private SyslogNormalAlarmMapper syslogNormalAlarmMapper;
|
||||
@Autowired
|
||||
private DataTransformer dataTransformer;
|
||||
|
||||
@Autowired
|
||||
private DataLoader dataLoader;
|
||||
|
||||
@Value("${etl.batch.page-size:1000}")
|
||||
private int pageSize;
|
||||
|
||||
|
||||
/**
|
||||
* 抽取并处理指定时间范围内的分组访问日志数据
|
||||
*/
|
||||
public void extractAndProcessQueryHoursGroupedData( String strStartTime ,String strEndTime ) {
|
||||
|
||||
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
|
||||
|
||||
LocalDateTime endTime = LocalDateTime.parse(strEndTime, formatter);
|
||||
LocalDateTime startTime = LocalDateTime.parse(strStartTime, formatter);
|
||||
|
||||
log.info("开始处理指定时间范围内访问日志数据,时间范围: {} - {}", startTime, endTime);
|
||||
|
||||
try {
|
||||
// 获取分组数据总量
|
||||
Long totalGroups = syslogNormalDataMapper.count24HoursGroupedData(startTime, endTime);
|
||||
log.info("指定时间范围分组数据量: {} 组", totalGroups);
|
||||
|
||||
if (totalGroups == 0) {
|
||||
log.info("没有需要处理的数据");
|
||||
return;
|
||||
}
|
||||
|
||||
int totalPages = (int) Math.ceil((double) totalGroups / pageSize);
|
||||
long totalProcessed = 0;
|
||||
|
||||
for (int page = 1; page <= totalPages; page++) {
|
||||
int offset = (page - 1) * pageSize;
|
||||
syslogNormalDataMapper.select24HoursGroupedDataByPage(
|
||||
startTime, endTime, offset, pageSize);
|
||||
// 分页查询分组数据
|
||||
List<GroupedSyslogData> groupedDataList =
|
||||
syslogNormalDataMapper.select24HoursGroupedDataByPage(
|
||||
startTime, endTime, offset, pageSize);
|
||||
|
||||
if (!groupedDataList.isEmpty()) {
|
||||
// 转换并加载数据
|
||||
List<AlarmVisit> alarmList = dataTransformer.transformGroupedDataVisit(groupedDataList);
|
||||
//dataLoader.batchInsertAlarms(alarmList);
|
||||
dataLoader.batchInsertAlarmVisits(alarmList);
|
||||
totalProcessed += groupedDataList.size();
|
||||
double progress = (double) totalProcessed / totalGroups * 100;
|
||||
log.info("分组数据处理进度: {}/{} ({}%)",
|
||||
totalProcessed, totalGroups, String.format("%.2f", progress));
|
||||
}
|
||||
|
||||
// 内存管理
|
||||
if (page % 50 == 0) {
|
||||
System.gc();
|
||||
log.debug("执行GC清理内存");
|
||||
}
|
||||
}
|
||||
|
||||
log.info("分组数据处理完成,共处理 {} 组数据", totalProcessed);
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("访问日志数据抽取处理失败", e);
|
||||
throw new RuntimeException("ETL处理失败", e);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 抽取并处理指定时间范围内的分组告警类型数据
|
||||
*/
|
||||
public void extractAndProcessQueryHoursAlarm( String strStartTime ,String strEndTime ) {
|
||||
|
||||
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
|
||||
LocalDateTime endTime = LocalDateTime.parse(strEndTime, formatter);
|
||||
LocalDateTime startTime = LocalDateTime.parse(strStartTime, formatter);
|
||||
|
||||
log.info("开始处理告警类型指定时间范围内数据,时间范围: {} - {}", startTime, endTime);
|
||||
|
||||
try {
|
||||
// 获取分组数据总量
|
||||
Long totalGroups = syslogNormalAlarmMapper.count24HoursGroupedData(startTime, endTime);
|
||||
log.info("指定时间范围分组数据量: {} 组", totalGroups);
|
||||
if (totalGroups == 0) {
|
||||
log.info("没有需要处理的数据");
|
||||
return;
|
||||
}
|
||||
|
||||
int totalPages = (int) Math.ceil((double) totalGroups / pageSize);
|
||||
long totalProcessed = 0;
|
||||
|
||||
for (int page = 1; page <= totalPages; page++) {
|
||||
int offset = (page - 1) * pageSize;
|
||||
syslogNormalAlarmMapper.select24HoursGroupedDataByPage(
|
||||
startTime, endTime, offset, pageSize);
|
||||
// 分页查询分组数据
|
||||
List<GroupedSyslogData> groupedDataList =
|
||||
syslogNormalAlarmMapper.select24HoursGroupedDataByPage(
|
||||
startTime, endTime, offset, pageSize);
|
||||
|
||||
if (!groupedDataList.isEmpty()) {
|
||||
// 转换并加载数据
|
||||
List<Alarm> alarmList = dataTransformer.transformGroupedData(groupedDataList);
|
||||
dataLoader.batchInsertAlarms(alarmList);
|
||||
|
||||
totalProcessed += groupedDataList.size();
|
||||
double progress = (double) totalProcessed / totalGroups * 100;
|
||||
log.info("分组数据处理进度: {}/{} ({}%)",
|
||||
totalProcessed, totalGroups, String.format("%.2f", progress));
|
||||
}
|
||||
|
||||
// 内存管理
|
||||
if (page % 50 == 0) {
|
||||
System.gc();
|
||||
log.debug("执行GC清理内存");
|
||||
}
|
||||
}
|
||||
|
||||
log.info("分组数据处理完成,共处理 {} 组数据", totalProcessed);
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("告警日志数据抽取处理失败", e);
|
||||
throw new RuntimeException("ETL处理失败", e);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 抽取并处理24小时内分组数据
|
||||
*/
|
||||
public void extractAndProcess24HoursGroupedData() {
|
||||
|
||||
LocalDateTime endTime = LocalDateTime.now();
|
||||
LocalDateTime startTime = endTime.minusHours(24);
|
||||
|
||||
log.info("开始处理24小时内数据,时间范围: {} - {}", startTime, endTime);
|
||||
|
||||
try {
|
||||
// 获取分组数据总量
|
||||
Long totalGroups = syslogNormalDataMapper.count24HoursGroupedData(startTime, endTime);
|
||||
log.info("24小时内分组数据量: {} 组", totalGroups);
|
||||
|
||||
if (totalGroups == 0) {
|
||||
log.info("没有需要处理的数据");
|
||||
return;
|
||||
}
|
||||
|
||||
int totalPages = (int) Math.ceil((double) totalGroups / pageSize);
|
||||
long totalProcessed = 0;
|
||||
|
||||
for (int page = 1; page <= totalPages; page++) {
|
||||
int offset = (page - 1) * pageSize;
|
||||
|
||||
// 分页查询分组数据
|
||||
List<GroupedSyslogData> groupedDataList =
|
||||
syslogNormalDataMapper.select24HoursGroupedDataByPage(
|
||||
startTime, endTime, offset, pageSize);
|
||||
|
||||
if (!groupedDataList.isEmpty()) {
|
||||
// 转换并加载数据
|
||||
List<Alarm> alarmList = dataTransformer.transformGroupedData(groupedDataList);
|
||||
dataLoader.batchInsertAlarms(alarmList);
|
||||
|
||||
totalProcessed += groupedDataList.size();
|
||||
double progress = (double) totalProcessed / totalGroups * 100;
|
||||
log.info("分组数据处理进度: {}/{} ({:.2f}%)",
|
||||
totalProcessed, totalGroups, progress);
|
||||
}
|
||||
|
||||
// 内存管理
|
||||
if (page % 50 == 0) {
|
||||
System.gc();
|
||||
log.debug("执行GC清理内存");
|
||||
}
|
||||
}
|
||||
|
||||
log.info("分组数据处理完成,共处理 {} 组数据", totalProcessed);
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("数据抽取处理失败", e);
|
||||
throw new RuntimeException("ETL处理失败", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
package com.common.service;
|
||||
|
||||
|
||||
|
||||
import com.common.entity.Alarm;
|
||||
import com.common.entity.AlarmVisit;
|
||||
import com.common.mapper.AlarmMapper;
|
||||
import com.common.mapper.AlarmVisitMapper;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.transaction.annotation.Propagation;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
public class DataLoader {
|
||||
|
||||
@Autowired
|
||||
private AlarmMapper alarmMapper;
|
||||
@Autowired
|
||||
private AlarmVisitMapper alarmVisitMapper;
|
||||
/**
|
||||
* 批量入库告警数据
|
||||
*/
|
||||
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
|
||||
public void batchInsertAlarms(List<Alarm> alarmList) {
|
||||
if (alarmList == null || alarmList.isEmpty()) {
|
||||
log.info("没有需要入库的告警类型数据");
|
||||
return;
|
||||
}
|
||||
|
||||
int batchSize = 500; // 每批500条
|
||||
List<List<Alarm>> batches = partitionList(alarmList, batchSize);
|
||||
int totalSuccess = 0;
|
||||
|
||||
for (int i = 0; i < batches.size(); i++) {
|
||||
List<Alarm> batch = batches.get(i);
|
||||
try {
|
||||
alarmMapper.batchInsert(batch);
|
||||
totalSuccess += batch.size();
|
||||
log.debug("第 {} 批数据入库成功,本批 {} 条", i + 1, batch.size());
|
||||
} catch (Exception e) {
|
||||
log.error("第 {} 批数据批量入库失败,尝试单条插入", i + 1, e);
|
||||
int singleSuccess = insertOneByOne(batch);
|
||||
totalSuccess += singleSuccess;
|
||||
}
|
||||
}
|
||||
|
||||
log.info("告警数据入库完成,成功: {} 条,总数: {} 条", totalSuccess, alarmList.size());
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 批量入库访问日志告警数据
|
||||
*/
|
||||
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
|
||||
public void batchInsertAlarmVisits(List<AlarmVisit> alarmList) {
|
||||
if (alarmList == null || alarmList.isEmpty()) {
|
||||
log.info("没有需要入库的访问日志数据");
|
||||
return;
|
||||
}
|
||||
|
||||
int batchSize = 500; // 每批500条
|
||||
List<List<AlarmVisit>> batches = partitionList(alarmList, batchSize);
|
||||
int totalSuccess = 0;
|
||||
|
||||
for (int i = 0; i < batches.size(); i++) {
|
||||
List<AlarmVisit> batch = batches.get(i);
|
||||
try {
|
||||
alarmVisitMapper.batchInsert(batch);
|
||||
totalSuccess += batch.size();
|
||||
log.debug("第 {} 批数据入库成功,本批 {} 条", i + 1, batch.size());
|
||||
} catch (Exception e) {
|
||||
log.error("第 {} 批数据批量入库失败,尝试单条插入", i + 1, e);
|
||||
int singleSuccess = insertVisitOneByOne(batch);
|
||||
totalSuccess += singleSuccess;
|
||||
}
|
||||
}
|
||||
|
||||
log.info("访问日志告警数据入库完成,成功: {} 条,总数: {} 条", totalSuccess, alarmList.size());
|
||||
}
|
||||
|
||||
|
||||
private int insertOneByOne(List<Alarm> alarmList) {
|
||||
int successCount = 0;
|
||||
for (Alarm alarm : alarmList) {
|
||||
try {
|
||||
alarmMapper.insert(alarm);
|
||||
successCount++;
|
||||
} catch (Exception e) {
|
||||
log.error("单条插入告警失败: {}", alarm.getId(), e);
|
||||
}
|
||||
}
|
||||
return successCount;
|
||||
}
|
||||
|
||||
private int insertVisitOneByOne(List<AlarmVisit> alarmList) {
|
||||
int successCount = 0;
|
||||
for (AlarmVisit alarm : alarmList) {
|
||||
try {
|
||||
alarmVisitMapper.insert(alarm);
|
||||
successCount++;
|
||||
} catch (Exception e) {
|
||||
log.error("单条插入告警失败: {}", alarm.getId(), e);
|
||||
}
|
||||
}
|
||||
return successCount;
|
||||
}
|
||||
private <T> List<List<T>> partitionList(List<T> list, int size) {
|
||||
return IntStream.range(0, (list.size() + size - 1) / size)
|
||||
.mapToObj(i -> list.subList(i * size, Math.min((i + 1) * size, list.size())))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
}
|
||||
+299
@@ -0,0 +1,299 @@
|
||||
package com.common.service;
|
||||
|
||||
|
||||
|
||||
import com.common.entity.Alarm;
|
||||
import com.common.entity.AlarmVisit;
|
||||
import com.common.entity.GroupedSyslogData;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
public class DataTransformer {
|
||||
|
||||
/**
|
||||
* 转换分组数据为告警记录
|
||||
*/
|
||||
public List<Alarm> transformGroupedData(List<GroupedSyslogData> groupedDataList) {
|
||||
List<Alarm> alarmList = new ArrayList<>(groupedDataList.size());
|
||||
|
||||
for (GroupedSyslogData groupedData : groupedDataList) {
|
||||
Alarm alarm = transformSingleGroupedData(groupedData);
|
||||
if (alarm != null) {
|
||||
alarmList.add(alarm);
|
||||
}
|
||||
}
|
||||
|
||||
return alarmList;
|
||||
}
|
||||
|
||||
/**
|
||||
* 转换分组数据为告警记录
|
||||
*/
|
||||
public List<AlarmVisit> transformGroupedDataVisit(List<GroupedSyslogData> groupedDataList) {
|
||||
List<AlarmVisit> alarmList = new ArrayList<>(groupedDataList.size());
|
||||
|
||||
for (GroupedSyslogData groupedData : groupedDataList) {
|
||||
AlarmVisit alarm = transformSingleGroupedDataVisit(groupedData);
|
||||
if (alarm != null) {
|
||||
alarmList.add(alarm);
|
||||
}
|
||||
}
|
||||
|
||||
return alarmList;
|
||||
}
|
||||
|
||||
private Alarm transformSingleGroupedData(GroupedSyslogData groupedData) {
|
||||
try {
|
||||
return Alarm.builder()
|
||||
.id(UUID.randomUUID().toString())
|
||||
.createdAt(LocalDateTime.now())
|
||||
.alarmName( groupedData.getOriginEventName())
|
||||
.alarmLevel(convertAlarmLevel(groupedData.getMaxEventLevel()))
|
||||
.alarmType(getAlarmType(groupedData.getFirstEventType(),groupedData.getEventType()))
|
||||
.alarmMajorType(groupedData.getEventType())
|
||||
.alarmMinorType(groupedData.getMinEventType())
|
||||
.alarmAreaId(0)
|
||||
.attackIp(groupedData.getAttackIps())
|
||||
.victimIp(groupedData.getVictimIps())
|
||||
.victimWebUrl(null)
|
||||
.attackChainPhase(new Integer[]{-1})
|
||||
.deviceId(groupedData.getDeviceIds())
|
||||
.tag(null)
|
||||
.comment(buildComment(groupedData))
|
||||
.originLogIds(groupedData.getOriginLogIds())
|
||||
.queryId(null)
|
||||
.judgedState(0)
|
||||
.disposedState(0)
|
||||
.dispositionAdvice("研判后处置")
|
||||
.attackResult(determineAttackResult(groupedData))
|
||||
.fall(0)
|
||||
.payload(extractPayloadSample(groupedData.getPayloadSamples()))
|
||||
.operateEvent(null)
|
||||
.attackPort(groupedData.getAttackPorts())
|
||||
.victimPort(groupedData.getVictimPorts())
|
||||
.attackMethod(groupedData.getOriginEventName())
|
||||
.businessExt(null)
|
||||
.logStartAt(groupedData.getMinLogTime())
|
||||
.logEndAt(groupedData.getMaxLogTime())
|
||||
.httpStatus(convertHttpStatus(groupedData.getHttpStatusCodes()))
|
||||
.dnsInfo(null)
|
||||
.accountInfo(null)
|
||||
.attackerInfo(null)
|
||||
.victimInfo(null)
|
||||
.suspiciousAction(null)
|
||||
.vulnInfo(null)
|
||||
.weakPwd(null)
|
||||
.complianceBaseline(null)
|
||||
.fileInfo(null)
|
||||
.fileTags(null)
|
||||
.endpointInfo(null)
|
||||
.endpointProtection(null)
|
||||
.originInfo(null)
|
||||
.protocolInfo(null)
|
||||
.emailInfo(null)
|
||||
.sensitiveData(null)
|
||||
.hitIntelligence(0)
|
||||
.windowTime(null)
|
||||
.updatedAt(LocalDateTime.now())
|
||||
.engineType(null)
|
||||
.attackIpPic(null)
|
||||
.victimIpPic(null)
|
||||
.operationAt(null)
|
||||
.attackDirection("other")
|
||||
.etlTime(LocalDateTime.now())
|
||||
.logCount(groupedData.getLogCount().intValue())
|
||||
.isAssetHit(0)
|
||||
.focused(false)
|
||||
.baseFocused(false)
|
||||
.isUpdated(false)
|
||||
.httpReqHeaders(groupedData.getHttpReqHeaders())
|
||||
.httpReqBodys(groupedData.getHttpReqBodys())
|
||||
.httpRespHeaders(groupedData.getHttpRespHeaders())
|
||||
.httpRespBodys(groupedData.getHttpRespBodys())
|
||||
.build();
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("转换分组数据失败: {}", groupedData, e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private AlarmVisit transformSingleGroupedDataVisit(GroupedSyslogData groupedData) {
|
||||
try {
|
||||
return AlarmVisit.builder()
|
||||
.id(UUID.randomUUID().toString())
|
||||
.createdAt(LocalDateTime.now())
|
||||
.alarmName( groupedData.getOriginEventName())
|
||||
.alarmLevel(convertAlarmLevel(groupedData.getMaxEventLevel()))
|
||||
.alarmType(getAlarmType(groupedData.getFirstEventType(),groupedData.getEventType()))
|
||||
.alarmMajorType(groupedData.getEventType())
|
||||
.alarmMinorType(groupedData.getMinEventType())
|
||||
.alarmAreaId(0)
|
||||
.attackIp(groupedData.getAttackIps())
|
||||
.victimIp(groupedData.getVictimIps())
|
||||
.victimWebUrl(null)
|
||||
.attackChainPhase(new Integer[]{-1})
|
||||
.deviceId(groupedData.getDeviceIds())
|
||||
.tag(null)
|
||||
.comment(buildComment(groupedData))
|
||||
.originLogIds(groupedData.getOriginLogIds())
|
||||
.queryId(null)
|
||||
.judgedState(0)
|
||||
.disposedState(0)
|
||||
.dispositionAdvice("研判后处置")
|
||||
.attackResult(determineAttackResult(groupedData))
|
||||
.fall(0)
|
||||
.payload(extractPayloadSample(groupedData.getPayloadSamples()))
|
||||
.operateEvent(null)
|
||||
.attackPort(groupedData.getAttackPorts())
|
||||
.victimPort(groupedData.getVictimPorts())
|
||||
.attackMethod(groupedData.getOriginEventName())
|
||||
.businessExt(null)
|
||||
.logStartAt(groupedData.getMinLogTime())
|
||||
.logEndAt(groupedData.getMaxLogTime())
|
||||
.httpStatus(convertHttpStatus(groupedData.getHttpStatusCodes()))
|
||||
.dnsInfo(null)
|
||||
.accountInfo(null)
|
||||
.attackerInfo(null)
|
||||
.victimInfo(null)
|
||||
.suspiciousAction(null)
|
||||
.vulnInfo(null)
|
||||
.weakPwd(null)
|
||||
.complianceBaseline(null)
|
||||
.fileInfo(null)
|
||||
.fileTags(null)
|
||||
.endpointInfo(null)
|
||||
.endpointProtection(null)
|
||||
.originInfo(null)
|
||||
.protocolInfo(null)
|
||||
.emailInfo(null)
|
||||
.sensitiveData(null)
|
||||
.hitIntelligence(0)
|
||||
.windowTime(null)
|
||||
.updatedAt(LocalDateTime.now())
|
||||
.engineType(null)
|
||||
.attackIpPic(null)
|
||||
.victimIpPic(null)
|
||||
.operationAt(null)
|
||||
.attackDirection("other")
|
||||
.etlTime(LocalDateTime.now())
|
||||
.logCount(groupedData.getLogCount().intValue())
|
||||
.isAssetHit(0)
|
||||
.focused(false)
|
||||
.baseFocused(false)
|
||||
.isUpdated(false)
|
||||
.httpReqHeaders(groupedData.getHttpReqHeaders())
|
||||
.httpReqBodys(groupedData.getHttpReqBodys())
|
||||
.httpRespHeaders(groupedData.getHttpRespHeaders())
|
||||
.httpRespBodys(groupedData.getHttpRespBodys())
|
||||
.build();
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("转换分组数据失败: {}", groupedData, e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private String getAlarmType(String firstEventType,String eventType) {
|
||||
if (firstEventType.equals(""))
|
||||
return firstEventType;
|
||||
else
|
||||
return eventType;
|
||||
}
|
||||
/**
|
||||
* 确定attack_result的值
|
||||
*/
|
||||
private Integer determineAttackResult(GroupedSyslogData groupedData) {
|
||||
// 优先使用单个attack_result值
|
||||
if (groupedData.getAttackResult() != null) {
|
||||
return groupedData.getAttackResult();
|
||||
}
|
||||
|
||||
// 如果没有单个值,使用最常见的值
|
||||
if (groupedData.getMostCommonAttackResult() != null) {
|
||||
return groupedData.getMostCommonAttackResult();
|
||||
}
|
||||
|
||||
// 如果有多值,取第一个非空值
|
||||
if (groupedData.getAllAttackResults() != null && groupedData.getAllAttackResults().length > 0) {
|
||||
for (Integer result : groupedData.getAllAttackResults()) {
|
||||
if (result != null) {
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 默认值
|
||||
return -1;
|
||||
}
|
||||
|
||||
/**
|
||||
* 提取payload样本
|
||||
*/
|
||||
private byte[] extractPayloadSample(byte[][] payloadSamples) {
|
||||
if (payloadSamples == null || payloadSamples.length == 0) {
|
||||
return null;
|
||||
}
|
||||
// 返回第一个样本
|
||||
return payloadSamples[0];
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建comment字段
|
||||
*/
|
||||
private String buildComment(GroupedSyslogData groupedData) {
|
||||
String victimIpsStr;
|
||||
if (StringUtils.isNotBlank(groupedData.getVictimIpsStr())) {
|
||||
victimIpsStr = groupedData.getVictimIpsStr();
|
||||
} else if (groupedData.getVictimIps() != null && groupedData.getVictimIps().length > 0) {
|
||||
victimIpsStr = String.join(",", groupedData.getVictimIps());
|
||||
} else {
|
||||
victimIpsStr = "未知";
|
||||
}
|
||||
|
||||
return String.format(
|
||||
"24小时内,检测到%s上产生%s告警:\n告警名称:%s\n攻击IP:%s\n攻击结果:%d",
|
||||
victimIpsStr,
|
||||
convertAlarmLevel(groupedData.getMaxEventLevel()),
|
||||
groupedData.getOriginEventName(),
|
||||
convertAttackIps(groupedData.getAttackIps()),
|
||||
determineAttackResult(groupedData)
|
||||
);
|
||||
}
|
||||
|
||||
private String convertAlarmLevel(Integer eventLevel) {
|
||||
if (eventLevel == null) return "未知";
|
||||
switch (eventLevel) {
|
||||
case 0: return "安全(无威胁)";
|
||||
case 1: return "低危";
|
||||
case 2: return "中危";
|
||||
case 3: return "高危";
|
||||
case 4: return "超危";
|
||||
default: return "未知";
|
||||
}
|
||||
}
|
||||
|
||||
private String convertHttpStatus(String[] httpStatusCodes) {
|
||||
if (httpStatusCodes == null || httpStatusCodes.length == 0) {
|
||||
return null;
|
||||
}
|
||||
return String.join(",", httpStatusCodes);
|
||||
}
|
||||
|
||||
private String convertAttackIps(String[] attackIps) {
|
||||
if (attackIps == null || attackIps.length == 0) {
|
||||
return null;
|
||||
}
|
||||
return String.join(",", attackIps);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
+136
@@ -0,0 +1,136 @@
|
||||
package com.common.service;
|
||||
|
||||
import com.common.entity.DeviceCollectTask;
|
||||
import com.common.mapper.DeviceCollectTaskMapper;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.cache.annotation.CacheConfig;
|
||||
import org.springframework.cache.annotation.CacheEvict;
|
||||
import org.springframework.cache.annotation.Cacheable;
|
||||
import org.springframework.cache.annotation.CachePut;
|
||||
import org.springframework.stereotype.Service;
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
@CacheConfig(cacheNames = "collectTask")
|
||||
public class DeviceCollectTaskService {
|
||||
|
||||
@Autowired
|
||||
private DeviceCollectTaskMapper deviceCollectTaskMapper;
|
||||
|
||||
/**
|
||||
* 根据ID查询采集任务 - 缓存
|
||||
*/
|
||||
@Cacheable(key = "'id:' + #id")
|
||||
public DeviceCollectTask getById(Integer id) {
|
||||
return deviceCollectTaskMapper.selectById(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询所有采集任务 - 缓存
|
||||
*/
|
||||
@Cacheable(key = "'all'")
|
||||
public List<DeviceCollectTask> getAll() {
|
||||
return deviceCollectTaskMapper.selectAll();
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据设备ID查询采集任务 - 缓存
|
||||
*/
|
||||
@Cacheable(key = "'device:' + #deviceId")
|
||||
public List<DeviceCollectTask> getByDeviceId(Integer deviceId) {
|
||||
return deviceCollectTaskMapper.selectByDeviceId(deviceId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据方法类型查询采集任务
|
||||
*/
|
||||
public List<DeviceCollectTask> getByMethod(Integer method) {
|
||||
return deviceCollectTaskMapper.selectByMethod(method);
|
||||
}
|
||||
|
||||
/**
|
||||
* 多条件组合查询
|
||||
*/
|
||||
public List<DeviceCollectTask> getByCondition(DeviceCollectTask condition) {
|
||||
return deviceCollectTaskMapper.selectByCondition(condition);
|
||||
}
|
||||
|
||||
/**
|
||||
* 新增采集任务 - 清除相关缓存
|
||||
*/
|
||||
@CacheEvict(allEntries = true)
|
||||
public int create(DeviceCollectTask task) {
|
||||
return deviceCollectTaskMapper.insert(task);
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新采集任务 - 更新缓存
|
||||
*/
|
||||
@CachePut(key = "'id:' + #task.id")
|
||||
@CacheEvict(key = "'device:' + #task.deviceId")
|
||||
public DeviceCollectTask update(DeviceCollectTask task) {
|
||||
deviceCollectTaskMapper.update(task);
|
||||
return deviceCollectTaskMapper.selectById(task.getId());
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除采集任务 - 清除缓存
|
||||
*/
|
||||
@CacheEvict(key = "'id:' + #id")
|
||||
public int delete(Integer id) {
|
||||
return deviceCollectTaskMapper.deleteById(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* 标记任务成功 - 更新缓存
|
||||
*/
|
||||
@CacheEvict(key = "'id:' + #id")
|
||||
public int markSuccess(Integer id) {
|
||||
return deviceCollectTaskMapper.updateSuccessStatus(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* 标记任务失败 - 更新缓存
|
||||
*/
|
||||
@CacheEvict(key = "'id:' + #id")
|
||||
public int markFailed(Integer id) {
|
||||
return deviceCollectTaskMapper.updateFailedStatus(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新EPM指标 - 更新缓存
|
||||
*/
|
||||
@CacheEvict(key = "'id:' + #id")
|
||||
public int updateEpm(Integer id, Integer epm) {
|
||||
return deviceCollectTaskMapper.updateEpm(id, epm);
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询成功的任务
|
||||
*/
|
||||
public List<DeviceCollectTask> getSuccessTasks() {
|
||||
return deviceCollectTaskMapper.selectSuccessTasks();
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询失败的任务
|
||||
*/
|
||||
public List<DeviceCollectTask> getFailedTasks() {
|
||||
return deviceCollectTaskMapper.selectFailedTasks();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取设备的最新采集任务
|
||||
*/
|
||||
@Cacheable(key = "'latest:device:' + #deviceId")
|
||||
public DeviceCollectTask getLatestByDeviceId(Integer deviceId) {
|
||||
return deviceCollectTaskMapper.selectLatestByDeviceId(deviceId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 统计设备任务数量
|
||||
*/
|
||||
public int countByDeviceId(Integer deviceId) {
|
||||
return deviceCollectTaskMapper.countByDeviceId(deviceId);
|
||||
}
|
||||
}
|
||||
+251
@@ -0,0 +1,251 @@
|
||||
package com.common.service;
|
||||
|
||||
|
||||
import com.common.entity.*;
|
||||
import com.common.mapper.DeviceCollectTaskMapper;
|
||||
import com.common.mapper.DeviceReceiveLogMapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
import java.time.ZoneOffset;
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class DeviceCollectTaskUpdateService {
|
||||
|
||||
private final DeviceReceiveLogMapper deviceReceiveLogMapper;
|
||||
private final DeviceCollectTaskMapper deviceCollectTaskMapper;
|
||||
|
||||
/**
|
||||
* 主处理方法:更新所有设备任务的时间信息
|
||||
*/
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void updateAllDeviceTaskTimes() {
|
||||
log.info("开始更新设备采集任务时间,当前时间: {}", LocalDateTime.now());
|
||||
|
||||
// 1. 查询所有设备任务
|
||||
List<DeviceCollectTask> allTasks = deviceCollectTaskMapper.selectAllTasks();
|
||||
if (CollectionUtils.isEmpty(allTasks)) {
|
||||
log.info("没有找到设备采集任务");
|
||||
return;
|
||||
}
|
||||
|
||||
// 2. 查询设备接收日志的时间信息
|
||||
Map<String, DeviceCollectTaskTime> successTimes = getDeviceSuccessTimes();
|
||||
Map<String, DeviceCollectTaskTime> failTimes = getDeviceFailTimes();
|
||||
|
||||
// 3. 更新任务时间
|
||||
LocalDateTime updateTime = LocalDateTime.now();
|
||||
int updatedCount = 0;
|
||||
|
||||
for (DeviceCollectTask task : allTasks) {
|
||||
String deviceCollectId = task.getId().toString();
|
||||
|
||||
// 获取成功时间
|
||||
DeviceCollectTaskTime successTime = successTimes.get(deviceCollectId);
|
||||
DeviceCollectTaskTime failTime = failTimes.get(deviceCollectId);
|
||||
|
||||
// 准备更新时间
|
||||
LocalDateTime firstTime = task.getFirstTime().toLocalDateTime();
|
||||
LocalDateTime lastSuccessTime = null;
|
||||
LocalDateTime lastFailTime = null;
|
||||
|
||||
// 设置最后成功时间
|
||||
if (successTime != null && successTime.getLastSuccessTime() != null) {
|
||||
lastSuccessTime = successTime.getLastSuccessTime();
|
||||
|
||||
// 如果first_time为空,且这是首次成功,则设置first_time
|
||||
if (firstTime == null && successTime.getFirstTime() != null) {
|
||||
firstTime = successTime.getFirstTime();
|
||||
}
|
||||
}
|
||||
|
||||
// 设置最后失败时间
|
||||
if (failTime != null && failTime.getLastFailTime() != null) {
|
||||
lastFailTime = failTime.getLastFailTime();
|
||||
}
|
||||
|
||||
// 如果有更新,则执行更新
|
||||
if (lastSuccessTime != null || lastFailTime != null) {
|
||||
int result = deviceCollectTaskMapper.updateTaskTime(
|
||||
deviceCollectId,
|
||||
firstTime,
|
||||
lastSuccessTime,
|
||||
lastFailTime,
|
||||
updateTime
|
||||
);
|
||||
|
||||
if (result > 0) {
|
||||
updatedCount++;
|
||||
log.debug("更新设备任务时间成功,设备ID: {}, 首次时间: {}, 最后成功: {}, 最后失败: {}",
|
||||
deviceCollectId, firstTime, lastSuccessTime, lastFailTime);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
log.info("设备采集任务时间更新完成,总计: {},已更新: {}", allTasks.size(), updatedCount);
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量更新版本(性能更好)
|
||||
*/
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void batchUpdateDeviceTaskTimes() {
|
||||
log.info("开始批量更新设备采集任务时间,当前时间: {}", LocalDateTime.now());
|
||||
|
||||
// 1. 查询所有设备任务
|
||||
List<DeviceCollectTask> allTasks = deviceCollectTaskMapper.selectAllTasks();
|
||||
if (CollectionUtils.isEmpty(allTasks)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 2. 查询时间信息
|
||||
Map<String, DeviceCollectTaskTime> successTimes = getDeviceSuccessTimes();
|
||||
Map<String, DeviceCollectTaskTime> failTimes = getDeviceFailTimes();
|
||||
|
||||
// 3. 批量更新
|
||||
LocalDateTime updateTime = LocalDateTime.now();
|
||||
|
||||
for (DeviceCollectTask task : allTasks) {
|
||||
String deviceCollectId = task.getId().toString();
|
||||
|
||||
// 获取成功和失败时间
|
||||
DeviceCollectTaskTime successTime = successTimes.get(deviceCollectId);
|
||||
DeviceCollectTaskTime failTime = failTimes.get(deviceCollectId);
|
||||
|
||||
// 更新成功时间
|
||||
if (successTime != null) {
|
||||
// 如果first_time为空,则设置首次成功时间
|
||||
if (task.getFirstTime() == null && successTime.getFirstTime() != null) {
|
||||
task.setFirstTime(successTime.getFirstTime().atOffset(ZoneOffset.UTC));
|
||||
}
|
||||
|
||||
// 设置最后成功时间
|
||||
if (successTime.getLastSuccessTime() != null) {
|
||||
task.setLastSuccessTime(successTime.getLastSuccessTime().atOffset(ZoneOffset.UTC));
|
||||
}
|
||||
}
|
||||
|
||||
// 更新失败时间
|
||||
if (failTime != null && failTime.getLastFailTime() != null) {
|
||||
task.setLastFailedTime(failTime.getLastFailTime().atOffset(ZoneOffset.UTC));
|
||||
}
|
||||
|
||||
task.setUpdatedAt(updateTime.atOffset(ZoneOffset.UTC));
|
||||
}
|
||||
|
||||
// 4. 批量更新到数据库
|
||||
int updatedCount = deviceCollectTaskMapper.batchUpdateTimes(allTasks);
|
||||
log.info("批量更新完成,总计: {},已更新: {}", allTasks.size(), updatedCount);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取设备的成功时间信息
|
||||
*/
|
||||
private Map<String, DeviceCollectTaskTime> getDeviceSuccessTimes() {
|
||||
// 查询当天的最新成功时间
|
||||
List<DeviceCollectTaskTime> dailySuccess = deviceReceiveLogMapper.selectDailySuccessTimes();
|
||||
|
||||
// 查询首次成功时间(历史)
|
||||
List<DeviceCollectTaskTime> firstSuccess = deviceReceiveLogMapper.selectFirstSuccessTimes();
|
||||
|
||||
// 合并结果
|
||||
Map<String, DeviceCollectTaskTime> result = new HashMap<>();
|
||||
|
||||
// 处理首次成功时间
|
||||
for (DeviceCollectTaskTime first : firstSuccess) {
|
||||
DeviceCollectTaskTime time = new DeviceCollectTaskTime();
|
||||
time.setDeviceCollectId(first.getDeviceCollectId());
|
||||
time.setFirstTime(first.getFirstTime());
|
||||
result.put(first.getDeviceCollectId(), time);
|
||||
}
|
||||
|
||||
// 处理当天成功时间
|
||||
for (DeviceCollectTaskTime daily : dailySuccess) {
|
||||
String deviceId = daily.getDeviceCollectId();
|
||||
DeviceCollectTaskTime time = result.getOrDefault(deviceId, new DeviceCollectTaskTime());
|
||||
time.setDeviceCollectId(deviceId);
|
||||
time.setLastSuccessTime(daily.getLastSuccessTime());
|
||||
result.put(deviceId, time);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取设备的失败时间信息
|
||||
*/
|
||||
private Map<String, DeviceCollectTaskTime> getDeviceFailTimes() {
|
||||
List<DeviceCollectTaskTime> failTimes = deviceReceiveLogMapper.selectDailyFailTimes();
|
||||
return failTimes.stream()
|
||||
.collect(Collectors.toMap(
|
||||
DeviceCollectTaskTime::getDeviceCollectId,
|
||||
ft -> ft,
|
||||
(existing, replacement) -> {
|
||||
// 如果存在重复,取更晚的时间
|
||||
if (existing.getLastFailTime() != null &&
|
||||
replacement.getLastFailTime() != null &&
|
||||
replacement.getLastFailTime().isAfter(existing.getLastFailTime())) {
|
||||
return replacement;
|
||||
}
|
||||
return existing;
|
||||
}
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* 增量更新:只处理最近一段时间的数据
|
||||
*/
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void incrementalUpdate(int hours) {
|
||||
LocalDateTime endTime = LocalDateTime.now();
|
||||
LocalDateTime startTime = endTime.minusHours(hours);
|
||||
|
||||
log.info("开始增量更新设备采集任务时间,时间范围: {} 到 {}", startTime, endTime);
|
||||
|
||||
// 查询指定时间范围内的成功记录
|
||||
List<DeviceCollectTaskTime> successTimes = deviceReceiveLogMapper.selectSuccessTimesByRange(startTime, endTime);
|
||||
|
||||
if (CollectionUtils.isEmpty(successTimes)) {
|
||||
log.info("没有找到增量数据");
|
||||
return;
|
||||
}
|
||||
|
||||
LocalDateTime updateTime = LocalDateTime.now();
|
||||
int updatedCount = 0;
|
||||
|
||||
for (DeviceCollectTaskTime successTime : successTimes) {
|
||||
// 查询现有任务
|
||||
DeviceCollectTask task = deviceCollectTaskMapper.selectOne(
|
||||
new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<DeviceCollectTask>()
|
||||
.eq("id", successTime.getDeviceCollectId())
|
||||
);
|
||||
|
||||
if (task != null) {
|
||||
// 更新任务时间
|
||||
int result = deviceCollectTaskMapper.updateTaskTime(
|
||||
successTime.getDeviceCollectId(),
|
||||
task.getFirstTime() == null ? successTime.getFirstTime() : null,
|
||||
successTime.getLastSuccessTime(),
|
||||
null, // 失败时间需要单独查询
|
||||
updateTime
|
||||
);
|
||||
|
||||
if (result > 0) {
|
||||
updatedCount++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
log.info("增量更新完成,处理记录: {},更新任务: {}", successTimes.size(), updatedCount);
|
||||
}
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package com.common.service;
|
||||
|
||||
|
||||
|
||||
import com.common.entity.DeviceReceiveLog;
|
||||
import com.github.pagehelper.PageInfo;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public interface DeviceReceiveLogService {
|
||||
|
||||
// 插入操作
|
||||
Long insertLog(DeviceReceiveLog log);
|
||||
int batchInsertLogs(List<DeviceReceiveLog> logs);
|
||||
|
||||
// 查询操作
|
||||
DeviceReceiveLog getById(Long id);
|
||||
List<DeviceReceiveLog> getByDeviceId(Integer deviceId);
|
||||
List<DeviceReceiveLog> getByCollectId(Integer collectId);
|
||||
List<DeviceReceiveLog> getByTimeRange(LocalDateTime startTime, LocalDateTime endTime);
|
||||
List<DeviceReceiveLog> getByCondition(DeviceReceiveLog condition);
|
||||
PageInfo<DeviceReceiveLog> getByConditionPage(DeviceReceiveLog condition, Integer pageNum, Integer pageSize);
|
||||
|
||||
// 统计操作
|
||||
Long countByCondition(DeviceReceiveLog condition);
|
||||
List<Map<String, Object>> getDeviceLogStatistics();
|
||||
|
||||
// 删除操作
|
||||
int deleteOldLogs(LocalDateTime beforeTime);
|
||||
|
||||
// 获取最近日志
|
||||
List<DeviceReceiveLog> getRecentLogs(Integer limit);
|
||||
}
|
||||
+189
@@ -0,0 +1,189 @@
|
||||
package com.common.service;
|
||||
|
||||
|
||||
import com.common.entity.DeviceStatsDTO;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.jdbc.core.RowMapper;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.List;
|
||||
import com.common.service.DeviceCollectTaskUpdateService;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Component;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class DeviceStatsUpdateService {
|
||||
|
||||
@Autowired
|
||||
private final DeviceCollectTaskUpdateService updateService;
|
||||
private static final DateTimeFormatter DATE_FORMATTER =
|
||||
DateTimeFormatter.ofPattern("yyyyMMdd");
|
||||
|
||||
@Autowired
|
||||
private JdbcTemplate jdbcTemplate;
|
||||
|
||||
// SQL 模板定义
|
||||
private static final String COLLECT_DEVICE_STATS_SQL =
|
||||
"WITH device_receive_stats AS ( " +
|
||||
" SELECT device_id, MAX(receive_time) AS last_receive_time " +
|
||||
" FROM %s " +
|
||||
" WHERE receive_time >= CURRENT_DATE " +
|
||||
" GROUP BY device_id " +
|
||||
"), " +
|
||||
"parse_stats AS ( " +
|
||||
" SELECT device_id, COUNT(*) AS parse_count " +
|
||||
" FROM ( " +
|
||||
" SELECT device_id FROM %s " +
|
||||
" WHERE created_at >= CURRENT_DATE " +
|
||||
" UNION ALL " +
|
||||
" SELECT device_id FROM %s " +
|
||||
" WHERE created_at >= CURRENT_DATE " +
|
||||
" ) t " +
|
||||
" GROUP BY device_id " +
|
||||
"), " +
|
||||
"non_log_stats AS ( " +
|
||||
" SELECT device_id, COUNT(*) AS non_log_count " +
|
||||
" FROM %s " +
|
||||
" WHERE created_at >= CURRENT_DATE " +
|
||||
" GROUP BY device_id " +
|
||||
"), " +
|
||||
"combined_stats AS ( " +
|
||||
" SELECT COALESCE(r.device_id, p.device_id, n.device_id) AS device_id, " +
|
||||
" r.last_receive_time, " +
|
||||
" COALESCE(p.parse_count, 0) AS parse_count, " +
|
||||
" COALESCE(n.non_log_count, 0) AS non_log_count " +
|
||||
" FROM device_receive_stats r " +
|
||||
" FULL OUTER JOIN parse_stats p ON r.device_id = p.device_id " +
|
||||
" FULL OUTER JOIN non_log_stats n ON COALESCE(r.device_id, p.device_id) = n.device_id " +
|
||||
") " +
|
||||
"SELECT * FROM combined_stats";
|
||||
|
||||
private static final String UPDATE_DEVICE_STATS_SQL =
|
||||
"UPDATE device_device " +
|
||||
"SET last_receive_time = ?, " +
|
||||
" today_parse_count = ?, " +
|
||||
" today_non_log_count = ?, " +
|
||||
" updated_at = NOW() " +
|
||||
"WHERE id = ?";
|
||||
|
||||
/**
|
||||
* 每分钟执行一次统计更新(秒:0,分:*,时:*)
|
||||
*/
|
||||
@Scheduled(cron = "0 * * * * ?")
|
||||
@Transactional
|
||||
public void updateDeviceStats() {
|
||||
long startTime = System.currentTimeMillis();
|
||||
log.info("开始执行设备统计更新任务...");
|
||||
|
||||
try {
|
||||
// 获取当前日期,用于动态表名
|
||||
String today = LocalDateTime.now().format(DATE_FORMATTER);
|
||||
|
||||
// 统计每个设备的当天数据
|
||||
List<DeviceStatsDTO> deviceStats = collectDeviceStats(today);
|
||||
|
||||
// 批量更新 device_device 表
|
||||
batchUpdateDeviceStats(deviceStats);
|
||||
|
||||
long endTime = System.currentTimeMillis();
|
||||
log.info("设备统计更新完成,处理设备数:{},耗时:{}ms",
|
||||
deviceStats.size(), (endTime - startTime));
|
||||
|
||||
// 批量更新 device_collect_task 表
|
||||
updateDeviceCollectTaskTimes();
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("设备统计更新任务执行失败", e);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 收集设备统计信息
|
||||
*/
|
||||
private List<DeviceStatsDTO> collectDeviceStats(String today) {
|
||||
// 构建动态表名
|
||||
String receiveLogTable = "device_receive_log";
|
||||
String normalDataTable = "syslog_normal_data_" + today;
|
||||
String normalAlarmTable = "syslog_normal_alarm_" + today;
|
||||
String nonNormalTable = "syslog_non_normal_message_" + today;
|
||||
|
||||
String sql = String.format(
|
||||
COLLECT_DEVICE_STATS_SQL,
|
||||
receiveLogTable,
|
||||
normalDataTable,
|
||||
normalAlarmTable,
|
||||
nonNormalTable
|
||||
);
|
||||
|
||||
return jdbcTemplate.query(sql, new RowMapper<DeviceStatsDTO>() {
|
||||
@Override
|
||||
public DeviceStatsDTO mapRow(ResultSet rs, int rowNum) throws SQLException {
|
||||
DeviceStatsDTO dto = new DeviceStatsDTO();
|
||||
dto.setDeviceId(rs.getLong("device_id"));
|
||||
|
||||
java.sql.Timestamp timestamp = rs.getTimestamp("last_receive_time");
|
||||
if (timestamp != null) {
|
||||
dto.setLastReceiveTime(timestamp.toLocalDateTime());
|
||||
}
|
||||
|
||||
dto.setParseCount(rs.getInt("parse_count"));
|
||||
dto.setNonLogCount(rs.getInt("non_log_count"));
|
||||
return dto;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量更新设备统计信息
|
||||
*/
|
||||
private void batchUpdateDeviceStats(List<DeviceStatsDTO> deviceStats) {
|
||||
if (deviceStats.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 使用批量更新提高性能
|
||||
List<Object[]> batchArgs = deviceStats.stream()
|
||||
.map(dto -> new Object[] {
|
||||
dto.getLastReceiveTime(),
|
||||
dto.getParseCount(),
|
||||
dto.getNonLogCount(),
|
||||
dto.getDeviceId()
|
||||
})
|
||||
.collect(java.util.stream.Collectors.toList());
|
||||
|
||||
int[] updateCounts = jdbcTemplate.batchUpdate(UPDATE_DEVICE_STATS_SQL, batchArgs);
|
||||
|
||||
log.debug("批量更新完成,影响行数:{}", updateCounts.length);
|
||||
}
|
||||
|
||||
|
||||
public void updateDeviceCollectTaskTimes() {
|
||||
log.info("开始执行设备采集探针任务时间更新,时间: {}", LocalDateTime.now());
|
||||
|
||||
try {
|
||||
long startTime = System.currentTimeMillis();
|
||||
|
||||
// 使用批量更新方法
|
||||
updateService.batchUpdateDeviceTaskTimes();
|
||||
|
||||
long endTime = System.currentTimeMillis();
|
||||
log.info("设备采集探针任务时间更新完成,耗时: {}ms", endTime - startTime);
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("执行设备采集探针任务时间更新失败", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package com.common.service;
|
||||
|
||||
import com.common.entity.DmColumn;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public interface DmColumnService {
|
||||
|
||||
List<DmColumn> findAll();
|
||||
|
||||
DmColumn findById(Long id);
|
||||
|
||||
DmColumn findByDmColumnId(Long id);
|
||||
|
||||
DmColumn findByName(String name);
|
||||
|
||||
List<DmColumn> findByDisplayName(String displayName);
|
||||
|
||||
List<DmColumn> findByIsBuiltIn(Boolean isBuiltIn);
|
||||
|
||||
int insert(DmColumn dmColumn);
|
||||
|
||||
int batchInsert(List<DmColumn> dmColumns);
|
||||
|
||||
List<DmColumn> findByCondition(DmColumn condition);
|
||||
Long count();
|
||||
|
||||
List<Map<String, Object>> selectAllNormal();
|
||||
}
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
package com.common.service;
|
||||
|
||||
import com.common.entity.XdrHoneypot;
|
||||
import com.common.mapper.XdrHoneypotMapper;
|
||||
import com.common.util.MyBatisUtil;
|
||||
import com.influx.SyslogToInfluxApp;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import org.apache.ibatis.session.SqlSession;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.cache.annotation.CacheConfig;
|
||||
import org.springframework.cache.annotation.Cacheable;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import com.common.mapper.DmNormalizeRuleMapper;
|
||||
import com.common.entity.DmNormalizeRule;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
|
||||
|
||||
@Service
|
||||
@CacheConfig(cacheNames = "normalizeRule")
|
||||
public class DmNormalizeRuleService {
|
||||
|
||||
@Autowired
|
||||
private DmNormalizeRuleMapper dmNormalizeRuleMapper;
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(DmNormalizeRuleService.class);
|
||||
|
||||
|
||||
/**
|
||||
* 根据ID查询规则
|
||||
*/
|
||||
@Cacheable(key = "'id:' + #id")
|
||||
public DmNormalizeRule getById(Long id) {
|
||||
return dmNormalizeRuleMapper.selectById(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据ID和租户查询规则
|
||||
*/
|
||||
public DmNormalizeRule getByIdAndTenant(Long id, String tenantId) {
|
||||
return dmNormalizeRuleMapper.selectByIdAndTenant(id, tenantId);
|
||||
}
|
||||
/**
|
||||
* 根据ID更新规则
|
||||
*/
|
||||
public boolean updateById(DmNormalizeRule rule) {
|
||||
// 设置更新时间
|
||||
rule.setUpdatedAt(java.time.LocalDateTime.now());
|
||||
rule.setUpdateTime(java.time.LocalDateTime.now());
|
||||
int result = dmNormalizeRuleMapper.updateById(rule);
|
||||
return result > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据ID和租户更新规则
|
||||
*/
|
||||
public boolean updateByIdAndTenant(DmNormalizeRule rule) {
|
||||
// 设置更新时间
|
||||
rule.setUpdatedAt(java.time.LocalDateTime.now());
|
||||
rule.setUpdateTime(java.time.LocalDateTime.now());
|
||||
int result = dmNormalizeRuleMapper.updateByIdAndTenant(rule);
|
||||
return result > 0;
|
||||
}
|
||||
/**
|
||||
* 根据device ID 获取normal rule 信息
|
||||
*/
|
||||
@Cacheable(key = "'deviceId:' + #id")
|
||||
public List<Map<String, Object>> selectByDeviceId( Long id)
|
||||
{
|
||||
try (SqlSession sqlSession = MyBatisUtil.getSqlSession()) {
|
||||
dmNormalizeRuleMapper = sqlSession.getMapper(DmNormalizeRuleMapper.class);
|
||||
|
||||
List<Map<String, Object>> ruleMap=dmNormalizeRuleMapper.selectByDeviceId(id);
|
||||
sqlSession.commit();
|
||||
return ruleMap;
|
||||
|
||||
} catch (Exception e) {
|
||||
logger.error("DmNormalizeRuleService MyBatisUtil getSqlSession 异常", e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据device ID 获取关联的Normalize Rule 信息
|
||||
* @param id
|
||||
* @return
|
||||
*/
|
||||
@Cacheable(key = "'deviceId:' + #id")
|
||||
public List<Map<String, Object>> selectByDeviceIdAuto( Long id)
|
||||
{
|
||||
System.out.println("调用selectByDeviceIdAuto 方法,id:"+id);
|
||||
List<Map<String, Object>> ruleMap=dmNormalizeRuleMapper.selectByDeviceId(id);
|
||||
return ruleMap;
|
||||
}
|
||||
|
||||
}
|
||||
+165
@@ -0,0 +1,165 @@
|
||||
package com.common.service;
|
||||
|
||||
|
||||
|
||||
import com.common.entity.AppLog;
|
||||
import com.common.service.AppLogRepository;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
|
||||
import org.springframework.data.elasticsearch.core.IndexOperations;
|
||||
import org.springframework.data.elasticsearch.core.document.Document;
|
||||
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.Collections;
|
||||
@Slf4j
|
||||
@Service
|
||||
public class ElasticsearchService {
|
||||
|
||||
@Autowired
|
||||
private AppLogRepository appLogRepository;
|
||||
|
||||
@Autowired
|
||||
private ElasticsearchRestTemplate elasticsearchRestTemplate;
|
||||
|
||||
private static final DateTimeFormatter INDEX_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd");
|
||||
|
||||
/**
|
||||
* 保存日志到ES
|
||||
*/
|
||||
public void saveAppLog(AppLog appLog) {
|
||||
try {
|
||||
// 设置索引名为当天的日期
|
||||
String indexName = "applog-" + LocalDate.now().format(INDEX_FORMATTER);
|
||||
appLog.setIndex(indexName);
|
||||
|
||||
// 检查索引是否存在,不存在则创建
|
||||
IndexOperations indexOps = elasticsearchRestTemplate.indexOps(IndexCoordinates.of(indexName));
|
||||
if (!indexOps.exists()) {
|
||||
indexOps.create();
|
||||
Document mapping = indexOps.createMapping(AppLog.class);
|
||||
indexOps.putMapping(mapping);
|
||||
log.info("创建ES索引: {}", indexName);
|
||||
}
|
||||
|
||||
// 保存数据
|
||||
appLogRepository.save(appLog);
|
||||
log.info("成功保存日志到ES, ID: {}, Index: {}", appLog.getId(), indexName);
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("保存日志到ES失败", e);
|
||||
throw new RuntimeException("保存ES日志失败", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量保存日志
|
||||
*/
|
||||
public void saveAppLogs(List<AppLog> appLogs) {
|
||||
try {
|
||||
String indexName = "applog-" + LocalDate.now().format(INDEX_FORMATTER);
|
||||
|
||||
// 设置所有日志的索引
|
||||
appLogs.forEach(log -> log.setIndex(indexName));
|
||||
|
||||
// 检查索引是否存在,不存在则创建
|
||||
IndexOperations indexOps = elasticsearchRestTemplate.indexOps(IndexCoordinates.of(indexName));
|
||||
if (!indexOps.exists()) {
|
||||
indexOps.create();
|
||||
Document mapping = indexOps.createMapping(AppLog.class);
|
||||
indexOps.putMapping(mapping);
|
||||
log.info("创建ES索引: {}", indexName);
|
||||
}
|
||||
|
||||
appLogRepository.saveAll(appLogs);
|
||||
log.info("批量保存 {} 条日志到ES索引: {}", appLogs.size(), indexName);
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("批量保存日志到ES失败", e);
|
||||
throw new RuntimeException("批量保存ES日志失败", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据日期获取索引中的日志
|
||||
*/
|
||||
public List<AppLog> getLogsByDate(LocalDate date) {
|
||||
String indexName = "applog-" + date.format(INDEX_FORMATTER);
|
||||
IndexCoordinates indexCoordinates = IndexCoordinates.of(indexName);
|
||||
|
||||
try {
|
||||
// 检查索引是否存在
|
||||
IndexOperations indexOps = elasticsearchRestTemplate.indexOps(indexCoordinates);
|
||||
if (!indexOps.exists()) {
|
||||
log.info("索引 {} 不存在", indexName);
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
// 使用ElasticsearchRestTemplate查询指定索引
|
||||
return elasticsearchRestTemplate.search(
|
||||
org.springframework.data.elasticsearch.core.query.Query.findAll(),
|
||||
AppLog.class,
|
||||
indexCoordinates
|
||||
).get().map(result -> {
|
||||
AppLog appLog = result.getContent();
|
||||
appLog.setIndex(indexName); // 设置索引名称
|
||||
appLog.setScore(result.getScore()); // 设置评分
|
||||
return appLog;
|
||||
}).collect(Collectors.toList());
|
||||
} catch (Exception e) {
|
||||
log.warn("查询ES索引 {} 失败", indexName, e);
|
||||
return Collections.emptyList();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据ID检查日志是否存在
|
||||
*/
|
||||
public boolean existsById(String id, LocalDate date) {
|
||||
String indexName = "applog-" + date.format(INDEX_FORMATTER);
|
||||
IndexCoordinates indexCoordinates = IndexCoordinates.of(indexName);
|
||||
|
||||
try {
|
||||
//return elasticsearchRestTemplate.exists(id, AppLog.class, indexCoordinates);
|
||||
return elasticsearchRestTemplate.exists(id, indexCoordinates);
|
||||
} catch (Exception e) {
|
||||
log.warn("检查日志存在性失败, ID: {}, Index: {}", id, indexName);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据索引名称获取日志
|
||||
*/
|
||||
public List<AppLog> getLogsByIndex(String indexName) {
|
||||
IndexCoordinates indexCoordinates = IndexCoordinates.of(indexName);
|
||||
|
||||
try {
|
||||
// 检查索引是否存在
|
||||
IndexOperations indexOps = elasticsearchRestTemplate.indexOps(indexCoordinates);
|
||||
if (!indexOps.exists()) {
|
||||
log.info("索引 {} 不存在", indexName);
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
return elasticsearchRestTemplate.search(
|
||||
org.springframework.data.elasticsearch.core.query.Query.findAll(),
|
||||
AppLog.class,
|
||||
indexCoordinates
|
||||
).get().map(result -> {
|
||||
AppLog appLog = result.getContent();
|
||||
appLog.setIndex(indexName);
|
||||
appLog.setScore(result.getScore());
|
||||
return appLog;
|
||||
}).collect(Collectors.toList());
|
||||
} catch (Exception e) {
|
||||
log.warn("查询ES索引 {} 失败", indexName, e);
|
||||
return Collections.emptyList();
|
||||
}
|
||||
}
|
||||
}
|
||||
+132
@@ -0,0 +1,132 @@
|
||||
package com.common.service;
|
||||
|
||||
import com.common.entity.AppLog;
|
||||
import com.common.entity.AppLogEntity;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.BeanUtils;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
public class EsToDbSyncService {
|
||||
|
||||
@Autowired
|
||||
private ElasticsearchService elasticsearchService;
|
||||
|
||||
@Autowired
|
||||
private ApplogService ApplogService;
|
||||
|
||||
/**
|
||||
* 同步指定日期的ES日志到数据库
|
||||
*/
|
||||
public void syncEsLogsToDatabase(LocalDate date) {
|
||||
log.info("开始同步ES日志到数据库,日期: {}", date);
|
||||
|
||||
try {
|
||||
// 从ES获取指定日期的日志
|
||||
List<AppLog> esLogs = elasticsearchService.getLogsByDate(date);
|
||||
|
||||
if (esLogs.isEmpty()) {
|
||||
log.info("ES中未找到 {} 的日志数据", date);
|
||||
return;
|
||||
}
|
||||
|
||||
log.info("从ES索引 applog-{} 获取到 {} 条日志",
|
||||
date.format(java.time.format.DateTimeFormatter.ofPattern("yyyyMMdd")),
|
||||
esLogs.size());
|
||||
|
||||
// 转换为数据库实体
|
||||
List<AppLogEntity> dbLogs = esLogs.stream()
|
||||
.map(this::convertToEntity)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
// 批量保存到数据库(自动去重)
|
||||
int savedCount = ApplogService.batchSaveAppLogsWithDeduplication(dbLogs);
|
||||
|
||||
log.info("同步完成,成功保存 {} 条日志到数据库", savedCount);
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("同步ES日志到数据库失败,日期: {}", date, e);
|
||||
throw new RuntimeException("同步失败", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 同步指定索引的ES日志到数据库
|
||||
*/
|
||||
public void syncEsLogsByIndexToDatabase(String indexName) {
|
||||
log.info("开始同步ES索引 {} 的日志到数据库", indexName);
|
||||
|
||||
try {
|
||||
// 从ES获取指定索引的日志
|
||||
List<AppLog> esLogs = elasticsearchService.getLogsByIndex(indexName);
|
||||
|
||||
if (esLogs.isEmpty()) {
|
||||
log.info("ES索引 {} 中未找到日志数据", indexName);
|
||||
return;
|
||||
}
|
||||
|
||||
log.info("从ES索引 {} 获取到 {} 条日志", indexName, esLogs.size());
|
||||
|
||||
// 转换为数据库实体
|
||||
List<AppLogEntity> dbLogs = esLogs.stream()
|
||||
.map(this::convertToEntity)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
// 批量保存到数据库(自动去重)
|
||||
int savedCount = ApplogService.batchSaveAppLogsWithDeduplication(dbLogs);
|
||||
|
||||
log.info("同步完成,成功保存 {} 条日志到数据库", savedCount);
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("同步ES索引 {} 的日志到数据库失败", indexName, e);
|
||||
throw new RuntimeException("同步失败", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将ES实体转换为数据库实体
|
||||
*/
|
||||
private AppLogEntity convertToEntity(AppLog esLog) {
|
||||
AppLogEntity entity = new AppLogEntity();
|
||||
|
||||
// 复制ES元数据字段
|
||||
entity.setEsId(esLog.getId());
|
||||
entity.setEsIndex(esLog.getIndex());
|
||||
entity.setEsType(esLog.getType());
|
||||
entity.setEsScore(esLog.getScore());
|
||||
|
||||
// 复制日志内容字段
|
||||
entity.setDtTime(esLog.getDtTime());
|
||||
entity.setCollectTime(esLog.getCollectTime());
|
||||
entity.setLogType(esLog.getLogType());
|
||||
entity.setTraceId(esLog.getTraceId());
|
||||
entity.setMethod(esLog.getMethod());
|
||||
entity.setAppName(esLog.getAppName());
|
||||
entity.setIp(esLog.getIp());
|
||||
entity.setClassName(esLog.getClassName());
|
||||
entity.setEnv(esLog.getEnv());
|
||||
entity.setContent(esLog.getContent());
|
||||
entity.setThreadName(esLog.getThreadName());
|
||||
entity.setLogLevel(esLog.getLogLevel());
|
||||
entity.setSeq(esLog.getSeq());
|
||||
entity.setIndexedAt(esLog.getIndexedAt());
|
||||
|
||||
// 转换时间字段
|
||||
if (esLog.getDtTime() != null) {
|
||||
entity.setLogDate(Instant.ofEpochMilli(esLog.getDtTime())
|
||||
.atZone(ZoneId.systemDefault())
|
||||
.toLocalDateTime());
|
||||
}
|
||||
|
||||
return entity;
|
||||
}
|
||||
}
|
||||
+212
@@ -0,0 +1,212 @@
|
||||
package com.common.service;
|
||||
|
||||
import com.influx.InfluxDBClient;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.ArrayList;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
public class InfluxSyslogService {
|
||||
|
||||
//@Autowired
|
||||
//private InfluxDBClient influxDBClient;
|
||||
// 初始化 InfluxDB 客户端
|
||||
//@Autowired
|
||||
private final com.influx.InfluxDBClient influxDBClient = new InfluxDBClient();
|
||||
|
||||
private static final DateTimeFormatter TABLE_DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd");
|
||||
private static final DateTimeFormatter INPUT_DATE_FORMATTER = DateTimeFormatter.ISO_DATE_TIME;
|
||||
|
||||
/**
|
||||
* 接口1:按时间范围查询(最长一天)
|
||||
*/
|
||||
public List<Map<String, Object>> queryByTimeRange(String startTime, String endTime) {
|
||||
try {
|
||||
Instant start = parseInstant(startTime);
|
||||
Instant end = parseInstant(endTime);
|
||||
|
||||
validateTimeRange(start, end);
|
||||
|
||||
// 生成需要查询的表名(处理跨天情况)
|
||||
List<String> measurementNames = generateMeasurementNames(start, end);
|
||||
List<Map<String, Object>> allResults = new ArrayList<>();
|
||||
|
||||
for (String measurement : measurementNames) {
|
||||
List<Map<String, Object>> results = influxDBClient.queryByTimeRange(measurement, start, end);
|
||||
allResults.addAll(results);
|
||||
}
|
||||
|
||||
log.info("按时间范围查询成功,查询表: {}, 返回记录数: {}", measurementNames, allResults.size());
|
||||
return allResults;
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("按时间范围查询失败: {}", e.getMessage());
|
||||
throw new RuntimeException("查询失败: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 接口2:按UUID查询详细日志
|
||||
*/
|
||||
public List<Map<String, Object>> queryByUuid(String uuid) {
|
||||
try {
|
||||
// 从UUID中提取日期部分
|
||||
String datePart = extractDateFromUuid(uuid);
|
||||
String measurement = "syslog_security_" + datePart;
|
||||
|
||||
List<Map<String, Object>> results = influxDBClient.queryByUuid(measurement, uuid);
|
||||
|
||||
log.info("按UUID查询成功,表: {}, UUID: {}, 返回记录数: {}", measurement, uuid, results.size());
|
||||
return results;
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("按UUID查询失败: {}", e.getMessage());
|
||||
throw new RuntimeException("查询失败: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 接口3:按设备ID和时间范围查询
|
||||
*/
|
||||
public List<Map<String, Object>> queryByDeviceIdAndTime(String deviceId, String startTime, String endTime) {
|
||||
try {
|
||||
Instant start = parseInstant(startTime);
|
||||
Instant end = parseInstant(endTime);
|
||||
|
||||
validateTimeRange(start, end);
|
||||
|
||||
List<String> measurementNames = generateMeasurementNames(start, end);
|
||||
List<Map<String, Object>> allResults = new ArrayList<>();
|
||||
|
||||
for (String measurement : measurementNames) {
|
||||
List<Map<String, Object>> results = influxDBClient.queryByDeviceIdAndTime(measurement, deviceId, start, end);
|
||||
allResults.addAll(results);
|
||||
}
|
||||
|
||||
log.info("按设备ID查询成功,设备: {}, 返回记录数: {}", deviceId, allResults.size());
|
||||
return allResults;
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("按设备ID查询失败: {}", e.getMessage());
|
||||
throw new RuntimeException("查询失败: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 接口4:模糊查询message内容
|
||||
*/
|
||||
public List<Map<String, Object>> queryByMessageContent(String startTime, String endTime, String keyword) {
|
||||
try {
|
||||
Instant start = parseInstant(startTime);
|
||||
Instant end = parseInstant(endTime);
|
||||
|
||||
validateTimeRange(start, end);
|
||||
validateKeyword(keyword);
|
||||
|
||||
List<String> measurementNames = generateMeasurementNames(start, end);
|
||||
List<Map<String, Object>> allResults = new ArrayList<>();
|
||||
|
||||
for (String measurement : measurementNames) {
|
||||
List<Map<String, Object>> results = influxDBClient.queryByMessageContent(measurement, start, end, keyword);
|
||||
allResults.addAll(results);
|
||||
}
|
||||
|
||||
log.info("模糊查询成功,关键字: {}, 返回记录数: {}", keyword, allResults.size());
|
||||
return allResults;
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("模糊查询失败: {}", e.getMessage());
|
||||
throw new RuntimeException("查询失败: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
public Map<String, List<Map<String, Object>>> queryByUuids(List<String> uuids) {
|
||||
if (CollectionUtils.isEmpty(uuids)) {
|
||||
return Collections.emptyMap();
|
||||
}
|
||||
Map<String, List<Map<String, Object>>> resultMap = new HashMap<>();
|
||||
for (String uuid : uuids) {
|
||||
// 查询单个UUID的日志
|
||||
List<Map<String, Object>> logList = queryByUuid(uuid);
|
||||
resultMap.put(uuid, logList);
|
||||
}
|
||||
return resultMap;
|
||||
}
|
||||
/**
|
||||
* 从UUID中提取日期部分
|
||||
*/
|
||||
private String extractDateFromUuid(String uuid) {
|
||||
if (uuid == null || uuid.length() < 8) {
|
||||
throw new IllegalArgumentException("UUID格式不正确,无法提取日期");
|
||||
}
|
||||
return uuid.substring(0, 8);
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析时间字符串为Instant
|
||||
*/
|
||||
private Instant parseInstant(String timeString) {
|
||||
try {
|
||||
return Instant.parse(timeString);
|
||||
} catch (Exception e) {
|
||||
throw new IllegalArgumentException("时间格式不正确,请使用ISO格式,例如: 2023-11-20T00:00:00Z");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证时间范围(最长一天)
|
||||
*/
|
||||
private void validateTimeRange(Instant start, Instant end) {
|
||||
long hours = ChronoUnit.HOURS.between(start, end);
|
||||
if (hours > 24) {
|
||||
throw new IllegalArgumentException("查询时间范围不能超过24小时");
|
||||
}
|
||||
if (start.isAfter(end)) {
|
||||
throw new IllegalArgumentException("开始时间不能晚于结束时间");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证搜索关键字
|
||||
*/
|
||||
private void validateKeyword(String keyword) {
|
||||
if (keyword == null || keyword.trim().isEmpty()) {
|
||||
throw new IllegalArgumentException("搜索关键字不能为空");
|
||||
}
|
||||
if (keyword.length() > 32) {
|
||||
throw new IllegalArgumentException("搜索关键字长度不能超过32个字符");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成需要查询的表名列表(处理跨天情况)
|
||||
*/
|
||||
private List<String> generateMeasurementNames(Instant start, Instant end) {
|
||||
List<String> measurements = new ArrayList<>();
|
||||
|
||||
LocalDateTime startDate = LocalDateTime.ofInstant(start, ZoneId.of("UTC"));
|
||||
LocalDateTime endDate = LocalDateTime.ofInstant(end, ZoneId.of("UTC"));
|
||||
|
||||
LocalDateTime currentDate = startDate;
|
||||
while (!currentDate.toLocalDate().isAfter(endDate.toLocalDate())) {
|
||||
String dateStr = currentDate.format(TABLE_DATE_FORMATTER);
|
||||
measurements.add("syslog_security_" + dateStr);
|
||||
currentDate = currentDate.plusDays(1);
|
||||
}
|
||||
|
||||
return measurements;
|
||||
}
|
||||
}
|
||||
+258
@@ -0,0 +1,258 @@
|
||||
package com.common.service;
|
||||
|
||||
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.JSONArray;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class LogDataCompleteService {
|
||||
|
||||
|
||||
/**
|
||||
* 处理日志数据补全
|
||||
*/
|
||||
public boolean processDataCompletion(String ruleContent,Map<String, Object> destMap) {
|
||||
try {
|
||||
boolean hasCompleted = false;
|
||||
if (executeCompleteRule(ruleContent, destMap)) {
|
||||
hasCompleted = true;
|
||||
}
|
||||
if (hasCompleted) {
|
||||
log.debug("数据补全完成: {}", destMap.get("id"));
|
||||
} else {
|
||||
log.debug("数据无需补全: {}", destMap.get("id"));
|
||||
}
|
||||
return hasCompleted;
|
||||
} catch (Exception e) {
|
||||
log.error("处理数据补全时发生错误: {}", e.getMessage(), e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行补全规则
|
||||
*/
|
||||
private boolean executeCompleteRule(String ruleContent, Map<String, Object> destMap) {
|
||||
try {
|
||||
JSONObject ruleJson = JSON.parseObject(ruleContent);
|
||||
JSONArray completeColumns = ruleJson.getJSONArray("complete_columns");
|
||||
|
||||
if (completeColumns == null || completeColumns.isEmpty()) {
|
||||
log.warn("补全规则为空");
|
||||
return false;
|
||||
}
|
||||
|
||||
boolean hasCompleted = false;
|
||||
|
||||
// 遍历所有补全配置
|
||||
for (int i = 0; i < completeColumns.size(); i++) {
|
||||
JSONObject completeConfig = completeColumns.getJSONObject(i);
|
||||
if (executeCompleteConfig(completeConfig, destMap)) {
|
||||
hasCompleted = true;
|
||||
}
|
||||
}
|
||||
|
||||
return hasCompleted;
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("解析补全规则失败: {}", e.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行单个补全配置
|
||||
*/
|
||||
private boolean executeCompleteConfig(JSONObject completeConfig, Map<String, Object> destMap) {
|
||||
try {
|
||||
String columnName = completeConfig.getString("column_name");
|
||||
Object value = completeConfig.get("value");
|
||||
JSONArray conditions = completeConfig.getJSONArray("conditions");
|
||||
String relation = completeConfig.getString("filters_relation");
|
||||
|
||||
// 检查目标字段是否已存在
|
||||
if (destMap.containsKey(columnName) && destMap.get(columnName) != null) {
|
||||
log.debug("字段 {} 已存在,跳过补全", columnName);
|
||||
return false;
|
||||
}
|
||||
|
||||
// 检查条件是否满足
|
||||
boolean conditionsMet = evaluateConditions(conditions, relation, destMap);
|
||||
|
||||
if (conditionsMet) {
|
||||
// 执行补全操作
|
||||
destMap.put(columnName, value);
|
||||
log.debug("字段 {} 补全完成,值: {}", columnName, value);
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("执行补全配置失败: {}", e.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 评估条件
|
||||
*/
|
||||
private boolean evaluateConditions(JSONArray conditions, String relation, Map<String, Object> destMap) {
|
||||
if (conditions == null || conditions.isEmpty()) {
|
||||
return true; // 无条件,直接通过
|
||||
}
|
||||
|
||||
// 根据关系类型评估
|
||||
if ("or".equalsIgnoreCase(relation)) {
|
||||
return evaluateOrConditions(conditions, destMap);
|
||||
} else {
|
||||
// 默认使用 AND 关系
|
||||
return evaluateAndConditions(conditions, destMap);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 评估 AND 关系的条件
|
||||
*/
|
||||
private boolean evaluateAndConditions(JSONArray conditions, Map<String, Object> destMap) {
|
||||
for (int i = 0; i < conditions.size(); i++) {
|
||||
JSONObject condition = conditions.getJSONObject(i);
|
||||
if (!evaluateCondition(condition, destMap)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 评估 OR 关系的条件
|
||||
*/
|
||||
private boolean evaluateOrConditions(JSONArray conditions, Map<String, Object> destMap) {
|
||||
for (int i = 0; i < conditions.size(); i++) {
|
||||
JSONObject condition = conditions.getJSONObject(i);
|
||||
if (evaluateCondition(condition, destMap)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 评估单个条件
|
||||
*/
|
||||
private boolean evaluateCondition(JSONObject condition, Map<String, Object> destMap) {
|
||||
String columnName = condition.getString("column_name");
|
||||
String op = condition.getString("op");
|
||||
Object value = condition.get("value");
|
||||
|
||||
// 从目标Map中获取字段值
|
||||
Object fieldValue = destMap.get(columnName);
|
||||
if (fieldValue == null) {
|
||||
fieldValue = ""; // 处理null值
|
||||
}
|
||||
|
||||
String fieldValueStr = fieldValue.toString();
|
||||
|
||||
try {
|
||||
switch (op) {
|
||||
case "=":
|
||||
return equals(fieldValueStr, value);
|
||||
case "!=":
|
||||
return notEquals(fieldValueStr, value);
|
||||
case "in":
|
||||
return in(fieldValueStr, value);
|
||||
case "zero_len":
|
||||
return zeroLen(fieldValueStr, value);
|
||||
case "contain":
|
||||
return contain(fieldValueStr, value);
|
||||
case "regexp":
|
||||
return regexp(fieldValueStr, value);
|
||||
default:
|
||||
log.warn("未知的操作符: {}", op);
|
||||
return false;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("评估条件失败: {}{}{}, 错误: {}", columnName, op, value, e.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 等于操作
|
||||
*/
|
||||
private boolean equals(String fieldValue, Object value) {
|
||||
if (value == null) return false;
|
||||
return fieldValue.equals(value.toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* 不等于操作
|
||||
*/
|
||||
private boolean notEquals(String fieldValue, Object value) {
|
||||
if (value == null) return true;
|
||||
return !fieldValue.equals(value.toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* IN 操作
|
||||
*/
|
||||
private boolean in(String fieldValue, Object value) {
|
||||
if (value instanceof JSONArray) {
|
||||
JSONArray array = (JSONArray) value;
|
||||
for (Object item : array) {
|
||||
if (fieldValue.equals(item.toString())) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 非空检查操作
|
||||
*/
|
||||
private boolean zeroLen(String fieldValue, Object value) {
|
||||
boolean isEmpty = !StringUtils.hasText(fieldValue);
|
||||
boolean expected = Boolean.parseBoolean(value.toString());
|
||||
return isEmpty == expected;
|
||||
}
|
||||
|
||||
/**
|
||||
* 包含操作
|
||||
*/
|
||||
private boolean contain(String fieldValue, Object value) {
|
||||
if (value == null) return false;
|
||||
return fieldValue.contains(value.toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* 正则表达式匹配
|
||||
*/
|
||||
private boolean regexp(String fieldValue, Object value) {
|
||||
if (value == null) return false;
|
||||
try {
|
||||
Pattern pattern = Pattern.compile(value.toString());
|
||||
return pattern.matcher(fieldValue).matches();
|
||||
} catch (Exception e) {
|
||||
log.error("正则表达式编译失败: {}, 错误: {}", value, e.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
+204
@@ -0,0 +1,204 @@
|
||||
package com.common.service;
|
||||
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.JSONArray;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.common.mapper.SyslogNormalDataMapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class LogDataFilterService {
|
||||
|
||||
/**
|
||||
* 评估过滤规则
|
||||
*/
|
||||
public boolean evaluateFilterRule(String ruleContent, Map<String, Object> destMap) {
|
||||
try {
|
||||
JSONObject ruleJson = JSON.parseObject(ruleContent);
|
||||
if (ruleJson.containsKey("filters_params") ) {
|
||||
JSONObject filtersParamsObj = ruleJson.getJSONObject("filters_params");
|
||||
JSONArray filtersParams = filtersParamsObj.getJSONArray("expressions");
|
||||
|
||||
if (filtersParams == null || filtersParams.isEmpty()) {
|
||||
log.warn("泛化规则-数据过滤规则为空,默认不处理!");
|
||||
return false;
|
||||
}
|
||||
// 遍历所有过滤组,只要满足任一过滤组即可
|
||||
for (int i = 0; i < filtersParams.size(); i++) {
|
||||
JSONObject filterGroup = filtersParams.getJSONObject(i);
|
||||
if (evaluateFilterGroup(filterGroup, destMap)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("解析过滤规则失败或filters_params为空: {}", e.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 评估过滤组
|
||||
*/
|
||||
private boolean evaluateFilterGroup(JSONObject filterGroup, Map<String, Object> destMap) {
|
||||
try {
|
||||
//JSONObject expressions_obj = filterGroup.getJSONObject("expressions");
|
||||
JSONArray expressions = filterGroup.getJSONArray("expressions");
|
||||
String relation = filterGroup.getString("filters_relation");
|
||||
|
||||
if (expressions == null || expressions.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 根据关系类型评估
|
||||
if ("or".equalsIgnoreCase(relation)) {
|
||||
return evaluateOrExpressions(expressions, destMap);
|
||||
} else {
|
||||
// 默认使用 AND 关系
|
||||
return evaluateAndExpressions(expressions, destMap);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("评估过滤组evaluateFilterGroup解析json失败: {}", e.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 评估 AND 关系的表达式
|
||||
*/
|
||||
private boolean evaluateAndExpressions(JSONArray expressions, Map<String, Object> destMap) {
|
||||
for (int i = 0; i < expressions.size(); i++) {
|
||||
JSONObject expression = expressions.getJSONObject(i);
|
||||
if (!evaluateExpression(expression, destMap)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 评估 OR 关系的表达式
|
||||
*/
|
||||
private boolean evaluateOrExpressions(JSONArray expressions, Map<String, Object> destMap) {
|
||||
for (int i = 0; i < expressions.size(); i++) {
|
||||
JSONObject expression = expressions.getJSONObject(i);
|
||||
if (evaluateExpression(expression, destMap)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 评估单个表达式
|
||||
*/
|
||||
private boolean evaluateExpression(JSONObject expression, Map<String, Object> destMap) {
|
||||
String columnName = expression.getString("column_name");
|
||||
String op = expression.getString("op");
|
||||
Object value = expression.get("value");
|
||||
|
||||
// 从目标Map中获取字段值
|
||||
Object fieldValue = destMap.get(columnName);
|
||||
if (fieldValue == null) {
|
||||
fieldValue = ""; // 处理null值
|
||||
}
|
||||
|
||||
String fieldValueStr = fieldValue.toString();
|
||||
|
||||
try {
|
||||
switch (op) {
|
||||
case "=":
|
||||
return equals(fieldValueStr, value);
|
||||
case "!=":
|
||||
return notEquals(fieldValueStr, value);
|
||||
case "in":
|
||||
return in(fieldValueStr, value);
|
||||
case "zero_len":
|
||||
return zeroLen(fieldValueStr, value);
|
||||
case "contain":
|
||||
return contain(fieldValueStr, value);
|
||||
case "regexp":
|
||||
return regexp(fieldValueStr, value);
|
||||
default:
|
||||
log.warn("未知的操作符: {}", op);
|
||||
return false;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("评估表达式失败: {}{}{}, 错误: {}", columnName, op, value, e.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 等于操作
|
||||
*/
|
||||
private boolean equals(String fieldValue, Object value) {
|
||||
return fieldValue.equals(value.toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* 不等于操作
|
||||
*/
|
||||
private boolean notEquals(String fieldValue, Object value) {
|
||||
return !fieldValue.equals(value.toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* IN 操作
|
||||
*/
|
||||
private boolean in(String fieldValue, Object value) {
|
||||
if (value instanceof JSONArray) {
|
||||
JSONArray array = (JSONArray) value;
|
||||
for (Object item : array) {
|
||||
if (fieldValue.equals(item.toString())) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 长度检查操作
|
||||
*/
|
||||
private boolean zeroLen(String fieldValue, Object value) {
|
||||
boolean isEmpty = !StringUtils.hasText(fieldValue);
|
||||
boolean expected = Boolean.parseBoolean(value.toString());
|
||||
return isEmpty == expected;
|
||||
}
|
||||
|
||||
/**
|
||||
* 包含操作
|
||||
*/
|
||||
private boolean contain(String fieldValue, Object value) {
|
||||
return fieldValue.contains(value.toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* 正则表达式匹配
|
||||
*/
|
||||
private boolean regexp(String fieldValue, Object value) {
|
||||
try {
|
||||
Pattern pattern = Pattern.compile(value.toString());
|
||||
return pattern.matcher(fieldValue).matches();
|
||||
} catch (Exception e) {
|
||||
log.error("正则表达式编译失败: {}, 错误: {}", value, e.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
+227
@@ -0,0 +1,227 @@
|
||||
package com.common.service;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.time.temporal.TemporalAdjusters;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.HashMap;
|
||||
@Service
|
||||
public class PartitionTableService {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(PartitionTableService.class);
|
||||
|
||||
@Autowired
|
||||
private JdbcTemplate jdbcTemplate;
|
||||
|
||||
private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd");
|
||||
private static final DateTimeFormatter SQL_DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
|
||||
private static final DateTimeFormatter DISPLAY_FORMATTER = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
|
||||
/**
|
||||
* 检查第二天的分区表状态
|
||||
*/
|
||||
public PartitionTableStatus checkTomorrowPartitionTable() {
|
||||
PartitionTableStatus status = new PartitionTableStatus();
|
||||
|
||||
try {
|
||||
LocalDate tomorrow = LocalDate.now().plusDays(1);
|
||||
String tableName = "syslog_normal_data_" + tomorrow.format(DATE_FORMATTER);
|
||||
|
||||
status.setCheckDate(tomorrow);
|
||||
status.setTableName(tableName);
|
||||
status.setExists(isTableExists(tableName));
|
||||
|
||||
if (!status.isExists()) {
|
||||
// 如果不存在,尝试创建
|
||||
boolean created = createDailyPartitionTable(tomorrow);
|
||||
status.setCreated(created);
|
||||
status.setMessage(created ? "分区表创建成功" : "分区表创建失败");
|
||||
} else {
|
||||
status.setCreated(false);
|
||||
status.setMessage("分区表已存在");
|
||||
}
|
||||
|
||||
logger.info("第二天分区表检查完成: {}", status);
|
||||
|
||||
} catch (Exception e) {
|
||||
status.setExists(false);
|
||||
status.setCreated(false);
|
||||
status.setMessage("检查过程中发生错误: " + e.getMessage());
|
||||
logger.error("检查第二天分区表失败: {}", e.getMessage(), e);
|
||||
}
|
||||
|
||||
return status;
|
||||
}
|
||||
/**
|
||||
* 获取分区表统计信息
|
||||
*/
|
||||
public Map<String, Object> getPartitionTableStats() {
|
||||
Map<String, Object> stats = new HashMap<>();
|
||||
|
||||
try {
|
||||
// 统计总分区表数量
|
||||
String countSql = "SELECT COUNT(*) FROM information_schema.tables " +
|
||||
"WHERE table_schema = 'public' AND table_name LIKE 'syslog_normal_data_%'";
|
||||
Integer totalCount = jdbcTemplate.queryForObject(countSql, Integer.class);
|
||||
stats.put("totalPartitionTables", totalCount != null ? totalCount : 0);
|
||||
|
||||
// 获取最近创建的分区表
|
||||
String recentSql = "SELECT table_name FROM information_schema.tables " +
|
||||
"WHERE table_schema = 'public' AND table_name LIKE 'syslog_normal_data_%' " +
|
||||
"ORDER BY table_name DESC LIMIT 5";
|
||||
List<String> recentTables = jdbcTemplate.queryForList(recentSql, String.class);
|
||||
stats.put("recentTables", recentTables);
|
||||
|
||||
// 检查明天分区表状态
|
||||
PartitionTableStatus tomorrowStatus = checkTomorrowPartitionTable();
|
||||
stats.put("tomorrowStatus", tomorrowStatus);
|
||||
|
||||
} catch (Exception e) {
|
||||
logger.error("获取分区表统计信息失败: {}", e.getMessage());
|
||||
stats.put("error", e.getMessage());
|
||||
}
|
||||
|
||||
return stats;
|
||||
}
|
||||
/**
|
||||
* 检查未来多天的分区表状态
|
||||
*/
|
||||
public List<PartitionTableStatus> checkFuturePartitionTables(int days) {
|
||||
List<PartitionTableStatus> statusList = new ArrayList<>();
|
||||
|
||||
for (int i = 1; i <= days; i++) {
|
||||
LocalDate checkDate = LocalDate.now().plusDays(i);
|
||||
String tableName = "syslog_normal_data_" + checkDate.format(DATE_FORMATTER);
|
||||
|
||||
PartitionTableStatus status = new PartitionTableStatus();
|
||||
status.setCheckDate(checkDate);
|
||||
status.setTableName(tableName);
|
||||
status.setExists(isTableExists(tableName));
|
||||
status.setMessage(status.isExists() ? "已存在" : "未创建");
|
||||
|
||||
statusList.add(status);
|
||||
}
|
||||
|
||||
return statusList;
|
||||
}
|
||||
/**
|
||||
* 创建下个月的分区表
|
||||
*/
|
||||
public void createNextMonthPartitionTable() {
|
||||
try {
|
||||
// 获取下个月的第一天
|
||||
LocalDate nextMonthFirstDay = LocalDate.now()
|
||||
.plusMonths(1)
|
||||
.with(TemporalAdjusters.firstDayOfMonth());
|
||||
|
||||
// 创建下个月每天的分区表
|
||||
LocalDate currentDay = nextMonthFirstDay;
|
||||
LocalDate nextMonthLastDay = nextMonthFirstDay.with(TemporalAdjusters.lastDayOfMonth());
|
||||
|
||||
while (!currentDay.isAfter(nextMonthLastDay)) {
|
||||
createDailyPartitionTable(currentDay);
|
||||
currentDay = currentDay.plusDays(1);
|
||||
}
|
||||
|
||||
logger.info("成功创建下个月所有分区表");
|
||||
|
||||
} catch (Exception e) {
|
||||
logger.error("创建分区表失败: {}", e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 创建指定日期的分区表
|
||||
*/
|
||||
public boolean createDailyPartitionTable(LocalDate date) {
|
||||
try {
|
||||
String tableName = "syslog_normal_data_" + date.format(DATE_FORMATTER);
|
||||
String nextDay = date.plusDays(1).format(SQL_DATE_FORMATTER);
|
||||
String currentDay = date.format(SQL_DATE_FORMATTER);
|
||||
|
||||
String sql = String.format(
|
||||
"CREATE TABLE IF NOT EXISTS %s PARTITION OF syslog_normal_data " +
|
||||
"FOR VALUES FROM ('%s') TO ('%s')",
|
||||
tableName, currentDay, nextDay
|
||||
);
|
||||
|
||||
jdbcTemplate.execute(sql);
|
||||
logger.info("成功创建分区表: {}", tableName);
|
||||
return true;
|
||||
|
||||
} catch (Exception e) {
|
||||
logger.error("创建分区表失败,日期: {},错误: {}", date, e.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 检查表是否存在
|
||||
*/
|
||||
public boolean isTableExists(String tableName) {
|
||||
try {
|
||||
String sql = "SELECT EXISTS (SELECT FROM information_schema.tables WHERE table_schema = 'public' AND table_name = ?)";
|
||||
return jdbcTemplate.queryForObject(sql, Boolean.class, tableName);
|
||||
} catch (Exception e) {
|
||||
logger.error("检查表是否存在失败: {}", e.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取下个月需要创建的分区表数量
|
||||
*/
|
||||
public int getNextMonthPartitionCount() {
|
||||
LocalDate nextMonthFirstDay = LocalDate.now()
|
||||
.plusMonths(1)
|
||||
.with(TemporalAdjusters.firstDayOfMonth());
|
||||
LocalDate nextMonthLastDay = nextMonthFirstDay.with(TemporalAdjusters.lastDayOfMonth());
|
||||
return nextMonthLastDay.getDayOfMonth();
|
||||
}
|
||||
|
||||
/**
|
||||
* 分区表状态类
|
||||
*/
|
||||
public static class PartitionTableStatus {
|
||||
private LocalDate checkDate;
|
||||
private String tableName;
|
||||
private boolean exists;
|
||||
private boolean created;
|
||||
private String message;
|
||||
|
||||
// Getter and Setter 方法
|
||||
public LocalDate getCheckDate() { return checkDate; }
|
||||
public void setCheckDate(LocalDate checkDate) { this.checkDate = checkDate; }
|
||||
|
||||
public String getTableName() { return tableName; }
|
||||
public void setTableName(String tableName) { this.tableName = tableName; }
|
||||
|
||||
public boolean isExists() { return exists; }
|
||||
public void setExists(boolean exists) { this.exists = exists; }
|
||||
|
||||
public boolean isCreated() { return created; }
|
||||
public void setCreated(boolean created) { this.created = created; }
|
||||
|
||||
public String getMessage() { return message; }
|
||||
public void setMessage(String message) { this.message = message; }
|
||||
|
||||
public String getDisplayDate() {
|
||||
return checkDate != null ? checkDate.format(DISPLAY_FORMATTER) : "";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return String.format("PartitionTableStatus{date=%s, table=%s, exists=%s, created=%s, message='%s'}",
|
||||
getDisplayDate(), tableName, exists, created, message);
|
||||
}
|
||||
}
|
||||
}
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
package com.common.service;
|
||||
|
||||
|
||||
import com.baomidou.mybatisplus.extension.service.IService;
|
||||
import com.common.entity.SyslogNonNormalMessage;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 非标日志服务接口
|
||||
*/
|
||||
public interface SyslogNonNormalMessageService extends IService<SyslogNonNormalMessage> {
|
||||
|
||||
/**
|
||||
* 保存非标日志
|
||||
* @param message 日志对象
|
||||
* @return 是否成功
|
||||
*/
|
||||
boolean saveMessage(SyslogNonNormalMessage message);
|
||||
|
||||
/**
|
||||
* 批量保存非标日志
|
||||
* @param messages 日志列表
|
||||
* @return 插入数量
|
||||
*/
|
||||
int saveBatchMessages(List<SyslogNonNormalMessage> messages);
|
||||
|
||||
/**
|
||||
* 更新非标日志
|
||||
* @param message 日志对象
|
||||
* @return 是否成功
|
||||
*/
|
||||
boolean updateMessage(SyslogNonNormalMessage message);
|
||||
|
||||
/**
|
||||
* 逻辑删除非标日志
|
||||
* @param id 日志ID
|
||||
* @return 是否成功
|
||||
*/
|
||||
boolean deleteMessage(String id);
|
||||
|
||||
/**
|
||||
* 根据ID查询非标日志
|
||||
* @param id 日志ID
|
||||
* @return 日志对象
|
||||
*/
|
||||
SyslogNonNormalMessage getMessageById(String id);
|
||||
|
||||
/**
|
||||
* 根据条件查询非标日志
|
||||
* @param deviceId 设备ID
|
||||
* @param startTime 开始时间
|
||||
* @param endTime 结束时间
|
||||
* @param ruleResult 规则结果
|
||||
* @return 日志列表
|
||||
*/
|
||||
List<SyslogNonNormalMessage> queryMessages(Integer deviceId, LocalDateTime startTime,
|
||||
LocalDateTime endTime, String ruleResult);
|
||||
|
||||
|
||||
/**
|
||||
* 根据ID和创建时间批量查询非标日志
|
||||
*/
|
||||
List<SyslogNonNormalMessage> getMessagesByIdsAndCreatedAts(
|
||||
List<String> ids, List<String> createdAts);
|
||||
|
||||
/**
|
||||
* 根据ID列表批量查询非标日志
|
||||
*/
|
||||
List<SyslogNonNormalMessage> getMessagesByIds(List<String> ids);
|
||||
|
||||
/**
|
||||
* 批量更新del_flag字段
|
||||
*/
|
||||
int updateBatchDelFlag(List<SyslogNonNormalMessage> messages);
|
||||
|
||||
/**
|
||||
* 批量更新记录
|
||||
*/
|
||||
int updateBatch(List<SyslogNonNormalMessage> messages);
|
||||
}
|
||||
+132
@@ -0,0 +1,132 @@
|
||||
package com.common.service;
|
||||
|
||||
import com.common.entity.SyslogNormalData;
|
||||
import com.common.mapper.SyslogNormalDataMapper;
|
||||
import com.common.mapper.SyslogNormalAlarmMapper;
|
||||
|
||||
import com.influx.SyslogToInfluxApp;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import java.net.InetAddress;
|
||||
import java.net.UnknownHostException;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Service
|
||||
public class SyslogNormalDataService {
|
||||
private static final Logger logger = LoggerFactory.getLogger(SyslogNormalDataService.class);
|
||||
@Autowired
|
||||
private SyslogNormalDataMapper syslogNormalDataMapper;
|
||||
@Autowired
|
||||
private SyslogNormalAlarmMapper syslogNormalAlarmMapper;
|
||||
|
||||
|
||||
/**
|
||||
* 动态插入单条数据 - Map方式
|
||||
*/
|
||||
@Transactional
|
||||
public int insertDynamic(Map<String, Object> dataMap) {
|
||||
// 设置必要字段的默认值
|
||||
if (!dataMap.containsKey("created_at")) {
|
||||
dataMap.put("created_at", new java.util.Date());
|
||||
}
|
||||
if (!dataMap.containsKey("log_time")) {
|
||||
dataMap.put("log_time", new java.util.Date());
|
||||
}
|
||||
if (dataMap.containsKey("tc_hostip")) {
|
||||
if(!isValidIP(dataMap.get("tc_hostip").toString()))
|
||||
{
|
||||
String hostip=dataMap.get("tc_hostip").toString();
|
||||
logger.error("tc_hostip 字段非IP类型,值为:{},将赋值为null",hostip);
|
||||
dataMap.remove("tc_hostip");
|
||||
|
||||
}
|
||||
}
|
||||
//判断是否包含event_level (事件级别),区分告警日志和访问日志,分别进入不同的标准化数据表
|
||||
if (dataMap != null && dataMap.get("event_level") != null) {
|
||||
return syslogNormalAlarmMapper.insertDynamic(dataMap);
|
||||
}
|
||||
else
|
||||
return syslogNormalDataMapper.insertDynamic(dataMap);
|
||||
}
|
||||
|
||||
/**
|
||||
* 插入单条数据 - 实体类方式
|
||||
*/
|
||||
@Transactional
|
||||
public int insertByEntity(SyslogNormalData entity) {
|
||||
// 设置必要字段的默认值
|
||||
if (entity.getCreatedAt() == null) {
|
||||
entity.setCreatedAt(java.time.LocalDateTime.now());
|
||||
}
|
||||
if (entity.getLogTime() == null) {
|
||||
entity.setLogTime(java.time.LocalDateTime.now());
|
||||
}
|
||||
return syslogNormalDataMapper.insertByEntity(entity);
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量插入数据
|
||||
*/
|
||||
@Transactional
|
||||
public int batchInsert(List<Map<String, Object>> dataList) {
|
||||
if (dataList == null || dataList.isEmpty()) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
// 为每条数据设置必要字段的默认值
|
||||
for (Map<String, Object> data : dataList) {
|
||||
if (!data.containsKey("created_at")) {
|
||||
data.put("created_at", new java.util.Date());
|
||||
}
|
||||
if (!data.containsKey("log_time")) {
|
||||
data.put("log_time", new java.util.Date());
|
||||
}
|
||||
}
|
||||
return syslogNormalDataMapper.batchInsert(dataList);
|
||||
}
|
||||
|
||||
/**
|
||||
* 转换实体类为Map
|
||||
*/
|
||||
public Map<String, Object> convertEntityToMap(SyslogNormalData entity) {
|
||||
// 使用反射或对象映射工具将实体类转换为Map
|
||||
// 这里可以使用 Jackson 的 ObjectMapper 或 Spring 的 BeanUtils
|
||||
org.springframework.beans.BeanWrapper wrapper = new org.springframework.beans.BeanWrapperImpl(entity);
|
||||
java.util.Map<String, Object> result = new java.util.HashMap<>();
|
||||
|
||||
for (java.beans.PropertyDescriptor pd : wrapper.getPropertyDescriptors()) {
|
||||
String propertyName = pd.getName();
|
||||
if (!"class".equals(propertyName)) {
|
||||
Object value = wrapper.getPropertyValue(propertyName);
|
||||
if (value != null) {
|
||||
// 将驼峰命名转换为下划线命名
|
||||
String columnName = camelToSnake(propertyName);
|
||||
result.put(columnName, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
// 字符串是否为IP
|
||||
public static boolean isValidIP(String ipString) {
|
||||
try {
|
||||
InetAddress.getByName(ipString);
|
||||
// 额外检查:确保不是域名(简单检查)
|
||||
return ipString.matches(".*\\d+\\..*");
|
||||
} catch (UnknownHostException e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 驼峰命名转下划线命名
|
||||
*/
|
||||
private String camelToSnake(String str) {
|
||||
return str.replaceAll("([a-z])([A-Z])", "$1_$2").toLowerCase();
|
||||
}
|
||||
}
|
||||
+183
@@ -0,0 +1,183 @@
|
||||
package com.common.service;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.DatagramPacket;
|
||||
import java.net.DatagramSocket;
|
||||
import java.net.InetAddress;
|
||||
import java.net.SocketException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
import com.common.entity.*;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.net.Socket;
|
||||
import java.net.UnknownHostException;
|
||||
|
||||
@Service
|
||||
public class SyslogService {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(SyslogService.class);
|
||||
|
||||
/**
|
||||
* 发送syslog消息
|
||||
*/
|
||||
public boolean sendSyslogMessage(SyslogRequest request) {
|
||||
logger.info("开始发送syslog消息: IP={}, Port={}", request.getIp(), request.getPort());
|
||||
|
||||
try {
|
||||
//String syslogMessage = formatSyslogMessage(request);
|
||||
String syslogMessage =request.getLogContent();
|
||||
logger.debug("传入的syslog消息: {}", syslogMessage);
|
||||
|
||||
if ("UDP".equalsIgnoreCase(request.getProtocol())) {
|
||||
return sendUdpSyslog(request.getIp(), request.getPort(), syslogMessage);
|
||||
} else {
|
||||
return sendTcpSyslog(request.getIp(), request.getPort(), syslogMessage);
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
logger.error("发送syslog消息失败", e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化syslog消息
|
||||
*/
|
||||
private String formatSyslogMessage(SyslogRequest request) {
|
||||
// 计算PRI值 (Facility * 8 + Severity)
|
||||
int pri = calculatePri(request.getFacility(), request.getSeverity());
|
||||
|
||||
// 时间戳
|
||||
String timestamp = new SimpleDateFormat("MMM dd HH:mm:ss").format(new Date());
|
||||
|
||||
// 主机名
|
||||
String hostname = "myapp";
|
||||
|
||||
// 构建syslog消息
|
||||
return String.format("<%d>%s %s %s", pri, timestamp, hostname, request.getLogContent());
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算PRI值
|
||||
*/
|
||||
private int calculatePri(String facility, String severity) {
|
||||
int facilityValue = getFacilityValue(facility);
|
||||
int severityValue = getSeverityValue(severity);
|
||||
return facilityValue * 8 + severityValue;
|
||||
}
|
||||
|
||||
private int getFacilityValue(String facility) {
|
||||
switch (facility.toUpperCase()) {
|
||||
case "KERN": return 0;
|
||||
case "USER": return 1;
|
||||
case "MAIL": return 2;
|
||||
case "DAEMON": return 3;
|
||||
case "AUTH": return 4;
|
||||
case "SYSLOG": return 5;
|
||||
case "LPR": return 6;
|
||||
case "NEWS": return 7;
|
||||
case "UUCP": return 8;
|
||||
case "CRON": return 9;
|
||||
case "AUTHPRIV": return 10;
|
||||
case "FTP": return 11;
|
||||
case "LOCAL0": return 16;
|
||||
case "LOCAL1": return 17;
|
||||
case "LOCAL2": return 18;
|
||||
case "LOCAL3": return 19;
|
||||
case "LOCAL4": return 20;
|
||||
case "LOCAL5": return 21;
|
||||
case "LOCAL6": return 22;
|
||||
case "LOCAL7": return 23;
|
||||
default: return 1; // 默认USER
|
||||
}
|
||||
}
|
||||
|
||||
private int getSeverityValue(String severity) {
|
||||
switch (severity.toUpperCase()) {
|
||||
case "EMERG": return 0;
|
||||
case "ALERT": return 1;
|
||||
case "CRIT": return 2;
|
||||
case "ERR": return 3;
|
||||
case "WARNING": return 4;
|
||||
case "NOTICE": return 5;
|
||||
case "INFO": return 6;
|
||||
case "DEBUG": return 7;
|
||||
default: return 6; // 默认INFO
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过UDP发送syslog消息
|
||||
*/
|
||||
private boolean sendUdpSyslog(String ip, int port, String message) {
|
||||
try (DatagramSocket socket = new DatagramSocket()) {
|
||||
InetAddress address = InetAddress.getByName(ip);
|
||||
byte[] buffer = message.getBytes();
|
||||
DatagramPacket packet = new DatagramPacket(buffer, buffer.length, address, port);
|
||||
socket.send(packet);
|
||||
logger.info("Syslog消息发送成功");
|
||||
return true;
|
||||
} catch (SocketException e) {
|
||||
logger.error("创建Socket失败", e);
|
||||
return false;
|
||||
} catch (IOException e) {
|
||||
logger.error("发送数据失败", e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过TCP发送syslog消息
|
||||
*/
|
||||
private boolean sendTcpSyslog(String ip, int port, String message) {
|
||||
Socket socket = null;
|
||||
OutputStream outputStream = null;
|
||||
|
||||
try {
|
||||
// 创建TCP socket连接
|
||||
socket = new Socket(ip, port);
|
||||
|
||||
// 设置连接超时和读取超时(可选)
|
||||
socket.setSoTimeout(5000); // 5秒超时
|
||||
|
||||
// 获取输出流
|
||||
outputStream = socket.getOutputStream();
|
||||
|
||||
// 发送消息,TCP通常需要以换行符结束
|
||||
byte[] buffer = (message + "\n").getBytes();
|
||||
outputStream.write(buffer);
|
||||
outputStream.flush(); // 确保数据发送
|
||||
|
||||
logger.info("TCP Syslog消息发送成功: {}:{}", ip, port);
|
||||
return true;
|
||||
|
||||
} catch (UnknownHostException e) {
|
||||
logger.error("无法解析主机地址: {}", ip, e);
|
||||
return false;
|
||||
} catch (IOException e) {
|
||||
logger.error("TCP连接或发送数据失败: {}:{}", ip, port, e);
|
||||
return false;
|
||||
} finally {
|
||||
// 关闭资源
|
||||
if (outputStream != null) {
|
||||
try {
|
||||
outputStream.close();
|
||||
} catch (IOException e) {
|
||||
logger.warn("关闭输出流时发生异常", e);
|
||||
}
|
||||
}
|
||||
if (socket != null) {
|
||||
try {
|
||||
socket.close();
|
||||
} catch (IOException e) {
|
||||
logger.warn("关闭socket时发生异常", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+161
@@ -0,0 +1,161 @@
|
||||
package com.common.service.impl;
|
||||
|
||||
|
||||
import com.common.entity.DeviceReceiveLog;
|
||||
import com.common.mapper.DeviceReceiveLogMapper;
|
||||
import com.common.service.DeviceReceiveLogService;
|
||||
import com.github.pagehelper.PageHelper;
|
||||
import com.github.pagehelper.PageInfo;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class DeviceReceiveLogServiceImpl implements DeviceReceiveLogService {
|
||||
|
||||
private final DeviceReceiveLogMapper deviceReceiveLogMapper;
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public Long insertLog(DeviceReceiveLog log) {
|
||||
// 设置默认时间
|
||||
if (log.getCreatedAt() == null) {
|
||||
log.setCreatedAt(LocalDateTime.now());
|
||||
}
|
||||
|
||||
if (log.getReceiveTimeStr() == null && log.getReceiveTime() != null) {
|
||||
log.setReceiveTimeStr(log.getReceiveTime().toString());
|
||||
}
|
||||
|
||||
deviceReceiveLogMapper.insert(log);
|
||||
// log.info("插入设备接收日志成功,ID: {}", log.getId());
|
||||
return log.getId();
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public int batchInsertLogs(List<DeviceReceiveLog> logs) {
|
||||
if (logs == null || logs.isEmpty()) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
// 批量处理,每1000条提交一次
|
||||
int batchSize = 1000;
|
||||
int totalInserted = 0;
|
||||
|
||||
for (int i = 0; i < logs.size(); i += batchSize) {
|
||||
int end = Math.min(i + batchSize, logs.size());
|
||||
List<DeviceReceiveLog> batchList = logs.subList(i, end);
|
||||
|
||||
// 设置默认值
|
||||
batchList.forEach(log -> {
|
||||
if (log.getCreatedAt() == null) {
|
||||
log.setCreatedAt(LocalDateTime.now());
|
||||
}
|
||||
if (log.getReceiveTimeStr() == null && log.getReceiveTime() != null) {
|
||||
log.setReceiveTimeStr(log.getReceiveTime().toString());
|
||||
}
|
||||
});
|
||||
|
||||
int inserted = deviceReceiveLogMapper.batchInsert(batchList);
|
||||
totalInserted += inserted;
|
||||
log.info("批量插入进度: {}/{}", end, logs.size());
|
||||
}
|
||||
|
||||
return totalInserted;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DeviceReceiveLog getById(Long id) {
|
||||
return deviceReceiveLogMapper.selectById(id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<DeviceReceiveLog> getByDeviceId(Integer deviceId) {
|
||||
return deviceReceiveLogMapper.selectByDeviceId(deviceId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<DeviceReceiveLog> getByCollectId(Integer collectId) {
|
||||
return deviceReceiveLogMapper.selectByCollectId(collectId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<DeviceReceiveLog> getByTimeRange(LocalDateTime startTime, LocalDateTime endTime) {
|
||||
if (startTime == null || endTime == null) {
|
||||
throw new IllegalArgumentException("时间范围不能为空");
|
||||
}
|
||||
if (startTime.isAfter(endTime)) {
|
||||
throw new IllegalArgumentException("开始时间不能晚于结束时间");
|
||||
}
|
||||
return deviceReceiveLogMapper.selectByTimeRange(startTime, endTime);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<DeviceReceiveLog> getByCondition(DeviceReceiveLog condition) {
|
||||
return deviceReceiveLogMapper.selectByCondition(condition);
|
||||
}
|
||||
|
||||
@Override
|
||||
public PageInfo<DeviceReceiveLog> getByConditionPage(DeviceReceiveLog condition, Integer pageNum, Integer pageSize) {
|
||||
if (pageNum == null || pageNum < 1) {
|
||||
pageNum = 1;
|
||||
}
|
||||
if (pageSize == null || pageSize < 1) {
|
||||
pageSize = 10;
|
||||
}
|
||||
|
||||
PageHelper.startPage(pageNum, pageSize);
|
||||
List<DeviceReceiveLog> list = deviceReceiveLogMapper.selectByCondition(condition);
|
||||
return new PageInfo<>(list);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Long countByCondition(DeviceReceiveLog condition) {
|
||||
return deviceReceiveLogMapper.countByCondition(condition);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Map<String, Object>> getDeviceLogStatistics() {
|
||||
return deviceReceiveLogMapper.countByDeviceGroup();
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public int deleteOldLogs(LocalDateTime beforeTime) {
|
||||
if (beforeTime == null) {
|
||||
throw new IllegalArgumentException("删除时间点不能为空");
|
||||
}
|
||||
|
||||
|
||||
LocalDateTime endTime = LocalDateTime.now().minusDays(7); // 默认保留7天
|
||||
if (beforeTime.isAfter(endTime)) {
|
||||
log.warn("删除时间点{}晚于默认保留时间{},使用默认时间", beforeTime, endTime);
|
||||
beforeTime = endTime;
|
||||
}
|
||||
|
||||
|
||||
int deleted = deviceReceiveLogMapper.deleteByTimeRange(
|
||||
LocalDateTime.of(2025, 11, 1, 0, 0,0) , // 默认2025年11月
|
||||
beforeTime
|
||||
);
|
||||
|
||||
log.info("删除{}天前的日志,共删除{}条", beforeTime, deleted);
|
||||
return deleted;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<DeviceReceiveLog> getRecentLogs(Integer limit) {
|
||||
if (limit == null || limit < 1) {
|
||||
limit = 50; // 默认返回50条
|
||||
}
|
||||
return deviceReceiveLogMapper.selectRecent(limit);
|
||||
}
|
||||
}
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
package com.common.service.impl;
|
||||
|
||||
|
||||
import com.common.entity.DmColumn;
|
||||
import com.common.mapper.DmColumnMapper;
|
||||
import com.common.mapper.DmNormalizeRuleMapper;
|
||||
import com.common.service.DmColumnService;
|
||||
import com.common.service.DmNormalizeRuleService;
|
||||
import com.common.util.MyBatisUtil;
|
||||
import org.apache.ibatis.session.SqlSession;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
//import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Service
|
||||
public class DmColumnServiceImpl implements DmColumnService {
|
||||
private static final Logger logger = LoggerFactory.getLogger(DmColumnServiceImpl.class);
|
||||
|
||||
@Autowired
|
||||
private DmColumnMapper dmColumnMapper;
|
||||
|
||||
@Override
|
||||
public List<DmColumn> findAll() {
|
||||
return dmColumnMapper.findAll();
|
||||
}
|
||||
|
||||
@Override
|
||||
public DmColumn findById(Long id) {
|
||||
|
||||
try (SqlSession sqlSession = MyBatisUtil.getSqlSession()) {
|
||||
logger.info(" begin DmColumnServiceImpl->findById" );
|
||||
dmColumnMapper = sqlSession.getMapper(DmColumnMapper.class);
|
||||
return dmColumnMapper.findById(id);
|
||||
} catch (Exception e) {
|
||||
logger.error("DmColumnServiceImpl findById MyBatisUtil getSqlSession 异常", e);
|
||||
}
|
||||
logger.error("DmColumn is null" );
|
||||
return null;
|
||||
|
||||
|
||||
}
|
||||
@Override
|
||||
public DmColumn findByDmColumnId(Long id) {
|
||||
return dmColumnMapper.findById(id);
|
||||
}
|
||||
@Override
|
||||
public DmColumn findByName(String name) {
|
||||
return dmColumnMapper.findByName(name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<DmColumn> findByDisplayName(String displayName) {
|
||||
return dmColumnMapper.findByDisplayName(displayName);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<DmColumn> findByIsBuiltIn(Boolean isBuiltIn) {
|
||||
return dmColumnMapper.findByIsBuiltIn(isBuiltIn);
|
||||
}
|
||||
|
||||
@Override
|
||||
//@Transactional
|
||||
public int insert(DmColumn dmColumn) {
|
||||
return dmColumnMapper.insert(dmColumn);
|
||||
}
|
||||
|
||||
@Override
|
||||
//@Transactional
|
||||
public int batchInsert(List<DmColumn> dmColumns) {
|
||||
return dmColumnMapper.batchInsert(dmColumns);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<DmColumn> findByCondition(DmColumn condition) {
|
||||
return dmColumnMapper.findByCondition(condition);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Long count() {
|
||||
return dmColumnMapper.count();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Map<String, Object>> selectAllNormal()
|
||||
{
|
||||
return dmColumnMapper.selectAllNormal();
|
||||
}
|
||||
|
||||
}
|
||||
+219
@@ -0,0 +1,219 @@
|
||||
package com.common.service.impl;
|
||||
|
||||
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
import com.common.entity.SyslogNonNormalMessage;
|
||||
import com.common.mapper.SyslogNonNormalMessageMapper;
|
||||
import com.common.service.SyslogNonNormalMessageService;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* 非标日志服务实现类
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
public class SyslogNonNormalMessageServiceImpl
|
||||
extends ServiceImpl<SyslogNonNormalMessageMapper, SyslogNonNormalMessage>
|
||||
implements SyslogNonNormalMessageService {
|
||||
|
||||
@Autowired
|
||||
private SyslogNonNormalMessageMapper messageMapper;
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public boolean saveMessage(SyslogNonNormalMessage message) {
|
||||
try {
|
||||
// 设置ID(如果未提供)
|
||||
if (message.getId() == null || message.getId().isEmpty()) {
|
||||
message.setId(generateMessageId());
|
||||
}
|
||||
|
||||
// 设置默认值
|
||||
if (message.getCreatedAt() == null) {
|
||||
// 设置为当前UTC时间
|
||||
message.setCreatedAt(OffsetDateTime.now(ZoneOffset.UTC));
|
||||
}
|
||||
|
||||
if (message.getCreateTime() == null) {
|
||||
message.setCreateTime(LocalDateTime.now());
|
||||
}
|
||||
|
||||
if (message.getUpdateTime() == null) {
|
||||
message.setUpdateTime(LocalDateTime.now());
|
||||
}
|
||||
|
||||
if (message.getDelFlag() == null || message.getDelFlag().isEmpty()) {
|
||||
message.setDelFlag("0");
|
||||
}
|
||||
|
||||
if (message.getRuleResult() == null || message.getRuleResult().isEmpty()) {
|
||||
message.setRuleResult("FAIL");
|
||||
}
|
||||
|
||||
if (message.getTenantId() == null || message.getTenantId().isEmpty()) {
|
||||
message.setTenantId("000000");
|
||||
}
|
||||
|
||||
// 执行插入
|
||||
return this.save(message);
|
||||
} catch (Exception e) {
|
||||
log.error("保存非标日志失败: {}", e.getMessage(), e);
|
||||
throw new RuntimeException("保存非标日志失败", e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public int saveBatchMessages(List<SyslogNonNormalMessage> messages) {
|
||||
if (messages == null || messages.isEmpty()) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
try {
|
||||
// 为每条记录设置默认值
|
||||
for (SyslogNonNormalMessage message : messages) {
|
||||
if (message.getId() == null || message.getId().isEmpty()) {
|
||||
message.setId(generateMessageId());
|
||||
}
|
||||
|
||||
if (message.getCreatedAt() == null) {
|
||||
message.setCreatedAt(OffsetDateTime.now(ZoneOffset.UTC));
|
||||
}
|
||||
|
||||
if (message.getCreateTime() == null) {
|
||||
message.setCreateTime(LocalDateTime.now());
|
||||
}
|
||||
|
||||
if (message.getUpdateTime() == null) {
|
||||
message.setUpdateTime(LocalDateTime.now());
|
||||
}
|
||||
|
||||
if (message.getDelFlag() == null || message.getDelFlag().isEmpty()) {
|
||||
message.setDelFlag("0");
|
||||
}
|
||||
|
||||
if (message.getRuleResult() == null || message.getRuleResult().isEmpty()) {
|
||||
message.setRuleResult("FAIL");
|
||||
}
|
||||
|
||||
if (message.getTenantId() == null || message.getTenantId().isEmpty()) {
|
||||
message.setTenantId("000000");
|
||||
}
|
||||
}
|
||||
|
||||
// 批量插入
|
||||
return messageMapper.batchInsert(messages);
|
||||
} catch (Exception e) {
|
||||
log.error("批量保存非标日志失败: {}", e.getMessage(), e);
|
||||
throw new RuntimeException("批量保存非标日志失败", e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public boolean updateMessage(SyslogNonNormalMessage message) {
|
||||
try {
|
||||
// 设置更新时间
|
||||
message.setUpdateTime(LocalDateTime.now());
|
||||
|
||||
// 构建更新条件
|
||||
LambdaQueryWrapper<SyslogNonNormalMessage> wrapper = new LambdaQueryWrapper<>();
|
||||
wrapper.eq(SyslogNonNormalMessage::getId, message.getId())
|
||||
.eq(SyslogNonNormalMessage::getDelFlag, "0");
|
||||
|
||||
return this.update(message, wrapper);
|
||||
} catch (Exception e) {
|
||||
log.error("更新非标日志失败: {}", e.getMessage(), e);
|
||||
throw new RuntimeException("更新非标日志失败", e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public boolean deleteMessage(String id) {
|
||||
try {
|
||||
// 逻辑删除,设置del_flag为1
|
||||
return messageMapper.logicalDelete(id) > 0;
|
||||
} catch (Exception e) {
|
||||
log.error("删除非标日志失败: {}", e.getMessage(), e);
|
||||
throw new RuntimeException("删除非标日志失败", e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public SyslogNonNormalMessage getMessageById(String id) {
|
||||
try {
|
||||
LambdaQueryWrapper<SyslogNonNormalMessage> wrapper = new LambdaQueryWrapper<>();
|
||||
wrapper.eq(SyslogNonNormalMessage::getId, id)
|
||||
.eq(SyslogNonNormalMessage::getDelFlag, "0");
|
||||
|
||||
return this.getOne(wrapper);
|
||||
} catch (Exception e) {
|
||||
log.error("查询非标日志失败: {}", e.getMessage(), e);
|
||||
throw new RuntimeException("查询非标日志失败", e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<SyslogNonNormalMessage> queryMessages(Integer deviceId, LocalDateTime startTime,
|
||||
LocalDateTime endTime, String ruleResult) {
|
||||
try {
|
||||
return messageMapper.findByTimeRange(startTime, endTime);
|
||||
} catch (Exception e) {
|
||||
log.error("查询非标日志失败: {}", e.getMessage(), e);
|
||||
throw new RuntimeException("查询非标日志失败", e);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 根据ID和创建时间批量查询非标日志
|
||||
*/
|
||||
@Override
|
||||
public List<SyslogNonNormalMessage> getMessagesByIdsAndCreatedAts(
|
||||
List<String> ids, List<String> createdAts) {
|
||||
return messageMapper.getMessagesByIdsAndCreatedAts(ids, createdAts);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据ID列表批量查询非标日志
|
||||
*/
|
||||
@Override
|
||||
public List<SyslogNonNormalMessage> getMessagesByIds(List<String> ids) {
|
||||
return messageMapper.getMessagesByIds(ids);
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量更新del_flag字段
|
||||
*/
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public int updateBatchDelFlag(List<SyslogNonNormalMessage> messages) {
|
||||
return messageMapper.updateBatchDelFlag(messages);
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量更新记录
|
||||
*/
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public int updateBatch(List<SyslogNonNormalMessage> messages) {
|
||||
return messageMapper.updateBatch(messages);
|
||||
}
|
||||
/**
|
||||
* 生成消息ID
|
||||
*/
|
||||
private String generateMessageId() {
|
||||
// 使用UUID生成唯一ID
|
||||
return UUID.randomUUID().toString().replace("-", "").substring(0, 20);
|
||||
}
|
||||
}
|
||||
+323
@@ -0,0 +1,323 @@
|
||||
package com.common.util;
|
||||
|
||||
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.JSONArray;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.common.entity.SyslogNormalData;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
public class AlgorithmResultParser {
|
||||
|
||||
private static final DateTimeFormatter[] DATE_FORMATTERS = {
|
||||
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"),
|
||||
DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss"),
|
||||
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"),
|
||||
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss"),
|
||||
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS")
|
||||
};
|
||||
|
||||
/**
|
||||
* 构建示例JSON对应的newLogs
|
||||
*/
|
||||
public List<SyslogNormalData> buildNewLogsFromExample() {
|
||||
String exampleJson = "[\n" +
|
||||
" {\n" +
|
||||
" \"_index\": \"es:skyeye-weblog-2025.09.30\",\n" +
|
||||
" \"access_time\": \"2025-09-30 12:05:00\",\n" +
|
||||
" \"dip\": \"10.20.30.51\",\n" +
|
||||
" \"dname\": \"网页木马流量\",\n" +
|
||||
" \"dtype\": \"疑似木马活动\",\n" +
|
||||
" \"host\": \"\",\n" +
|
||||
" \"log_id\": \"hidden-002\",\n" +
|
||||
" \"origin_field\": \"匹配到文件名: shell.php:.jpg 与 匹配到恶意请求: exec=dir\",\n" +
|
||||
" \"reason\": \"源IP 203.0.113.51 访问 目的IP 10.20.30.51 异常,入度=0, 出度=0, 独立访客=1,匹配到文件名: shell.php:.jpg,匹配到恶意请求: exec=dir\",\n" +
|
||||
" \"referer\": \"\",\n" +
|
||||
" \"sip\": \"203.0.113.51\",\n" +
|
||||
" \"status_code\": 200,\n" +
|
||||
" \"url\": \"/admin/shell.php:.jpg\"\n" +
|
||||
" }\n" +
|
||||
"]";
|
||||
|
||||
return parseJsonToLogs(exampleJson);
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析JSON字符串为SyslogNormalData列表
|
||||
*/
|
||||
public List<SyslogNormalData> parseJsonToLogs(String jsonStr) {
|
||||
List<SyslogNormalData> logs = new ArrayList<>();
|
||||
|
||||
try {
|
||||
JSONArray jsonArray = JSON.parseArray(jsonStr);
|
||||
|
||||
for (int i = 0; i < jsonArray.size(); i++) {
|
||||
JSONObject jsonObj = jsonArray.getJSONObject(i);
|
||||
SyslogNormalData logData = convertJsonObject(jsonObj);
|
||||
if (logData != null) {
|
||||
logs.add(logData);
|
||||
}
|
||||
}
|
||||
|
||||
log.info("成功解析 {} 条日志数据", logs.size());
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("解析JSON失败: {}", e.getMessage(), e);
|
||||
}
|
||||
|
||||
return logs;
|
||||
}
|
||||
|
||||
/**
|
||||
* 转换单个JSON对象
|
||||
*/
|
||||
private SyslogNormalData convertJsonObject(JSONObject jsonObj) {
|
||||
try {
|
||||
SyslogNormalData logData = new SyslogNormalData();
|
||||
|
||||
// 基础字段
|
||||
logData.setId(getString(jsonObj, "log_id", UUID.randomUUID().toString()));
|
||||
logData.setSyslogUuid(UUID.randomUUID().toString());
|
||||
logData.setLogId(getString(jsonObj, "log_id"));
|
||||
|
||||
// 时间字段
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
logData.setCreatedAt(now);
|
||||
logData.setEventDate(now);
|
||||
|
||||
String accessTime = getString(jsonObj, "access_time");
|
||||
if (accessTime != null && !accessTime.isEmpty()) {
|
||||
LocalDateTime logTime = parseDateTime(accessTime);
|
||||
logData.setLogTime(logTime != null ? logTime : now);
|
||||
} else {
|
||||
logData.setLogTime(now);
|
||||
}
|
||||
|
||||
// IP字段
|
||||
logData.setSrcIp(getString(jsonObj, "sip"));
|
||||
logData.setDestIp(getString(jsonObj, "dip"));
|
||||
logData.setSrcIpStr(getString(jsonObj, "sip"));
|
||||
logData.setDestIpStr(getString(jsonObj, "dip"));
|
||||
|
||||
// HTTP字段
|
||||
logData.setHttpUrl(getString(jsonObj, "url"));
|
||||
logData.setHttpHost(getString(jsonObj, "host"));
|
||||
logData.setHttpReferer(getString(jsonObj, "referer"));
|
||||
logData.setHttpStatusCode(getLong(jsonObj, "status_code", 200L));
|
||||
logData.setHttpMethod("GET");
|
||||
|
||||
// 安全检测字段
|
||||
logData.setAttackResult(1);
|
||||
logData.setEventCategory(1);
|
||||
logData.setEventType(1);
|
||||
logData.setEventLevel(3);
|
||||
logData.setEngineType(getString(jsonObj, "dtype"));
|
||||
logData.setOriginRuleName(getString(jsonObj, "dname"));
|
||||
logData.setOriginEventName(getString(jsonObj, "dname"));
|
||||
logData.setDescription(getString(jsonObj, "reason"));
|
||||
logData.setOriginAttackResult(getString(jsonObj, "origin_field"));
|
||||
|
||||
// 协议
|
||||
logData.setProto("http");
|
||||
logData.setSyslogTopic("algorithm_detection");
|
||||
|
||||
// 从origin_field提取额外信息
|
||||
String originField = getString(jsonObj, "origin_field");
|
||||
if (originField != null) {
|
||||
extractAdditionalInfo(logData, originField);
|
||||
}
|
||||
|
||||
// 设置索引信息
|
||||
logData.setId(getString(jsonObj, "_index"));
|
||||
|
||||
return logData;
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("转换JSON对象失败: {}", e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 从origin_field提取额外信息
|
||||
*/
|
||||
private void extractAdditionalInfo(SyslogNormalData logData, String originField) {
|
||||
// 提取文件名
|
||||
if (originField.contains("文件名:")) {
|
||||
String[] parts = originField.split("文件名:");
|
||||
if (parts.length > 1) {
|
||||
String fileInfo = parts[1].split("与")[0].trim();
|
||||
logData.setFileName(fileInfo);
|
||||
logData.setFileType(determineFileType(fileInfo));
|
||||
|
||||
if (fileInfo.toLowerCase().contains("shell")) {
|
||||
logData.setWebshellType("疑似Webshell");
|
||||
logData.setBackdoorType("网页后门");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 提取恶意请求
|
||||
if (originField.contains("恶意请求:")) {
|
||||
String[] parts = originField.split("恶意请求:");
|
||||
if (parts.length > 1) {
|
||||
String maliciousRequest = parts[1].trim();
|
||||
logData.setCmdline(maliciousRequest);
|
||||
logData.setShellCmdline(maliciousRequest);
|
||||
logData.setDetail(maliciousRequest);
|
||||
|
||||
// 检查是否是命令执行
|
||||
if (maliciousRequest.contains("exec=") ||
|
||||
maliciousRequest.contains("cmd=") ||
|
||||
maliciousRequest.contains("system(")) {
|
||||
logData.setOriginAttackAction("命令执行");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据文件名确定文件类型
|
||||
*/
|
||||
private String determineFileType(String fileName) {
|
||||
if (fileName == null) return "";
|
||||
|
||||
fileName = fileName.toLowerCase();
|
||||
|
||||
if (fileName.endsWith(".php") || fileName.contains(".php:")) {
|
||||
return "php";
|
||||
} else if (fileName.endsWith(".jsp")) {
|
||||
return "jsp";
|
||||
} else if (fileName.endsWith(".asp") || fileName.endsWith(".aspx")) {
|
||||
return "asp";
|
||||
} else if (fileName.endsWith(".jpg") || fileName.endsWith(".jpeg")) {
|
||||
return "image";
|
||||
} else if (fileName.endsWith(".png")) {
|
||||
return "image";
|
||||
} else if (fileName.endsWith(".gif")) {
|
||||
return "image";
|
||||
} else if (fileName.endsWith(".bmp")) {
|
||||
return "image";
|
||||
} else if (fileName.endsWith(".exe")) {
|
||||
return "executable";
|
||||
} else if (fileName.endsWith(".dll")) {
|
||||
return "library";
|
||||
} else if (fileName.endsWith(".bat") || fileName.endsWith(".cmd")) {
|
||||
return "batch";
|
||||
} else if (fileName.endsWith(".sh")) {
|
||||
return "shell";
|
||||
} else if (fileName.endsWith(".py")) {
|
||||
return "python";
|
||||
} else if (fileName.endsWith(".js")) {
|
||||
return "javascript";
|
||||
} else if (fileName.endsWith(".html") || fileName.endsWith(".htm")) {
|
||||
return "html";
|
||||
} else if (fileName.endsWith(".css")) {
|
||||
return "css";
|
||||
} else if (fileName.endsWith(".xml")) {
|
||||
return "xml";
|
||||
} else if (fileName.endsWith(".json")) {
|
||||
return "json";
|
||||
} else if (fileName.endsWith(".txt")) {
|
||||
return "text";
|
||||
} else if (fileName.endsWith(".pdf")) {
|
||||
return "pdf";
|
||||
} else if (fileName.endsWith(".doc") || fileName.endsWith(".docx")) {
|
||||
return "document";
|
||||
} else if (fileName.endsWith(".xls") || fileName.endsWith(".xlsx")) {
|
||||
return "spreadsheet";
|
||||
} else if (fileName.endsWith(".zip") || fileName.endsWith(".rar") ||
|
||||
fileName.endsWith(".7z") || fileName.endsWith(".tar") ||
|
||||
fileName.endsWith(".gz")) {
|
||||
return "archive";
|
||||
} else {
|
||||
return "unknown";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析时间字符串
|
||||
*/
|
||||
private LocalDateTime parseDateTime(String timeStr) {
|
||||
if (timeStr == null || timeStr.isEmpty()) {
|
||||
return LocalDateTime.now();
|
||||
}
|
||||
|
||||
for (DateTimeFormatter formatter : DATE_FORMATTERS) {
|
||||
try {
|
||||
return LocalDateTime.parse(timeStr, formatter);
|
||||
} catch (Exception e) {
|
||||
// 继续尝试下一个格式
|
||||
}
|
||||
}
|
||||
|
||||
// 如果所有格式都失败,尝试其他格式
|
||||
try {
|
||||
// 尝试处理带有时区的时间格式
|
||||
if (timeStr.contains("T")) {
|
||||
return LocalDateTime.parse(timeStr,
|
||||
DateTimeFormatter.ISO_LOCAL_DATE_TIME);
|
||||
}
|
||||
|
||||
// 尝试处理日期部分
|
||||
if (timeStr.length() >= 10) {
|
||||
String datePart = timeStr.substring(0, 10);
|
||||
return LocalDateTime.parse(datePart + "T00:00:00");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.warn("无法解析时间字符串: {}, 使用当前时间", timeStr);
|
||||
}
|
||||
|
||||
return LocalDateTime.now();
|
||||
}
|
||||
|
||||
/**
|
||||
* 安全获取字符串字段
|
||||
*/
|
||||
private String getString(JSONObject jsonObj, String key) {
|
||||
return getString(jsonObj, key, "");
|
||||
}
|
||||
|
||||
private String getString(JSONObject jsonObj, String key, String defaultValue) {
|
||||
try {
|
||||
String value = jsonObj.getString(key);
|
||||
return value != null ? value : defaultValue;
|
||||
} catch (Exception e) {
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 安全获取Long字段
|
||||
*/
|
||||
private Long getLong(JSONObject jsonObj, String key, Long defaultValue) {
|
||||
try {
|
||||
Long value = jsonObj.getLong(key);
|
||||
return value != null ? value : defaultValue;
|
||||
} catch (Exception e) {
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 安全获取Integer字段
|
||||
*/
|
||||
private Integer getInteger(JSONObject jsonObj, String key, Integer defaultValue) {
|
||||
try {
|
||||
Integer value = jsonObj.getInteger(key);
|
||||
return value != null ? value : defaultValue;
|
||||
} catch (Exception e) {
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,351 @@
|
||||
package com.common.util;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.JsonNodeType;
|
||||
import com.common.entity.*;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import java.util.*;
|
||||
import java.util.Map.Entry;
|
||||
import org.json.JSONObject;
|
||||
import org.json.JSONArray;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class JsonParser {
|
||||
|
||||
private static final ObjectMapper objectMapper = new ObjectMapper();
|
||||
private static final Logger logger = LoggerFactory.getLogger(JsonParser.class);
|
||||
|
||||
public static void main(String[] args) {
|
||||
String logMessage = "<15>Sep 24 12:06:59 LAPTOP-ARDUR3N0 <15>2025-09-24T11:52:26Z 5f46d3be75e1 supermario 128 honeypot_event - {\"source\":\"honeypot\",\"id\":\"f6a13c35-bf9d-4da6-a181-50ce23e7ef6a\",\"start_time\":\"2023-09-03T11:07:02.50167643Z\",\"time\":\"2023-09-03T11:16:18.883885281Z\",\"risk_level\":4,\"connection\":\"b18f3fbe-3fbf-4495-815f-ff26f6fb0bdf\",\"file_info\":null,\"extra\":{\"payload\":{\"format\":\"line\",\"name\":{\"cn\":\"攻击载荷\",\"en\":\"payload\"},\"value\":\"\"},\"uid\":{\"format\":\"line\",\"name\":{\"cn\":\"\",\"en\":\"\"},\"uid\":\"b4cbc73c-25d0-4429-ae1b-a856cdf1a651\",\"value\":\"\"}},\"type\":\"WEB_ATTACK_SCANNER\",\"agent_sn\":\"caa7da42-0cca-4cb1-b501-1f1eb2b588d5\",\"agent_name\":\" 教育局蜜罐探针\",\"honeypot_id\":\"11a9ac6bdf38ae2aaa49ec4f1b4a921bff71952cb9f175bdd8ee1f0497057bc6\",\"honeypot_name\":\"茂名市中小学管理平台管理后台\",\"src_ip\":\"117.50.189.7\",\"src_port\":58512,\"src_mac\":\"\",\"dest_ip\":\"192.168.222.2\",\"dest_port\":9200,\"proxy_ip\":null,\"node\":\"WRx3\"}";
|
||||
System.out.println(logMessage);
|
||||
try {
|
||||
XdrHoneypot xdrHoneypot = parseLogMessageToXdrHoneypot(logMessage);
|
||||
System.out.println("解析成功!");
|
||||
System.out.println(xdrHoneypot);
|
||||
} catch (Exception e) {
|
||||
System.err.println("解析失败: " + e.getMessage());
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
// 多层嵌套 JSON
|
||||
String complexJson = "{\"source\":\"honeypot1\",\"id\":\"f6a13c35-bf9d-4da6-a181-50ce23e7ef6a\",\"start_time\":\"2023-09-03T11:07:02.50167643Z\",\"time\":\"2023-09-03T11:16:18.883885281Z\",\"risk_level\":4,\"connection\":\"b18f3fbe-3fbf-4495-815f-ff26f6fb0bdf\",\"file_info\":null,\"extra\":{\"payload\":{\"format\":\"line\",\"name\":{\"cn\":\"攻击载荷\",\"en\":\"payload\"},\"value\":\"\"},\"uid\":{\"format\":\"line\",\"name\":{\"cn\":\"\",\"en\":\"\"},\"uid\":\"b4cbc73c-25d0-4429-ae1b-a856cdf1a651\",\"value\":\"\"}},\"type\":\"WEB_ATTACK_SCANNER\",\"agent_sn\":\"caa7da42-0cca-4cb1-b501-1f1eb2b588d5\",\"agent_name\":\" 教育局蜜罐探针\",\"honeypot_id\":\"11a9ac6bdf38ae2aaa49ec4f1b4a921bff71952cb9f175bdd8ee1f0497057bc6\",\"honeypot_name\":\"茂名市中小学管理平台管理后台\",\"src_ip\":\"117.50.189.7\",\"src_port\":58512,\"src_mac\":\"\",\"dest_ip\":\"192.168.222.2\",\"dest_port\":9200,\"proxy_ip\":null,\"node\":\"WRx3\"}";
|
||||
|
||||
System.out.println("=== 扁平化 Map 解析结果 ===");
|
||||
Map<String, Object> flatMap = parseJsonToFlatMap(complexJson);
|
||||
flatMap.forEach((key, value) -> System.out.println(key + " = " + value));
|
||||
|
||||
System.out.println("\n=== 嵌套结构 Map 解析结果 ===");
|
||||
Map<String, Object> nestedMap = parseJsonToNestedMap(complexJson);
|
||||
printMap(nestedMap);
|
||||
|
||||
System.out.println("\n=== 特定值访问示例 ===");
|
||||
// 访问特定值
|
||||
System.out.println("extra.payload.format: " + flatMap.get("extra.payload.format"));
|
||||
System.out.println("extra.payload.format: " + flatMap.get("extra.payload.name.cn"));
|
||||
}
|
||||
|
||||
/**
|
||||
* 从日志消息中解析 JSON 并转换为 XdrHoneypot 对象
|
||||
*/
|
||||
public static XdrHoneypot parseLogMessageToXdrHoneypot(String logMessage) throws Exception {
|
||||
// 1. 提取 JSON 部分
|
||||
String jsonString = extractJsonFromLogMessage(logMessage);
|
||||
|
||||
// 2. 解析 JSON
|
||||
JsonNode jsonNode = objectMapper.readTree(jsonString);
|
||||
|
||||
// 3. 创建并填充 XdrHoneypot 对象
|
||||
XdrHoneypot xdrHoneypot = new XdrHoneypot();
|
||||
|
||||
// 设置字段值
|
||||
xdrHoneypot.setVcsource(getStringValue(jsonNode, "source"));
|
||||
xdrHoneypot.setDstartTime(getStringValue(jsonNode, "start_time"));
|
||||
xdrHoneypot.setDtime(getStringValue(jsonNode, "time"));
|
||||
xdrHoneypot.setRiskLevel(getStringValue(jsonNode, "risk_level"));
|
||||
xdrHoneypot.setVcconnection(getStringValue(jsonNode, "connection"));
|
||||
xdrHoneypot.setFileInfo(getStringValue(jsonNode, "file_info"));
|
||||
xdrHoneypot.setExtra(getExtraAsString(jsonNode.get("extra")));
|
||||
xdrHoneypot.setVctype(getStringValue(jsonNode, "type"));
|
||||
xdrHoneypot.setAgentSn(getStringValue(jsonNode, "agent_sn"));
|
||||
xdrHoneypot.setAgentName(getStringValue(jsonNode, "agent_name"));
|
||||
xdrHoneypot.setHoneypotId(getStringValue(jsonNode, "honeypot_id"));
|
||||
xdrHoneypot.setHoneypotName(getStringValue(jsonNode, "honeypot_name"));
|
||||
xdrHoneypot.setSrcIp(getStringValue(jsonNode, "src_ip"));
|
||||
xdrHoneypot.setSrcPort(getStringValue(jsonNode, "src_port"));
|
||||
xdrHoneypot.setSrcMac(getStringValue(jsonNode, "src_mac"));
|
||||
xdrHoneypot.setDestIp(getStringValue(jsonNode, "dest_ip"));
|
||||
xdrHoneypot.setDestPort(getStringValue(jsonNode, "dest_port"));
|
||||
xdrHoneypot.setProxyIp(getStringValue(jsonNode, "proxy_ip"));
|
||||
xdrHoneypot.setNode(getStringValue(jsonNode, "node"));
|
||||
xdrHoneypot.setCreateTime(LocalDateTime.now());
|
||||
|
||||
return xdrHoneypot;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从日志消息中提取 JSON 部分
|
||||
*/
|
||||
public static String extractJsonFromLogMessage(String logMessage) {
|
||||
// 查找第一个 { 和最后一个 } 的位置
|
||||
int startIndex = logMessage.indexOf('{');
|
||||
int endIndex = logMessage.lastIndexOf('}');
|
||||
|
||||
if (startIndex == -1 || endIndex == -1 || endIndex <= startIndex) {
|
||||
throw new IllegalArgumentException("日志消息中未找到有效的 JSON 内容");
|
||||
}
|
||||
return logMessage.substring(startIndex, endIndex + 1);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 安全地获取字符串值
|
||||
*/
|
||||
private static String getStringValue(JsonNode jsonNode, String fieldName) {
|
||||
JsonNode fieldNode = jsonNode.get(fieldName);
|
||||
if (fieldNode == null || fieldNode.isNull()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (fieldNode.isTextual()) {
|
||||
return fieldNode.asText();
|
||||
} else {
|
||||
// 对于非文本类型(如数字),转换为字符串
|
||||
return fieldNode.toString();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将 extra 字段转换为 JSON 字符串
|
||||
*/
|
||||
private static String getExtraAsString(JsonNode extraNode) {
|
||||
if (extraNode == null || extraNode.isNull()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return objectMapper.writeValueAsString(extraNode);
|
||||
} catch (Exception e) {
|
||||
// 如果序列化失败,返回原始字符串
|
||||
return extraNode.toString();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 解析 JSON 字符串为扁平化的 Map
|
||||
* @param jsonStr JSON 字符串
|
||||
* @return 扁平化的 Map,key 使用点号表示嵌套路径
|
||||
*/
|
||||
public static LinkedHashMap<String, Object> parseJsonToFlatMap(String jsonStr) {
|
||||
try {
|
||||
LinkedHashMap<String, Object> resultMap = new LinkedHashMap<>();
|
||||
if(!isValidJson(jsonStr))
|
||||
{
|
||||
System.out.println("parseJsonToFlatMap() json str:"+jsonStr);
|
||||
System.out.println("isValidJson(string) is false");
|
||||
return null;
|
||||
}
|
||||
|
||||
TypeReference<Map<String, Object>> typeRef = new TypeReference<Map<String, Object>>() {};
|
||||
Object jsonObject = objectMapper.readValue(jsonStr, typeRef);
|
||||
//Object jsonObject = objectMapper.readValue(jsonStr.trim(), Object.class);
|
||||
flattenJson("", jsonObject, resultMap);
|
||||
return resultMap;
|
||||
} catch (Exception e) {
|
||||
//System.out.println("Exception ex.message:"+ e.getMessage());
|
||||
logger.error("parseJsonToFlatMap ex.message:{}", e.getMessage());
|
||||
throw new RuntimeException("parseJsonToFlatMap JSON 解析失败", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 递归扁平化 JSON 对象
|
||||
*/
|
||||
private static void flattenJson(String currentPath, Object jsonObject, Map<String, Object> resultMap) {
|
||||
|
||||
try {
|
||||
if (jsonObject instanceof Map) {
|
||||
// 处理 JSON 对象
|
||||
Map<?, ?> map = (Map<?, ?>) jsonObject;
|
||||
for (Entry<?, ?> entry : map.entrySet()) {
|
||||
String key = entry.getKey().toString();
|
||||
String newPath = currentPath.isEmpty() ? key : currentPath + "." + key;
|
||||
flattenJson(newPath, entry.getValue(), resultMap);
|
||||
}
|
||||
} else if (jsonObject instanceof List) {
|
||||
// 处理 JSON 数组
|
||||
List<?> list = (List<?>) jsonObject;
|
||||
for (int i = 0; i < list.size(); i++) {
|
||||
String newPath = currentPath + "[" + i + "]";
|
||||
flattenJson(newPath, list.get(i), resultMap);
|
||||
}
|
||||
} else {
|
||||
// 基本类型值
|
||||
resultMap.put(currentPath, jsonObject);
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
System.out.println("Exception ex.message:"+ e.getMessage());
|
||||
|
||||
throw new RuntimeException("flattenJson 处理异常", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 保持嵌套结构的 JSON 解析
|
||||
*/
|
||||
public static Map<String, Object> parseJsonToNestedMap(String jsonStr) {
|
||||
try {
|
||||
return objectMapper.readValue(jsonStr, Map.class);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("parseJsonToNestedMap() JSON 解析失败", e);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 打印 Map 内容
|
||||
*/
|
||||
public static void printMap(Map<String, Object> map) {
|
||||
printMap("", map, 0);
|
||||
}
|
||||
|
||||
private static void printMap(String prefix, Map<String, Object> map, int indent) {
|
||||
// String indentStr = " ".repeat(indent);
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (int i = 0; i < indent; i++) {
|
||||
sb.append(" ");
|
||||
}
|
||||
String indentStr = sb.toString();
|
||||
|
||||
for (Entry<String, Object> entry : map.entrySet()) {
|
||||
String key = entry.getKey();
|
||||
Object value = entry.getValue();
|
||||
String fullKey = prefix.isEmpty() ? key : prefix + "." + key;
|
||||
|
||||
if (value instanceof Map) {
|
||||
System.out.println(indentStr + key + ":");
|
||||
printMap(fullKey, (Map<String, Object>) value, indent + 1);
|
||||
} else if (value instanceof List) {
|
||||
System.out.println(indentStr + key + ":");
|
||||
printList(fullKey, (List<Object>) value, indent + 1);
|
||||
} else {
|
||||
System.out.println(indentStr + key + " = " + value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void printList(String prefix, List<Object> list, int indent) {
|
||||
//String indentStr = " ".repeat(indent);
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (int i = 0; i < indent; i++) {
|
||||
sb.append(" ");
|
||||
}
|
||||
String indentStr = sb.toString();
|
||||
for (int i = 0; i < list.size(); i++) {
|
||||
Object value = list.get(i);
|
||||
String itemKey = prefix + "[" + i + "]";
|
||||
|
||||
if (value instanceof Map) {
|
||||
System.out.println(indentStr + "[" + i + "]:");
|
||||
printMap(itemKey, (Map<String, Object>) value, indent + 1);
|
||||
} else if (value instanceof List) {
|
||||
System.out.println(indentStr + "[" + i + "]:");
|
||||
printList(itemKey, (List<Object>) value, indent + 1);
|
||||
} else {
|
||||
System.out.println(indentStr + "[" + i + "] = " + value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 将 JSONObject 转换为 Map
|
||||
*/
|
||||
public static LinkedHashMap<String, Object> jsonToMap(String jsonString) {
|
||||
try {
|
||||
JSONObject jsonObject = new JSONObject(jsonString.trim());
|
||||
return toMap(jsonObject);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("jsonToMap 转换失败: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 递归转换 JSONObject 到 Map
|
||||
*/
|
||||
private static LinkedHashMap<String, Object> toMap(JSONObject jsonObject) {
|
||||
LinkedHashMap<String, Object> map = new LinkedHashMap<>();
|
||||
Iterator<String> keys = jsonObject.keys();
|
||||
|
||||
while (keys.hasNext()) {
|
||||
String key = keys.next();
|
||||
Object value = jsonObject.get(key);
|
||||
|
||||
if (value instanceof JSONObject) {
|
||||
// 嵌套对象
|
||||
value = toMap((JSONObject) value);
|
||||
} else if (value instanceof JSONArray) {
|
||||
// 数组
|
||||
value = toList((JSONArray) value);
|
||||
}
|
||||
|
||||
map.put(key, value);
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
/**
|
||||
* 递归转换 JSONArray 到 List
|
||||
*/
|
||||
private static List<Object> toList(JSONArray array) {
|
||||
List<Object> list = new ArrayList<>();
|
||||
for (int i = 0; i < array.length(); i++) {
|
||||
Object value = array.get(i);
|
||||
if (value instanceof JSONObject) {
|
||||
value = toMap((JSONObject) value);
|
||||
} else if (value instanceof JSONArray) {
|
||||
value = toList((JSONArray) value);
|
||||
}
|
||||
list.add(value);
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 预处理 JSON 字符串
|
||||
*/
|
||||
public static Optional<String> preprocessJson(String jsonString) {
|
||||
if (jsonString == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
String trimmed = jsonString.trim();
|
||||
// 处理空字符串
|
||||
if (trimmed.isEmpty()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
// 处理 BOM
|
||||
if (trimmed.startsWith("\uFEFF")) {
|
||||
trimmed = trimmed.substring(1).trim();
|
||||
if (trimmed.isEmpty()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
return Optional.of(trimmed);
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查 JSON 字符串是否有效
|
||||
*/
|
||||
public static boolean isValidJson(String jsonString) {
|
||||
return preprocessJson(jsonString).isPresent();
|
||||
}
|
||||
|
||||
}
|
||||
+135
@@ -0,0 +1,135 @@
|
||||
package com.common.util;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class KeyValueParser {
|
||||
|
||||
/**
|
||||
* 解析键值对字符串
|
||||
* @param input 输入字符串
|
||||
* @return 解析后的键值对Map
|
||||
*/
|
||||
public static Map<String, String> parseKeyValueString(String input) {
|
||||
Map<String, String> result = new HashMap<>();
|
||||
|
||||
// 移除首尾的方括号(如果存在)
|
||||
String cleanedInput = input.trim();
|
||||
if (cleanedInput.startsWith("[") && cleanedInput.endsWith("]")) {
|
||||
cleanedInput = cleanedInput.substring(1, cleanedInput.length() - 1);
|
||||
}
|
||||
|
||||
// 使用正则表达式匹配键值对
|
||||
// 匹配模式:键=值,值可以包含任意字符(包括空格和标点)
|
||||
Pattern pattern = Pattern.compile("(\\w+)=([^=]+?)(?=\\s+\\w+=|$)");
|
||||
Matcher matcher = pattern.matcher(cleanedInput);
|
||||
|
||||
while (matcher.find()) {
|
||||
String key = matcher.group(1);
|
||||
String value = matcher.group(2).trim();
|
||||
result.put(key, value);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 简单的分割解析方法(适用于格式规整的情况)
|
||||
* @param input 输入字符串
|
||||
* @return 解析后的键值对Map
|
||||
*/
|
||||
public static Map<String, String> parseBySplit(String input) {
|
||||
Map<String, String> result = new HashMap<>();
|
||||
|
||||
// 移除首尾的方括号
|
||||
String cleanedInput = input.trim();
|
||||
if (cleanedInput.startsWith("[") && cleanedInput.endsWith("]")) {
|
||||
cleanedInput = cleanedInput.substring(1, cleanedInput.length() - 1);
|
||||
}
|
||||
|
||||
// 按空格分割,但保留值中的空格
|
||||
String[] pairs = cleanedInput.split("\\s+(?=\\w+=)");
|
||||
|
||||
for (String pair : pairs) {
|
||||
int equalsIndex = pair.indexOf('=');
|
||||
if (equalsIndex > 0) {
|
||||
String key = pair.substring(0, equalsIndex);
|
||||
String value = pair.substring(equalsIndex + 1);
|
||||
result.put(key, value);
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从文本中提取第一个 [] 包裹的键值对字符串并转换为 Map
|
||||
*
|
||||
* @param text 包含键值对的原始文本
|
||||
* @return 包含键值对的 Map
|
||||
* @throws IllegalArgumentException 如果格式不正确
|
||||
*/
|
||||
public static Map<String, String> parseKeyValuePairs(String text) {
|
||||
if (text == null || text.trim().isEmpty()) {
|
||||
throw new IllegalArgumentException("Input text cannot be null or empty");
|
||||
}
|
||||
|
||||
// 查找第一个 [ 和对应的 ]
|
||||
int start = text.indexOf('[');
|
||||
int end = text.indexOf(']', start + 1);
|
||||
|
||||
if (start == -1 || end == -1) {
|
||||
throw new IllegalArgumentException("No valid [] pair found in text");
|
||||
}
|
||||
|
||||
// 提取 [] 内的内容
|
||||
String content = text.substring(start + 1, end).trim();
|
||||
if (content.isEmpty()) {
|
||||
return new HashMap<>(); // 返回空Map
|
||||
}
|
||||
|
||||
// 分割键值对
|
||||
String[] pairs = content.split("\\s+");
|
||||
Map<String, String> result = new HashMap<>();
|
||||
|
||||
for (String pair : pairs) {
|
||||
// 分割键和值
|
||||
int equalSign = pair.indexOf('=');
|
||||
if (equalSign == -1) {
|
||||
throw new IllegalArgumentException("Invalid key-value pair format: " + pair);
|
||||
}
|
||||
|
||||
String key = pair.substring(0, equalSign).trim();
|
||||
String value = pair.substring(equalSign + 1).trim();
|
||||
|
||||
if (key.isEmpty()) {
|
||||
throw new IllegalArgumentException("Key cannot be empty in pair: " + pair);
|
||||
}
|
||||
|
||||
result.put(key, value);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
public static void main(String[] args) {
|
||||
String input = "[name=非工作时间访问 riskLevel=中 riskMain=账号 appName=蜜罐系统-企信外网 riskDesc=账号在2025-04-27,通过47.94.211.49客户端IP在非常用访问时间2025-04-27 15:38:54,进行了业务访问]";
|
||||
|
||||
System.out.println("=== 使用正则表达式解析 ===");
|
||||
Map<String, String> result1 = parseKeyValueString(input);
|
||||
for (Map.Entry<String, String> entry : result1.entrySet()) {
|
||||
System.out.println(entry.getKey() + ": " + entry.getValue());
|
||||
}
|
||||
|
||||
System.out.println("\n=== 使用分割方法解析 ===");
|
||||
Map<String, String> result2 = parseBySplit(input);
|
||||
for (Map.Entry<String, String> entry : result2.entrySet()) {
|
||||
System.out.println(entry.getKey() + ": " + entry.getValue());
|
||||
}
|
||||
|
||||
System.out.println("\n=== 获取特定字段 ===");
|
||||
System.out.println("应用名称: " + result1.get("appName"));
|
||||
System.out.println("风险等级: " + result1.get("riskLevel"));
|
||||
System.out.println("风险描述: " + result1.get("riskDesc"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
package com.common.util;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import com.common.entity.RuleContent.kv_paramsType;
|
||||
|
||||
@Component
|
||||
public class KvTextParser {
|
||||
|
||||
/**
|
||||
* 解析键值对类型的文本数据
|
||||
* @param text 要解析的文本
|
||||
* @param params 解析参数配置
|
||||
* @return 解析后的Map对象
|
||||
*/
|
||||
public LinkedHashMap<String, Object> parseKvText(String text, kv_paramsType params) {
|
||||
LinkedHashMap<String, Object> result = new LinkedHashMap<>();
|
||||
|
||||
if (text == null || text.trim().isEmpty()) {
|
||||
return result;
|
||||
}
|
||||
|
||||
// 获取分隔符配置
|
||||
String internal = params.getInternal(); // KV内部分隔符,如"="
|
||||
String external = params.getExternal(); // KV之间分隔符,如空格
|
||||
String lTrim = params.getL_trim(); // 左修剪字符
|
||||
String rTrim = params.getR_trim(); // 右修剪字符
|
||||
|
||||
// 转义分隔符,用于正则表达式
|
||||
String escapedExternal = Pattern.quote(external);
|
||||
String escapedInternal = Pattern.quote(internal);
|
||||
|
||||
try {
|
||||
// 使用外部KV分隔符分割字符串
|
||||
String[] kvPairs = text.split(escapedExternal);
|
||||
|
||||
for (String kvPair : kvPairs) {
|
||||
if (kvPair == null || kvPair.trim().isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// 使用内部分隔符分割键值对
|
||||
String[] parts = kvPair.split(escapedInternal, 2); // 限制分割为2部分
|
||||
|
||||
if (parts.length == 2) {
|
||||
String key = parts[0].trim();
|
||||
String value = parts[1].trim();
|
||||
|
||||
// 应用修剪
|
||||
key = applyTrim(key, lTrim, rTrim);
|
||||
value = applyTrim(value, lTrim, rTrim);
|
||||
|
||||
// 移除可能的引号
|
||||
value = removeQuotes(value);
|
||||
|
||||
result.put(key, value);
|
||||
} else if (parts.length == 1) {
|
||||
// 只有key没有value的情况
|
||||
String key = applyTrim(parts[0].trim(), lTrim, rTrim);
|
||||
result.put(key, "");
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("解析键值对文本时发生错误: " + e.getMessage(), e);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 应用字符串修剪
|
||||
*/
|
||||
private String applyTrim(String str, String lTrim, String rTrim) {
|
||||
if (str == null) return "";
|
||||
|
||||
String result = str;
|
||||
|
||||
// 左修剪
|
||||
if (lTrim != null && !lTrim.isEmpty()) {
|
||||
result = result.replaceAll("^[" + Pattern.quote(lTrim) + "]+", "");
|
||||
}
|
||||
|
||||
// 右修剪
|
||||
if (rTrim != null && !rTrim.isEmpty()) {
|
||||
result = result.replaceAll("[" + Pattern.quote(rTrim) + "]+$", "");
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 移除字符串两端的引号
|
||||
*/
|
||||
private String removeQuotes(String str) {
|
||||
if (str == null || str.length() < 2) {
|
||||
return str;
|
||||
}
|
||||
|
||||
// 检查是否被引号包围
|
||||
if ((str.startsWith("\"") && str.endsWith("\"")) ||
|
||||
(str.startsWith("'") && str.endsWith("'"))) {
|
||||
return str.substring(1, str.length() - 1);
|
||||
}
|
||||
|
||||
return str;
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用正则表达式解析更复杂的键值对格式
|
||||
* 适用于包含特殊字符的值
|
||||
*/
|
||||
public LinkedHashMap<String, Object> parseKvTextWithRegex(String text, kv_paramsType params) {
|
||||
// Map<String, String> result = new HashMap<>();
|
||||
LinkedHashMap<String, Object> result = new LinkedHashMap<>();
|
||||
if (text == null || text.trim().isEmpty()) {
|
||||
return result;
|
||||
}
|
||||
|
||||
String internal = Pattern.quote(params.getInternal());
|
||||
String external = Pattern.quote(params.getExternal());
|
||||
|
||||
// 构建正则表达式模式
|
||||
// 匹配格式: key=value 或 key="包含空格的value"
|
||||
String patternStr = "(\\w+)" + internal + "(\"[^\"]*\"|[^" + external + "]*)";
|
||||
Pattern pattern = Pattern.compile(patternStr);
|
||||
Matcher matcher = pattern.matcher(text);
|
||||
|
||||
while (matcher.find()) {
|
||||
String key = matcher.group(1);
|
||||
String value = matcher.group(2);
|
||||
|
||||
// 移除引号并应用修剪
|
||||
value = removeQuotes(value);
|
||||
value = applyTrim(value, params.getL_trim(), params.getR_trim());
|
||||
|
||||
result.put(key, value);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package com.common.util;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.apache.ibatis.io.Resources;
|
||||
import org.apache.ibatis.session.SqlSession;
|
||||
import org.apache.ibatis.session.SqlSessionFactory;
|
||||
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.function.Function;
|
||||
import org.springframework.stereotype.Component;
|
||||
/**
|
||||
* MyBatis 工具类
|
||||
*/
|
||||
|
||||
|
||||
@Component
|
||||
public class MyBatisUtil {
|
||||
private static final Logger logger = LoggerFactory.getLogger(MyBatisUtil.class);
|
||||
private static SqlSessionFactory sqlSessionFactory;
|
||||
@Autowired
|
||||
private SqlSessionFactory autoWiredSqlSessionFactory;
|
||||
static {
|
||||
init();
|
||||
}
|
||||
private static void init() {
|
||||
try {
|
||||
String resource = "mybatis-config.xml";
|
||||
InputStream inputStream = Resources.getResourceAsStream(resource);
|
||||
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
|
||||
logger.info("MyBatis 初始化成功");
|
||||
} catch (IOException e) {
|
||||
logger.error("初始化MyBatis失败", e);
|
||||
throw new RuntimeException("初始化MyBatis失败", e);
|
||||
}
|
||||
}
|
||||
public static SqlSession getSqlSession() {
|
||||
return sqlSessionFactory.openSession();
|
||||
}
|
||||
|
||||
public static SqlSessionFactory getSqlSessionFactory() {
|
||||
return sqlSessionFactory;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取 SqlSession(自动提交事务)
|
||||
*/
|
||||
public static SqlSession getSqlSessionAutoCommit() {
|
||||
return sqlSessionFactory.openSession(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行查询操作(自动管理资源)
|
||||
*/
|
||||
public static <T> T executeQuery(Function<SqlSession, T> function) {
|
||||
SqlSession sqlSession = getSqlSession();
|
||||
try {
|
||||
return function.apply(sqlSession);
|
||||
} finally {
|
||||
sqlSession.close();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行更新操作(自动提交事务和管理资源)
|
||||
*/
|
||||
public static <T> T executeUpdate(Function<SqlSession, T> function) {
|
||||
SqlSession sqlSession = getSqlSession();
|
||||
try {
|
||||
T result = function.apply(sqlSession);
|
||||
sqlSession.commit();
|
||||
return result;
|
||||
} catch (Exception e) {
|
||||
sqlSession.rollback();
|
||||
throw new RuntimeException("数据库操作失败", e);
|
||||
} finally {
|
||||
sqlSession.close();
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 重新初始化(用于配置热更新)
|
||||
*/
|
||||
public static void reload() {
|
||||
init();
|
||||
}
|
||||
}
|
||||
+510
@@ -0,0 +1,510 @@
|
||||
package com.common.util;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.core.JsonParser;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.regex.Matcher;
|
||||
|
||||
public class NestedJsonParserUtil {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(NestedJsonParserUtil.class);
|
||||
|
||||
// 配置ObjectMapper,启用容错特性
|
||||
private static final ObjectMapper objectMapper = new ObjectMapper()
|
||||
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
|
||||
.configure(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE, false)
|
||||
.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true)
|
||||
.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true)
|
||||
.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true)
|
||||
.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true)
|
||||
.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true)
|
||||
.configure(JsonParser.Feature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER, true);
|
||||
|
||||
/**
|
||||
* 安全的JSON字符串转Map方法(支持嵌套结构)
|
||||
*/
|
||||
public static LinkedHashMap<String, Object> safeParseJson(String jsonStr) {
|
||||
return safeParseJson(jsonStr, new LinkedHashMap<>());
|
||||
}
|
||||
|
||||
/**
|
||||
* 安全的JSON字符串转Map方法(支持嵌套结构和自定义选项)
|
||||
*/
|
||||
public static LinkedHashMap<String, Object> safeParseJson(String jsonStr, LinkedHashMap<String, Object> options) {
|
||||
if (jsonStr == null || jsonStr.trim().isEmpty()) {
|
||||
logger.warn("JSON字符串为空或null");
|
||||
//return Collections.emptyMap();
|
||||
return null;
|
||||
}
|
||||
|
||||
// 获取选项,嵌套3层
|
||||
int maxDepth = (Integer) options.getOrDefault("maxDepth", 3);
|
||||
boolean allowUnquoted = (Boolean) options.getOrDefault("allowUnquoted", true);
|
||||
boolean allowSingleQuotes = (Boolean) options.getOrDefault("allowSingleQuotes", true);
|
||||
|
||||
try {
|
||||
// 1. 预处理JSON字符串
|
||||
// String processedJson = preprocessJsonString(jsonStr, allowUnquoted, allowSingleQuotes);
|
||||
String processedJson =jsonStr;
|
||||
|
||||
System.out.println("processedJson:"+processedJson);
|
||||
// 2. 深度验证嵌套结构
|
||||
//validateNestedStructure(processedJson, maxDepth);
|
||||
//ObjectMapper mapper = new ObjectMapper(); // 这里使用Jackson
|
||||
//System.out.println( mapper.readTree(processedJson));
|
||||
|
||||
//TypeReference<Map<String, String>> typeRef1 = new TypeReference<Map<String, String>>() {};
|
||||
//Map<String, String> result1 = objectMapper.readValue(processedJson, typeRef1);
|
||||
|
||||
|
||||
// 3. 尝试解析
|
||||
TypeReference<Map<String, Object>> typeRef = new TypeReference<Map<String, Object>>() {};
|
||||
Map<String, Object> result = objectMapper.readValue(processedJson, typeRef);
|
||||
|
||||
// 4. 后处理:清理和验证解析结果
|
||||
return postProcessParsedData(result, maxDepth);
|
||||
|
||||
} catch (JsonProcessingException e) {
|
||||
logger.error("JSON解析失败json:{} 错误消息: {}",jsonStr, e.getMessage());
|
||||
|
||||
// 5. 尝试修复并重新解析
|
||||
try {
|
||||
String fixedJson = tryFixNestedJson(jsonStr, maxDepth);
|
||||
if (!fixedJson.equals(jsonStr)) {
|
||||
TypeReference<Map<String, Object>> typeRef = new TypeReference<Map<String, Object>>() {};
|
||||
Map<String, Object> result = objectMapper.readValue(fixedJson, typeRef);
|
||||
return postProcessParsedData(result, maxDepth);
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
logger.error("JSON修复后解析仍然失败", ex);
|
||||
}
|
||||
return null;
|
||||
//return Collections.emptyMap();
|
||||
|
||||
} catch (Exception e) {
|
||||
logger.error("JSON解析发生未知异常", e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析JSON为JsonNode(更灵活的嵌套处理)
|
||||
*/
|
||||
public static JsonNode safeParseJsonNode(String jsonStr) {
|
||||
if (jsonStr == null || jsonStr.trim().isEmpty()) {
|
||||
return objectMapper.createObjectNode();
|
||||
}
|
||||
|
||||
try {
|
||||
String processedJson = preprocessJsonString(jsonStr, true, true);
|
||||
return objectMapper.readTree(processedJson);
|
||||
} catch (Exception e) {
|
||||
logger.error("解析JSON为JsonNode失败", e);
|
||||
try {
|
||||
String fixedJson = tryFixNestedJson(jsonStr, 10);
|
||||
return objectMapper.readTree(fixedJson);
|
||||
} catch (Exception ex) {
|
||||
logger.error("修复后解析JSON Node仍然失败", ex);
|
||||
return objectMapper.createObjectNode();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 预处理JSON字符串(增强版)
|
||||
*/
|
||||
private static String preprocessJsonString(String jsonStr, boolean allowUnquoted, boolean allowSingleQuotes) {
|
||||
if (jsonStr == null) {
|
||||
return "{}";
|
||||
}
|
||||
|
||||
String processed = jsonStr.trim();
|
||||
|
||||
// 移除BOM字符
|
||||
if (processed.startsWith("\uFEFF")) {
|
||||
processed = processed.substring(1);
|
||||
}
|
||||
|
||||
// 处理不同编码的空白字符
|
||||
processed = processed.replaceAll("[\\u00A0\\u2007\\u202F]", " ");
|
||||
|
||||
// 确保字符串以{开头,以}结尾
|
||||
if (!processed.startsWith("{") && !processed.startsWith("[")) {
|
||||
// 尝试检测是否是JSONP格式
|
||||
if (processed.contains("(") && processed.contains(")")) {
|
||||
processed = extractJsonFromJsonp(processed);
|
||||
} else {
|
||||
// 如果不是JSON对象或数组,尝试包装成对象
|
||||
processed = "{\"data\": " + processed + "}";
|
||||
}
|
||||
}
|
||||
|
||||
// 根据选项处理引号
|
||||
if (!allowSingleQuotes) {
|
||||
processed = convertSingleQuotesToDouble(processed);
|
||||
}
|
||||
|
||||
return processed;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从JSONP中提取JSON
|
||||
*/
|
||||
private static String extractJsonFromJsonp(String jsonp) {
|
||||
try {
|
||||
int start = jsonp.indexOf('(');
|
||||
int end = jsonp.lastIndexOf(')');
|
||||
if (start != -1 && end != -1 && end > start) {
|
||||
return jsonp.substring(start + 1, end);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.warn("JSONP提取失败", e);
|
||||
}
|
||||
return "{}";
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证嵌套结构深度
|
||||
*/
|
||||
private static void validateNestedStructure(String jsonStr, int maxDepth) {
|
||||
int depth = calculateJsonDepth(jsonStr);
|
||||
if (depth > maxDepth) {
|
||||
throw new IllegalArgumentException("JSON嵌套深度超过限制: " + depth + " > " + maxDepth);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算JSON最大嵌套深度
|
||||
*/
|
||||
private static int calculateJsonDepth(String jsonStr) {
|
||||
int maxDepth = 0;
|
||||
int currentDepth = 0;
|
||||
|
||||
for (int i = 0; i < jsonStr.length(); i++) {
|
||||
char c = jsonStr.charAt(i);
|
||||
if (c == '{' || c == '[') {
|
||||
currentDepth++;
|
||||
maxDepth = Math.max(maxDepth, currentDepth);
|
||||
} else if (c == '}' || c == ']') {
|
||||
currentDepth--;
|
||||
}
|
||||
|
||||
if (currentDepth < 0) {
|
||||
throw new IllegalArgumentException("calculateJsonDepth() JSON括号不匹配");
|
||||
}
|
||||
}
|
||||
|
||||
if (currentDepth != 0) {
|
||||
throw new IllegalArgumentException("calculateJsonDepth() JSON括号不匹配");
|
||||
}
|
||||
|
||||
return maxDepth;
|
||||
}
|
||||
|
||||
/**
|
||||
* 尝试修复嵌套JSON
|
||||
*/
|
||||
private static String tryFixNestedJson(String jsonStr, int maxDepth) {
|
||||
if (jsonStr == null) {
|
||||
return "{}";
|
||||
}
|
||||
|
||||
String fixed = jsonStr.trim();
|
||||
|
||||
try {
|
||||
// 修复步骤序列
|
||||
fixed = fixJsonpWrapper(fixed);
|
||||
fixed = fixUnescapedQuotesInNestedJson(fixed);
|
||||
fixed = fixSingleQuotes(fixed);
|
||||
fixed = fixUnescapedBackslashes(fixed);
|
||||
fixed = fixTrailingCommas(fixed);
|
||||
fixed = fixMissingQuotesInNestedJson(fixed);
|
||||
fixed = fixNumericIssues(fixed);
|
||||
fixed = fixBooleanIssues(fixed);
|
||||
fixed = fixNullIssues(fixed);
|
||||
fixed = fixArrayIssues(fixed);
|
||||
|
||||
logger.info("尝试修复嵌套JSON字符串");
|
||||
return fixed;
|
||||
|
||||
} catch (Exception e) {
|
||||
logger.warn("嵌套JSON修复过程中发生异常", e);
|
||||
return jsonStr;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 修复JSONP包装
|
||||
*/
|
||||
private static String fixJsonpWrapper(String json) {
|
||||
if (json.matches("^[a-zA-Z_$][a-zA-Z0-9_$]*\\s*\\(") && json.contains(")")) {
|
||||
return extractJsonFromJsonp(json);
|
||||
}
|
||||
return json;
|
||||
}
|
||||
|
||||
/**
|
||||
* 修复嵌套JSON中的未转义引号
|
||||
*/
|
||||
private static String fixUnescapedQuotesInNestedJson(String json) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
boolean inString = false;
|
||||
char prevChar = 0;
|
||||
int braceCount = 0;
|
||||
int bracketCount = 0;
|
||||
|
||||
for (int i = 0; i < json.length(); i++) {
|
||||
char c = json.charAt(i);
|
||||
|
||||
// 跟踪嵌套级别
|
||||
if (c == '{') braceCount++;
|
||||
if (c == '}') braceCount--;
|
||||
if (c == '[') bracketCount++;
|
||||
if (c == ']') bracketCount--;
|
||||
|
||||
// 处理字符串状态
|
||||
if (c == '"' && prevChar != '\\') {
|
||||
inString = !inString;
|
||||
sb.append(c);
|
||||
} else if (inString && c == '"' && prevChar == '\\') {
|
||||
sb.append(c);
|
||||
} else if (inString && c == '"') {
|
||||
// 在字符串中遇到未转义的双引号,需要转义
|
||||
sb.append("\\\"");
|
||||
} else {
|
||||
sb.append(c);
|
||||
}
|
||||
|
||||
prevChar = c;
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 修复嵌套JSON中缺失的引号
|
||||
*/
|
||||
private static String fixMissingQuotesInNestedJson(String json) {
|
||||
// 使用更复杂的正则表达式来修复嵌套对象中的键
|
||||
Pattern pattern = Pattern.compile("([{,{]\\s*)([a-zA-Z_$][a-zA-Z0-9_$]*)(\\s*:\\s*)");
|
||||
Matcher matcher = pattern.matcher(json);
|
||||
StringBuffer result = new StringBuffer();
|
||||
|
||||
while (matcher.find()) {
|
||||
String replacement = matcher.group(1) + "\"" + matcher.group(2) + "\"" + matcher.group(3);
|
||||
matcher.appendReplacement(result, Matcher.quoteReplacement(replacement));
|
||||
}
|
||||
matcher.appendTail(result);
|
||||
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 修复数字问题
|
||||
*/
|
||||
private static String fixNumericIssues(String json) {
|
||||
// 修复前导零的数字
|
||||
json = json.replaceAll(":\\s*0+(\\d+)", ":$1");
|
||||
// 修复缺失小数点的数字
|
||||
json = json.replaceAll(":\\s*(\\d+)\\.(\\s*[,\\}])", ":$1.0$2");
|
||||
return json;
|
||||
}
|
||||
|
||||
/**
|
||||
* 修复布尔值问题
|
||||
*/
|
||||
private static String fixBooleanIssues(String json) {
|
||||
json = json.replaceAll(":\\s*true", ":true");
|
||||
json = json.replaceAll(":\\s*false", ":false");
|
||||
json = json.replaceAll(":\\s*TRUE", ":true");
|
||||
json = json.replaceAll(":\\s*FALSE", ":false");
|
||||
return json;
|
||||
}
|
||||
|
||||
/**
|
||||
* 修复null值问题
|
||||
*/
|
||||
private static String fixNullIssues(String json) {
|
||||
json = json.replaceAll(":\\s*null", ":null");
|
||||
json = json.replaceAll(":\\s*NULL", ":null");
|
||||
json = json.replaceAll(":\\s*Null", ":null");
|
||||
return json;
|
||||
}
|
||||
|
||||
/**
|
||||
* 修复数组问题
|
||||
*/
|
||||
private static String fixArrayIssues(String json) {
|
||||
// 修复数组中的尾随逗号
|
||||
//json = json.replaceAll(",(\s*])", "$1");
|
||||
// json =json.replaceAll(",(\s[}\])])", "$1");
|
||||
return json;
|
||||
}
|
||||
|
||||
/**
|
||||
* 单引号转双引号
|
||||
*/
|
||||
private static String fixSingleQuotes(String json) {
|
||||
return convertSingleQuotesToDouble(json);
|
||||
}
|
||||
|
||||
/**
|
||||
* 单引号转双引号(智能转换,不转换字符串内的单引号)
|
||||
*/
|
||||
private static String convertSingleQuotesToDouble(String json) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
boolean inDoubleString = false;
|
||||
boolean inSingleString = false;
|
||||
char prevChar = 0;
|
||||
|
||||
for (int i = 0; i < json.length(); i++) {
|
||||
char c = json.charAt(i);
|
||||
|
||||
if (c == '"' && prevChar != '\\') {
|
||||
inDoubleString = !inDoubleString;
|
||||
sb.append(c);
|
||||
} else if (c == '\'' && prevChar != '\\' && !inDoubleString) {
|
||||
if (!inSingleString) {
|
||||
sb.append('"');
|
||||
inSingleString = true;
|
||||
} else {
|
||||
sb.append('"');
|
||||
inSingleString = false;
|
||||
}
|
||||
} else {
|
||||
sb.append(c);
|
||||
}
|
||||
|
||||
prevChar = c;
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 修复未转义的反斜杠
|
||||
*/
|
||||
private static String fixUnescapedBackslashes(String json) {
|
||||
// 简单的反斜杠转义,注意不要破坏已经转义的内容
|
||||
return json.replace("\\", "\\\\").replace("\\\\\"", "\\\"");
|
||||
}
|
||||
|
||||
/**
|
||||
* 修复尾随逗号
|
||||
*/
|
||||
private static String fixTrailingCommas(String json) {
|
||||
// 移除对象和数组中的尾随逗号
|
||||
//json = json.replaceAll(",(\s*[}\]])", "$1");
|
||||
return json;
|
||||
}
|
||||
|
||||
/**
|
||||
* 后处理解析的数据
|
||||
*/
|
||||
private static LinkedHashMap<String, Object> postProcessParsedData(Map<String, Object> data, int maxDepth) {
|
||||
if (data == null) {
|
||||
//return Collections.emptyMap();
|
||||
return null;
|
||||
}
|
||||
|
||||
// 深度清理和验证
|
||||
return cleanNestedData(data, 0, maxDepth);
|
||||
}
|
||||
|
||||
/**
|
||||
* 清理嵌套数据
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
private static LinkedHashMap<String, Object> cleanNestedData(Map<String, Object> data, int currentDepth, int maxDepth) {
|
||||
if (currentDepth > maxDepth) {
|
||||
logger.warn("数据嵌套过深,进行截断");
|
||||
// return Collections.emptyMap();
|
||||
return null;
|
||||
}
|
||||
|
||||
LinkedHashMap<String, Object> cleaned = new LinkedHashMap<>();
|
||||
|
||||
for (Map.Entry<String, Object> entry : data.entrySet()) {
|
||||
String key = entry.getKey();
|
||||
Object value = entry.getValue();
|
||||
|
||||
// 清理键
|
||||
String cleanedKey = key.trim();
|
||||
|
||||
// 清理值
|
||||
Object cleanedValue = cleanValue(value, currentDepth + 1, maxDepth);
|
||||
|
||||
cleaned.put(cleanedKey, cleanedValue);
|
||||
}
|
||||
|
||||
return cleaned;
|
||||
}
|
||||
|
||||
/**
|
||||
* 清理值
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
private static Object cleanValue(Object value, int currentDepth, int maxDepth) {
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (value instanceof Map) {
|
||||
return cleanNestedData((Map<String, Object>) value, currentDepth, maxDepth);
|
||||
} else if (value instanceof List) {
|
||||
List<Object> cleanedList = new ArrayList<>();
|
||||
for (Object item : (List<?>) value) {
|
||||
cleanedList.add(cleanValue(item, currentDepth + 1, maxDepth));
|
||||
}
|
||||
return cleanedList;
|
||||
} else if (value instanceof String) {
|
||||
return ((String) value).trim();
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
// 测试复杂的嵌套JSON
|
||||
String complexJson = "{\"source\":\"portrait\",\"uuid\":\"1a26ac6e-2d77-4ada-b560-1abbcae1de98\",\"host\":{\"cpuConcurrency\":8,\"fonts\":[\"Rockwell\",\"Calibri\",\"Gadugi\",\"Leelawadee UI\",\"Bahnschrift\",\"DengXian\",\"Roboto\",\"DejaVu Sans Mono\",\"Open Sans\",\"Source Han Serif CN\"],\"hasUnity\":false,\"language\":\"zh-CN\",\"memory\":0,\"os\":\"Windows 10.0\",\"render\":\"ANGLE (Intel, Intel(R) UHD Graphics 620 Direct3D9Ex vs_3_0 ps_3_0, igdumdim32.dll-30.0.101.1338)\",\"screenResolution\":[1366,768],\"timezone\":\"Asia/Shanghai\",\"touchSupport\":true},\"network\":{\"externalIP\":{\"ip\":\"60.190.198.14\"},\"internalIP\":{\"ip\":\"\"},\"realIP\":{\"ip\":\"60.190.198.14\"}},\"browser\":{\"arch\":\"\",\"bitness\":\"\",\"canvasFingerprint\":\"7031cc506eaded347eb1b596677ec7be\",\"canvas_fp\":\"7031cc506eaded347eb1b596677ec7be\",\"canvas_fp2\":\"7031cc506eaded347eb1b596677ec7be\",\"chrome_ext\":[\"Google Office\"],\"fp2\":\"559732dbe9bafced9536c77a6c020f88\",\"is_private\":false,\"mobile\":false,\"model\":\"\",\"name\":\"Chrome\",\"os\":\"Windows 10.0\",\"tid\":\"s:16951889730ae4d6af8-b3b4b-5ede70.22c7306819e72dd14e3e5c5644e49ed42a44d857ca55f6df0acd0460f510f15f\",\"version\":\"94.0.4606.71\",\"versionNumber\":94,\"webgl_fp\":\"487f7b22f68312d2c1bbc93b1aea445b\",\"webgl_fp2\":\"487f7b22f68312d2c1bbc93b1aea445b\"},\"social\":{},\"extra\":{\"version\":\"1.1\"},\"node\":\"AQSE\"}";
|
||||
|
||||
//String complexJson ="{\"sn\":\"8cf9a388-578e-4b30-ac4b-098a46dde642\",\"name\":\"茂名市住房和城乡建设局蜜罐探针\",\"send\":true,\"host\":\"172.25.142.16\",\"type\":\"agent_connect\",\"event_type_display_name\":{\"en\":\"Agent Connect Event\",\"cn\":\"探针连接建立\"},\"node\":\"WRx3\"}";
|
||||
// 测试有问题的嵌套JSON
|
||||
String problematicJson = "{\"source\":\"portrait\",\"uuid\":\"1a26ac6e-2d77-4ada-b560-1abbcae1de98\",\"host\":{\"cpuConcurrency\":8,\"fonts\":[\"Rockwell\",\"Calibri\",\"Gadugi\",\"Leelawadee UI\",\"Bahnschrift\",\"DengXian\",\"Roboto\",\"DejaVu Sans Mono\",\"Open Sans\",\"Source Han Serif CN\"],\"hasUnity\":false,\"language\":\"zh-CN\",\"memory\":0,\"os\":\"Windows 10.0\",\"render\":\"ANGLE (Intel, Intel(R) UHD Graphics 620 Direct3D9Ex vs_3_0 ps_3_0, igdumdim32.dll-30.0.101.1338)\",\"screenResolution\":[1366,768],\"timezone\":\"Asia/Shanghai\",\"touchSupport\":true},\"network\":{\"externalIP\":{\"ip\":\"60.190.198.14\"},\"internalIP\":{\"ip\":\"\"},\"realIP\":{\"ip\":\"60.190.198.14\"}},\"browser\":{\"arch\":\"\",\"bitness\":\"\",\"canvasFingerprint\":\"7031cc506eaded347eb1b596677ec7be\",\"canvas_fp\":\"7031cc506eaded347eb1b596677ec7be\",\"canvas_fp2\":\"7031cc506eaded347eb1b596677ec7be\",\"chrome_ext\":[\"Google Office\"],\"fp2\":\"559732dbe9bafced9536c77a6c020f88\",\"is_private\":false,\"mobile\":false,\"model\":\"\",\"name\":\"Chrome\",\"os\":\"Windows 10.0\",\"tid\":\"s:16951889730ae4d6af8-b3b4b-5ede70.22c7306819e72dd14e3e5c5644e49ed42a44d857ca55f6df0acd0460f510f15f\",\"version\":\"94.0.4606.71\",\"versionNumber\":94,\"webgl_fp\":\"487f7b22f68312d2c1bbc93b1aea445b\",\"webgl_fp2\":\"487f7b22f68312d2c1bbc93b1aea445b\"},\"social\":{},\"extra\":{\"version\":\"1.1\"},\"node\":\"AQSE\"}";
|
||||
|
||||
// 测试解析
|
||||
System.out.println("=== 正常嵌套JSON解析 ===");
|
||||
LinkedHashMap<String, Object> result1 = NestedJsonParserUtil.safeParseJson(complexJson);
|
||||
System.out.println("解析结果: " + result1);
|
||||
|
||||
System.out.println("\\n=== 有问题嵌套JSON解析 ===");
|
||||
LinkedHashMap<String, Object> result2 = NestedJsonParserUtil.safeParseJson(problematicJson);
|
||||
System.out.println("解析结果: " + result2);
|
||||
|
||||
/**
|
||||
System.out.println("\\n=== 嵌套值获取 ===");
|
||||
String userName = NestedJsonUtils.getNestedString(result1, "user.name");
|
||||
Integer userAge = NestedJsonUtils.getNestedInteger(result1, "user.profile.age");
|
||||
String city = NestedJsonUtils.getNestedString(result1, "user.profile.address.city");
|
||||
|
||||
System.out.println("用户名: " + userName);
|
||||
System.out.println("年龄: " + userAge);
|
||||
System.out.println("城市: " + city);
|
||||
**/
|
||||
System.out.println("\\n=== 扁平化处理 ===");
|
||||
|
||||
LinkedHashMap<String, Object> flattened = NestedJsonUtils.flattenNestedJson(result1);
|
||||
System.out.println("扁平化结果: " + flattened);
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
+169
@@ -0,0 +1,169 @@
|
||||
package com.common.util;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.core.JsonParser;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.regex.Matcher;
|
||||
|
||||
/**
|
||||
* 嵌套JSON专门处理工具
|
||||
*/
|
||||
public class NestedJsonUtils {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(NestedJsonUtils.class);
|
||||
|
||||
/**
|
||||
* 安全地获取嵌套值
|
||||
*/
|
||||
public static Object getNestedValue(Map<String, Object> data, String path) {
|
||||
return getNestedValue(data, path, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 安全地获取嵌套值(带默认值)
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public static Object getNestedValue(Map<String, Object> data, String path, Object defaultValue) {
|
||||
if (data == null || path == null || path.trim().isEmpty()) {
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
String[] keys = path.split("\\.");
|
||||
Object current = data;
|
||||
|
||||
for (String key : keys) {
|
||||
if (current instanceof Map) {
|
||||
current = ((Map<String, Object>) current).get(key);
|
||||
} else {
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
if (current == null) {
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
|
||||
return current != null ? current : defaultValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* 安全地获取嵌套字符串
|
||||
*/
|
||||
public static String getNestedString(Map<String, Object> data, String path) {
|
||||
return getNestedString(data, path, null);
|
||||
}
|
||||
|
||||
public static String getNestedString(Map<String, Object> data, String path, String defaultValue) {
|
||||
Object value = getNestedValue(data, path, defaultValue);
|
||||
return value != null ? value.toString() : defaultValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* 安全地获取嵌套整数
|
||||
*/
|
||||
public static Integer getNestedInteger(Map<String, Object> data, String path) {
|
||||
return getNestedInteger(data, path, null);
|
||||
}
|
||||
|
||||
public static Integer getNestedInteger(Map<String, Object> data, String path, Integer defaultValue) {
|
||||
Object value = getNestedValue(data, path, defaultValue);
|
||||
|
||||
if (value instanceof Integer) {
|
||||
return (Integer) value;
|
||||
} else if (value instanceof String) {
|
||||
try {
|
||||
return Integer.parseInt((String) value);
|
||||
} catch (NumberFormatException e) {
|
||||
logger.warn("无法将值转换为整数: {}", value);
|
||||
return defaultValue;
|
||||
}
|
||||
} else if (value instanceof Number) {
|
||||
return ((Number) value).intValue();
|
||||
}
|
||||
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* 安全地获取嵌套Map
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public static Map<String, Object> getNestedMap(Map<String, Object> data, String path) {
|
||||
Object value = getNestedValue(data, path, Collections.emptyMap());
|
||||
|
||||
if (value instanceof Map) {
|
||||
return (Map<String, Object>) value;
|
||||
}
|
||||
|
||||
return Collections.emptyMap();
|
||||
}
|
||||
|
||||
/**
|
||||
* 安全地获取嵌套列表
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public static List<Object> getNestedList(Map<String, Object> data, String path) {
|
||||
Object value = getNestedValue(data, path, Collections.emptyList());
|
||||
|
||||
if (value instanceof List) {
|
||||
return (List<Object>) value;
|
||||
}
|
||||
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
/**
|
||||
* 扁平化嵌套JSON
|
||||
*/
|
||||
public static LinkedHashMap<String, Object> flattenNestedJson(LinkedHashMap<String, Object> data) {
|
||||
return flattenNestedJson(data, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 扁平化嵌套JSON(带前缀)
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public static LinkedHashMap<String, Object> flattenNestedJson(Map<String, Object> data, String prefix) {
|
||||
LinkedHashMap<String, Object> flattened = new LinkedHashMap<>();
|
||||
String currentPrefix = prefix != null ? prefix + "." : "";
|
||||
|
||||
for (Map.Entry<String, Object> entry : data.entrySet()) {
|
||||
String key = entry.getKey();
|
||||
Object value = entry.getValue();
|
||||
String fullKey = currentPrefix + key;
|
||||
|
||||
if (value instanceof Map) {
|
||||
flattened.putAll(flattenNestedJson((Map<String, Object>) value, fullKey));
|
||||
} else if (value instanceof List) {
|
||||
// 处理列表,可以按索引展开或保持为列表
|
||||
flattened.put(fullKey, value);
|
||||
} else {
|
||||
flattened.put(fullKey, value);
|
||||
}
|
||||
}
|
||||
|
||||
return flattened;
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证嵌套JSON结构
|
||||
*/
|
||||
public static boolean validateNestedStructure(Map<String, Object> data, String schema) {
|
||||
|
||||
// 项目中可以使用JSON Schema验证库
|
||||
try {
|
||||
// 这里可以实现自定义的结构验证逻辑
|
||||
return data != null && !data.isEmpty();
|
||||
} catch (Exception e) {
|
||||
logger.error("嵌套结构验证失败", e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
+204
@@ -0,0 +1,204 @@
|
||||
package com.common.util;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* 正则表达式文本解析工具类
|
||||
*/
|
||||
@Component
|
||||
public class RegexTextParser {
|
||||
|
||||
/**
|
||||
* 使用正则表达式解析文本数据
|
||||
* @param text 原始文本
|
||||
* @param regex 正则表达式(必须包含捕获组)
|
||||
* @return LinkedHashMap对象,key为序号字符串,value为实际值
|
||||
*/
|
||||
public static LinkedHashMap<String, Object> parseWithRegex(String text, String regex) {
|
||||
LinkedHashMap<String, Object> resultMap = new LinkedHashMap<>();
|
||||
|
||||
if (text == null || text.trim().isEmpty()) {
|
||||
return resultMap;
|
||||
}
|
||||
|
||||
if (regex == null || regex.isEmpty()) {
|
||||
throw new IllegalArgumentException("正则表达式不能为空");
|
||||
}
|
||||
|
||||
try {
|
||||
Pattern pattern = Pattern.compile(regex);
|
||||
Matcher matcher = pattern.matcher(text);
|
||||
|
||||
if (matcher.find()) {
|
||||
// 获取所有捕获组(从group(1)开始,group(0)是整个匹配)
|
||||
int groupCount = matcher.groupCount();
|
||||
|
||||
if (groupCount == 0) {
|
||||
// 如果没有捕获组,将整个匹配作为第一个元素
|
||||
resultMap.put("1", matcher.group(0));
|
||||
} else {
|
||||
// 遍历所有捕获组
|
||||
for (int i = 1; i <= groupCount; i++) {
|
||||
String value = matcher.group(i);
|
||||
resultMap.put(String.valueOf(i), value != null ? value.trim() : "");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return resultMap;
|
||||
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("正则表达式解析失败: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用正则表达式解析文本数据(支持多次匹配)
|
||||
* @param text 原始文本
|
||||
* @param regex 正则表达式
|
||||
* @param matchAll 是否匹配所有结果
|
||||
* @return LinkedHashMap对象,key为匹配序号,value为实际值
|
||||
*/
|
||||
public static LinkedHashMap<String, Object> parseWithRegex(String text, String regex, boolean matchAll) {
|
||||
LinkedHashMap<String, Object> resultMap = new LinkedHashMap<>();
|
||||
|
||||
if (text == null || text.trim().isEmpty()) {
|
||||
return resultMap;
|
||||
}
|
||||
|
||||
if (regex == null || regex.isEmpty()) {
|
||||
throw new IllegalArgumentException("正则表达式不能为空");
|
||||
}
|
||||
|
||||
if (!matchAll) {
|
||||
return parseWithRegex(text, regex);
|
||||
}
|
||||
|
||||
try {
|
||||
Pattern pattern = Pattern.compile(regex);
|
||||
Matcher matcher = pattern.matcher(text);
|
||||
|
||||
int matchCount = 0;
|
||||
while (matcher.find()) {
|
||||
matchCount++;
|
||||
int groupCount = matcher.groupCount();
|
||||
|
||||
if (groupCount == 0) {
|
||||
// 如果没有捕获组,将整个匹配作为一个元素
|
||||
resultMap.put(String.valueOf(matchCount), matcher.group(0));
|
||||
} else {
|
||||
// 对于每个匹配,将捕获组按顺序存储
|
||||
for (int i = 1; i <= groupCount; i++) {
|
||||
String key = matchCount + "_" + i; // 格式:匹配序号_组号
|
||||
String value = matcher.group(i);
|
||||
resultMap.put(key, value != null ? value.trim() : "");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return resultMap;
|
||||
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("正则表达式解析失败: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用正则表达式解析文本数据(带类型转换)
|
||||
* @param text 原始文本
|
||||
* @param regex 正则表达式
|
||||
* @param valueType 值类型
|
||||
* @return LinkedHashMap对象
|
||||
*/
|
||||
public static LinkedHashMap<String, Object> parseWithRegex(String text, String regex, ValueType valueType) {
|
||||
LinkedHashMap<String, Object> resultMap = parseWithRegex(text, regex);
|
||||
|
||||
// 应用类型转换
|
||||
resultMap.replaceAll((key, value) -> convertValue(value.toString(), valueType));
|
||||
|
||||
return resultMap;
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用正则表达式分割文本(类似String.split但返回LinkedHashMap)
|
||||
* @param text 原始文本
|
||||
* @param regex 分割正则表达式
|
||||
* @return LinkedHashMap对象
|
||||
*/
|
||||
public static LinkedHashMap<String, Object> splitWithRegex(String text, String regex) {
|
||||
LinkedHashMap<String, Object> resultMap = new LinkedHashMap<>();
|
||||
|
||||
if (text == null || text.trim().isEmpty()) {
|
||||
return resultMap;
|
||||
}
|
||||
|
||||
if (regex == null || regex.isEmpty()) {
|
||||
throw new IllegalArgumentException("分割正则表达式不能为空");
|
||||
}
|
||||
|
||||
try {
|
||||
String[] parts = text.split(regex, -1); // 使用-1保留空字符串
|
||||
|
||||
for (int i = 0; i < parts.length; i++) {
|
||||
resultMap.put(String.valueOf(i + 1), parts[i].trim());
|
||||
}
|
||||
|
||||
return resultMap;
|
||||
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("正则表达式分割失败: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 提取引号内的内容(专用方法,处理示例中的情况)
|
||||
* @param text 原始文本
|
||||
* @return LinkedHashMap对象
|
||||
*/
|
||||
public static LinkedHashMap<String, Object> extractQuotedContent(String text) {
|
||||
// 正则表达式匹配双引号内的内容,忽略转义引号
|
||||
String regex = "\"([^\"]*)\"";
|
||||
return parseWithRegex(text, regex, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 值类型枚举
|
||||
*/
|
||||
public enum ValueType {
|
||||
STRING, INTEGER, LONG, DOUBLE, BOOLEAN, DATE
|
||||
}
|
||||
|
||||
/**
|
||||
* 值类型转换
|
||||
*/
|
||||
private static Object convertValue(String value, ValueType valueType) {
|
||||
if (value == null || value.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
switch (valueType) {
|
||||
case INTEGER:
|
||||
return Integer.parseInt(value);
|
||||
case LONG:
|
||||
return Long.parseLong(value);
|
||||
case DOUBLE:
|
||||
return Double.parseDouble(value);
|
||||
case BOOLEAN:
|
||||
return Boolean.parseBoolean(value) || "1".equals(value) || "true".equalsIgnoreCase(value);
|
||||
case DATE:
|
||||
// 简单日期解析,实际项目中可以使用DateTimeFormatter
|
||||
return java.sql.Timestamp.valueOf(value);
|
||||
case STRING:
|
||||
default:
|
||||
return value;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
// 转换失败时返回原始字符串
|
||||
return value;
|
||||
}
|
||||
}
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package com.common.util;
|
||||
|
||||
import org.springframework.beans.BeansException;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.ApplicationContextAware;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class SpringContextUtil implements ApplicationContextAware {
|
||||
|
||||
private static ApplicationContext applicationContext;
|
||||
|
||||
@Override
|
||||
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
|
||||
SpringContextUtil.applicationContext = applicationContext;
|
||||
}
|
||||
|
||||
public static ApplicationContext getApplicationContext() {
|
||||
return applicationContext;
|
||||
}
|
||||
|
||||
public static <T> T getBean(Class<T> clazz) {
|
||||
return applicationContext.getBean(clazz);
|
||||
}
|
||||
|
||||
public static <T> T getBean(String name, Class<T> clazz) {
|
||||
return applicationContext.getBean(name, clazz);
|
||||
}
|
||||
|
||||
// 专门获取 Mapper 的方法
|
||||
public static <T> T getMapper(Class<T> mapperClass) {
|
||||
return applicationContext.getBean(mapperClass);
|
||||
}
|
||||
}
|
||||
+285
@@ -0,0 +1,285 @@
|
||||
package com.common.util;
|
||||
|
||||
public class StringExtractorUtil {
|
||||
|
||||
/**
|
||||
* 简化的字符串截取方法
|
||||
* @param text 原始文本
|
||||
* @param startChar 开始字符
|
||||
* @param startOffset 开始偏移量(负数表示向前)
|
||||
* @param endChar 结束字符
|
||||
* @param endOccurrence 结束字符第几次出现
|
||||
* @return 截取的字符串
|
||||
*/
|
||||
public static String extract(String text, char startChar, int startOffset,
|
||||
char endChar, int endOccurrence) {
|
||||
if (text == null) return "";
|
||||
|
||||
int startIndex = text.indexOf(startChar);
|
||||
if (startIndex == -1) return "";
|
||||
|
||||
// 计算实际开始位置
|
||||
int actualStart = Math.max(0, startIndex + startOffset);
|
||||
if (actualStart >= text.length()) return "";
|
||||
|
||||
// 查找结束字符
|
||||
int currentIndex = actualStart;
|
||||
int count = 0;
|
||||
|
||||
while (currentIndex < text.length()) {
|
||||
if (text.charAt(currentIndex) == endChar) {
|
||||
count++;
|
||||
if (count == endOccurrence) {
|
||||
return text.substring(actualStart, currentIndex);
|
||||
}
|
||||
}
|
||||
currentIndex++;
|
||||
}
|
||||
return ""; // 未找到足够的结束字符
|
||||
}
|
||||
/**
|
||||
* 从文本中截取字符串,从指定起始字符串的第0位开始,直到文本末尾
|
||||
* @param text 原始文本
|
||||
* @param startString 起始字符串
|
||||
* @return 截取后的字符串,如果起始字符串不存在则返回空字符串
|
||||
*/
|
||||
public static String extractFromStartToEnd(String text, String startString) {
|
||||
if (text == null || startString == null) {
|
||||
return "";
|
||||
}
|
||||
|
||||
// 查找起始字符串的位置
|
||||
int startIndex = text.indexOf(startString);
|
||||
if (startIndex == -1) {
|
||||
return ""; // 起始字符串不存在
|
||||
}
|
||||
|
||||
// 从起始字符串的第0位开始截取到文本末尾
|
||||
return text.substring(startIndex);
|
||||
}
|
||||
|
||||
/**
|
||||
* 从文本中截取字符串,从指定起始字符串的指定位置开始,直到文本末尾
|
||||
* @param text 原始文本
|
||||
* @param startString 起始字符串
|
||||
* @param startOffset 起始偏移量(从起始字符串开始计算)
|
||||
* @return 截取后的字符串
|
||||
*/
|
||||
public static String extractFromStartToEnd(String text, String startString, int startOffset) {
|
||||
if (text == null || startString == null) {
|
||||
return "";
|
||||
}
|
||||
|
||||
int startIndex = text.indexOf(startString);
|
||||
if (startIndex == -1) {
|
||||
return "";
|
||||
}
|
||||
|
||||
// 计算实际开始位置
|
||||
int actualStartIndex = startIndex + startOffset;
|
||||
|
||||
// 确保开始位置在有效范围内
|
||||
if (actualStartIndex < 0) {
|
||||
actualStartIndex = 0;
|
||||
} else if (actualStartIndex >= text.length()) {
|
||||
return "";
|
||||
}
|
||||
|
||||
return text.substring(actualStartIndex);
|
||||
}
|
||||
|
||||
/**
|
||||
* 从文本中截取字符串,从指定起始字符串开始,到指定结束字符串为止
|
||||
* @param text 原始文本
|
||||
* @param startString 起始字符串
|
||||
* @param endString 结束字符串
|
||||
* @return 截取后的字符串
|
||||
*/
|
||||
public static String extractBetweenStrings(String text, String startString, String endString) {
|
||||
if (text == null || startString == null || endString == null) {
|
||||
return "";
|
||||
}
|
||||
|
||||
int startIndex = text.indexOf(startString);
|
||||
if (startIndex == -1) {
|
||||
return "";
|
||||
}
|
||||
|
||||
// 从起始字符串位置开始查找结束字符串
|
||||
int endIndex = text.indexOf(endString, startIndex + startString.length());
|
||||
if (endIndex == -1) {
|
||||
// 如果找不到结束字符串,则截取到文本末尾
|
||||
return text.substring(startIndex);
|
||||
}
|
||||
|
||||
return text.substring(startIndex, endIndex + endString.length());
|
||||
}
|
||||
|
||||
/**
|
||||
* 高级版本:支持多个起始字符串选项和容错处理
|
||||
* @param text 原始文本
|
||||
* @param possibleStartStrings 可能的起始字符串数组(按优先级排序)
|
||||
* @return 截取后的字符串
|
||||
*/
|
||||
public static String extractWithFallback(String text, String[] possibleStartStrings) {
|
||||
if (text == null || possibleStartStrings == null || possibleStartStrings.length == 0) {
|
||||
return "";
|
||||
}
|
||||
|
||||
// 尝试每个可能的起始字符串
|
||||
for (String startString : possibleStartStrings) {
|
||||
int startIndex = text.indexOf(startString);
|
||||
if (startIndex != -1) {
|
||||
return text.substring(startIndex);
|
||||
}
|
||||
}
|
||||
|
||||
return ""; // 所有起始字符串都不存在
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 字符串截取方法
|
||||
* @param text 原始文本
|
||||
* @param startStr 开始字符串
|
||||
* @param startOffset 开始偏移量(负数表示向前)
|
||||
* @param endStr 结束字符串
|
||||
* @param endOffset 结束偏移量(负数表示向前)
|
||||
* @return 截取的字符串
|
||||
*/
|
||||
public static String extract(String text, String startStr, int startOffset,
|
||||
String endStr, int endOffset) {
|
||||
if (text == null || text.isEmpty()) {
|
||||
return "";
|
||||
}
|
||||
|
||||
int startIndex = 0;
|
||||
int endIndex = text.length();
|
||||
|
||||
// 处理开始位置
|
||||
if (startStr != null && !startStr.isEmpty()) {
|
||||
int foundStartIndex = text.indexOf(startStr);
|
||||
if (foundStartIndex == -1) {
|
||||
return ""; // 未找到开始字符串
|
||||
}
|
||||
startIndex = foundStartIndex + startStr.length() + startOffset;
|
||||
startIndex = Math.max(0, Math.min(startIndex, text.length()));
|
||||
} else {
|
||||
// 没有开始字符串,直接使用偏移量
|
||||
startIndex = Math.max(0, startOffset);
|
||||
startIndex = Math.min(startIndex, text.length());
|
||||
}
|
||||
|
||||
// 处理结束位置
|
||||
if (endStr != null && !endStr.isEmpty()) {
|
||||
int foundEndIndex = text.indexOf(endStr, startIndex);
|
||||
if (foundEndIndex == -1) {
|
||||
return ""; // 未找到结束字符串
|
||||
}
|
||||
endIndex = foundEndIndex + endOffset;
|
||||
endIndex = Math.max(0, Math.min(endIndex, text.length()));
|
||||
} else if (endOffset != 0) {
|
||||
// 没有结束字符串但有结束偏移量
|
||||
endIndex = startIndex + endOffset;
|
||||
endIndex = Math.max(0, Math.min(endIndex, text.length()));
|
||||
}
|
||||
// 如果结束字符串为空且结束偏移量为0,则endIndex保持为文本长度(截取到最后)
|
||||
|
||||
// 验证位置有效性
|
||||
if (startIndex >= endIndex || startIndex >= text.length()) {
|
||||
return "";
|
||||
}
|
||||
|
||||
return text.substring(startIndex, endIndex);
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
// 测试示例
|
||||
String text = "这是一段前置文本,然后是我们需要的内容,这是后续文本。";
|
||||
String startString = "然后";
|
||||
|
||||
System.out.println("=== 基本用法:从起始字符串第0位开始到文本末尾 ===");
|
||||
String result1 = extractFromStartToEnd(text, startString);
|
||||
System.out.println("结果1: " + result1);
|
||||
|
||||
System.out.println("\n=== 使用偏移量:从起始字符串第2位开始 ===");
|
||||
String result2 = extractFromStartToEnd(text, startString, 2);
|
||||
System.out.println("结果2: " + result2);
|
||||
|
||||
System.out.println("\n=== 在两个字符串之间截取 ===");
|
||||
String result3 = extractBetweenStrings(text, "然后", "后续");
|
||||
System.out.println("结果3: " + result3);
|
||||
|
||||
System.out.println("\n=== 使用多个可能的起始字符串 ===");
|
||||
String[] startOptions = {"不存在的字符串", "然后", "这是"};
|
||||
String result4 = extractWithFallback(text, startOptions);
|
||||
System.out.println("结果4: " + result4);
|
||||
|
||||
System.out.println("\n=== 处理边界情况 ===");
|
||||
// 测试起始字符串不存在的情况
|
||||
String result5 = extractFromStartToEnd(text, "不存在的字符串");
|
||||
System.out.println("起始字符串不存在: '" + result5 + "'");
|
||||
|
||||
// 测试空文本
|
||||
String result6 = extractFromStartToEnd("", startString);
|
||||
System.out.println("空文本: '" + result6 + "'");
|
||||
|
||||
// 测试实际应用场景
|
||||
System.out.println("\n=== 实际应用示例 ===");
|
||||
String logText = "2024-01-15 10:30:25 [INFO] User login successful. User ID: 12345, Session: abcdef";
|
||||
String logStart = "[INFO]";
|
||||
|
||||
String logResult = extractFromStartToEnd(logText, logStart);
|
||||
System.out.println("日志内容: " + logResult);
|
||||
|
||||
// 只提取消息部分(去掉日志级别)
|
||||
String messageResult = extractFromStartToEnd(logText, logStart, logStart.length());
|
||||
System.out.println("纯消息: " + messageResult.trim());
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 简化的文本截取方法
|
||||
* @param text 原始文本
|
||||
* @param startString 起始字符串
|
||||
* @return 从起始字符串开始到文本末尾的内容
|
||||
*/
|
||||
public static String extract(String text, String startString) {
|
||||
// 参数检查
|
||||
if (text == null || startString == null) {
|
||||
return "";
|
||||
}
|
||||
|
||||
// 查找起始字符串
|
||||
int startIndex = text.indexOf(startString);
|
||||
|
||||
// 如果找到起始字符串,则截取从该位置到末尾的内容
|
||||
if (startIndex != -1) {
|
||||
return text.substring(startIndex);
|
||||
}
|
||||
|
||||
return ""; // 起始字符串不存在
|
||||
}
|
||||
|
||||
public static void main22(String[] args) {
|
||||
// 示例使用
|
||||
String exampleText = "前置内容,这是起始点,这是我们需要的内容,继续到文本结束。";
|
||||
String start = "这是起始点";
|
||||
|
||||
String result = extract(exampleText, start);
|
||||
System.out.println("截取结果: " + result);
|
||||
|
||||
// 如果起始字符串不存在
|
||||
String noResult = extract(exampleText, "不存在的字符串");
|
||||
System.out.println("起始不存在: '" + noResult + "'");
|
||||
|
||||
String example = "前置文本{这是要截取的内容}后置文本";
|
||||
|
||||
// 从 { 前1位开始,到第一个 } 结束
|
||||
// String result = extract(example, '{', 0, '}', 0);
|
||||
//System.out.println("截取结果: " + result); // 输出: 前置文本{
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,355 @@
|
||||
package com.common.util;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.time.format.DateTimeParseException;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import com.common.entity.SyslogMessage;
|
||||
import com.common.entity.RFC3164Message;
|
||||
import com.common.entity.RFC5424Message;
|
||||
import com.influx.SyslogToInfluxApp;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import java.util.*;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import java.util.Locale;
|
||||
|
||||
public class SyslogParser {
|
||||
private static final Logger logger = LoggerFactory.getLogger(SyslogToInfluxApp.class);
|
||||
// RFC 5424 正则表达式
|
||||
private static final Pattern RFC5424_PATTERN = Pattern.compile(
|
||||
"^<(?<pri>\\d{1,3})>(?<version>\\d+) " +
|
||||
"(?<timestamp>\\S+) " +
|
||||
"(?<host>\\S+) " +
|
||||
"(?<app>\\S+) " +
|
||||
"(?<pid>\\S+) " +
|
||||
"(?<msgid>\\S+) " +
|
||||
"(?<sd>(?:-|\\[.*\\]))" +
|
||||
"(?: (?<message>.+))?$"
|
||||
);
|
||||
|
||||
// RFC 3164 正则表达式
|
||||
private static final Pattern RFC3164_PATTERN = Pattern.compile(
|
||||
"^<(?<pri>\\d{1,3})>" +
|
||||
"(?<timestamp>[A-Z][a-z]{2}\\s+\\d{1,2}\\s+\\d{2}:\\d{2}:\\d{2}) " +
|
||||
"(?<host>\\S+) " +
|
||||
"(?<content>.+)$"
|
||||
);
|
||||
|
||||
// RFC 3164 时间戳格式
|
||||
private static final DateTimeFormatter RFC3164_FORMATTER =
|
||||
DateTimeFormatter.ofPattern("MMM dd HH:mm:ss");
|
||||
|
||||
/**
|
||||
* 解析 Syslog 消息,自动检测格式
|
||||
*/
|
||||
public static SyslogMessage parse(String logLine) {
|
||||
if (logLine == null || logLine.trim().isEmpty()) {
|
||||
throw new IllegalArgumentException("Log line cannot be null or empty");
|
||||
}
|
||||
// 尝试解析为 RFC 5424 格式
|
||||
try {
|
||||
RFC5424Message msg5424 = parseRFC5424(logLine);
|
||||
if (msg5424 != null) {
|
||||
return msg5424;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
// 继续尝试 RFC 3164
|
||||
}
|
||||
|
||||
// 尝试解析为 RFC 3164 格式
|
||||
try {
|
||||
RFC3164Message msg3164 = parseRFC3164(logLine);
|
||||
if (msg3164 != null) {
|
||||
return msg3164;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
// 解析失败
|
||||
}
|
||||
// 解析非标数据格式,提取字符【{】自后的内容
|
||||
try {
|
||||
String content = extractJsonStringNew(logLine);
|
||||
RFC5424Message msgClass =new RFC5424Message();
|
||||
if (content != null) {
|
||||
msgClass.setMessage(content.toString());
|
||||
return msgClass;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
// 解析失败
|
||||
}
|
||||
throw new IllegalArgumentException("Unable to parse syslog message: " + logLine);
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析 RFC 5424 格式
|
||||
*/
|
||||
public static RFC5424Message parseRFC5424(String logLine) {
|
||||
Matcher matcher = RFC5424_PATTERN.matcher(logLine);
|
||||
if (!matcher.find()) {
|
||||
return null;
|
||||
}
|
||||
RFC5424Message message = new RFC5424Message();
|
||||
// 解析优先级
|
||||
int pri = Integer.parseInt(matcher.group("pri"));
|
||||
message.setPriority(pri);
|
||||
|
||||
// 解析版本
|
||||
message.setVersion(Integer.parseInt(matcher.group("version")));
|
||||
|
||||
// 解析时间戳 (RFC 3339 格式)
|
||||
String timestampStr = matcher.group("timestamp");
|
||||
try {
|
||||
message.setTimestamp(OffsetDateTime.parse(timestampStr));
|
||||
} catch (DateTimeParseException e) {
|
||||
throw new IllegalArgumentException("Invalid RFC5424 timestamp: " + timestampStr, e);
|
||||
}
|
||||
// 解析其他字段
|
||||
message.setHostname(matcher.group("host"));
|
||||
message.setAppName(matcher.group("app"));
|
||||
message.setProcId(matcher.group("pid"));
|
||||
message.setMsgId(matcher.group("msgid"));
|
||||
|
||||
// 解析结构化数据
|
||||
String sd = matcher.group("sd");
|
||||
if (!"-".equals(sd)) {
|
||||
message.setStructuredData(parseStructuredData(sd));
|
||||
}
|
||||
// 解析消息内容
|
||||
String msg = matcher.group("message");
|
||||
if (msg != null) {
|
||||
message.setMessage(msg.trim());
|
||||
}
|
||||
return message;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析 RFC 3164 格式
|
||||
*/
|
||||
public static RFC3164Message parseRFC3164(String logLine) {
|
||||
Matcher matcher = RFC3164_PATTERN.matcher(logLine);
|
||||
if (!matcher.find()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
RFC3164Message message = new RFC3164Message();
|
||||
|
||||
// 解析优先级
|
||||
int pri = Integer.parseInt(matcher.group("pri"));
|
||||
message.setPriority(pri);
|
||||
|
||||
// 解析时间戳 (需要特殊处理,因为没有年份)
|
||||
String timestampStr = matcher.group("timestamp");
|
||||
message.setTimestamp(parseRFC3164Timestamp(timestampStr));
|
||||
|
||||
// 解析主机名
|
||||
message.setHostname(matcher.group("host"));
|
||||
|
||||
// 解析内容和标签
|
||||
String content = matcher.group("content");
|
||||
parseRFC3164Content(content, message);
|
||||
|
||||
return message;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析 RFC 3164 时间戳
|
||||
*/
|
||||
private static OffsetDateTime parseRFC3164Timestamp(String timestampStr) {
|
||||
try {
|
||||
// 添加当前年份,因为 RFC3164 时间戳不包含年份
|
||||
String currentYear = String.valueOf(java.time.Year.now().getValue());
|
||||
String fullTimestamp = currentYear + " " + timestampStr;
|
||||
|
||||
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy MMM dd HH:mm:ss", Locale.US);
|
||||
LocalDateTime localDateTime = LocalDateTime.parse(fullTimestamp, formatter);
|
||||
// DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy MMM dd HH:mm:ss", Locale.US);
|
||||
|
||||
// 假设为系统默认时区
|
||||
return localDateTime.atOffset(ZoneOffset.systemDefault().getRules().getOffset(localDateTime));
|
||||
} catch (DateTimeParseException e) {
|
||||
throw new IllegalArgumentException("Invalid RFC3164 timestamp: " + timestampStr, e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析 RFC 3164 内容部分
|
||||
*/
|
||||
private static void parseRFC3164Content(String content, RFC3164Message message) {
|
||||
// 尝试匹配标签格式: app[pid]:
|
||||
Pattern tagPattern = Pattern.compile("^(?<tag>\\S+?)(?:\\[(?<pid>\\d+)\\])?:\\s*(?<message>.*)$");
|
||||
Matcher tagMatcher = tagPattern.matcher(content);
|
||||
|
||||
if (tagMatcher.find()) {
|
||||
message.setTag(tagMatcher.group("tag"));
|
||||
String pid = tagMatcher.group("pid");
|
||||
if (pid != null) {
|
||||
message.setProcId(pid);
|
||||
}
|
||||
message.setMessage(tagMatcher.group("message").trim());
|
||||
} else {
|
||||
// 如果没有标签格式,整个内容作为消息
|
||||
message.setTag("");
|
||||
message.setMessage(content.trim());
|
||||
}
|
||||
|
||||
// 对于 RFC3164,appName 通常与 tag 相同
|
||||
message.setAppName(message.getTag());
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析结构化数据
|
||||
*/
|
||||
private static Map<String, Map<String, String>> parseStructuredData(String sd) {
|
||||
Map<String, Map<String, String>> structuredData = new HashMap<>();
|
||||
|
||||
// 简单的结构化数据解析,实际应用可能需要更复杂的解析
|
||||
Pattern sdPattern = Pattern.compile("\\[(?<id>[^\\]]+)\\]");
|
||||
Pattern paramPattern = Pattern.compile("(?<key>[^=\\s]+)=\"(?<value>[^\"]*)\"");
|
||||
|
||||
Matcher sdMatcher = sdPattern.matcher(sd);
|
||||
while (sdMatcher.find()) {
|
||||
String sdElement = sdMatcher.group("id");
|
||||
Map<String, String> params = new HashMap<>();
|
||||
|
||||
Matcher paramMatcher = paramPattern.matcher(sdElement);
|
||||
while (paramMatcher.find()) {
|
||||
params.put(paramMatcher.group("key"), paramMatcher.group("value"));
|
||||
}
|
||||
// 使用第一个参数作为键,或者生成一个键
|
||||
String key = params.containsKey("sdId") ? params.get("sdId") :
|
||||
"element" + structuredData.size();
|
||||
structuredData.put(key, params);
|
||||
}
|
||||
return structuredData;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 提取 JSON 字符串(不解析)
|
||||
*/
|
||||
public static Optional<String> extractJsonString(String syslogMessage) {
|
||||
try {
|
||||
if (syslogMessage == null) return Optional.empty();
|
||||
|
||||
int jsonStart = syslogMessage.indexOf('{');
|
||||
if (jsonStart == -1) return Optional.empty();
|
||||
return Optional.of(syslogMessage.substring(jsonStart));
|
||||
} catch (Exception e) {
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 提取 JSON 字符串(不解析)
|
||||
*/
|
||||
public static String extractJsonStringNew (String syslogMessage) {
|
||||
try {
|
||||
if (syslogMessage == null) return "";
|
||||
|
||||
int jsonStart = syslogMessage.indexOf('{');
|
||||
if (jsonStart == -1) return "";
|
||||
|
||||
return syslogMessage.substring(jsonStart);
|
||||
} catch (Exception e) {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 截取字符串中第一个 ']' 之后的所有内容
|
||||
*
|
||||
* @param text 原始字符串
|
||||
* @return 第一个 ']' 之后的内容,如果没有 ']' 则返回空字符串
|
||||
*/
|
||||
public static String substringAfterFirstCloseBracket(String text) {
|
||||
if (text == null) {
|
||||
return "";
|
||||
}
|
||||
|
||||
int closeBracketIndex = text.indexOf(']');
|
||||
|
||||
if (closeBracketIndex == -1) {
|
||||
return ""; // 没有找到 ']',返回空字符串
|
||||
}
|
||||
|
||||
// 返回 ']' 之后的内容(+1 是为了跳过 ']' 本身)
|
||||
return text.substring(closeBracketIndex + 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* 截取字符串中第一个指定字符之前的所有内容
|
||||
*
|
||||
* @param text 原始字符串
|
||||
* @param delimiterChar 分隔字符
|
||||
* @return 分隔字符之前的内容
|
||||
*/
|
||||
public static String substringBeforeFirstChar(String text, char delimiterChar) {
|
||||
if (text == null) {
|
||||
return "";
|
||||
}
|
||||
|
||||
int delimiterIndex = text.indexOf(delimiterChar);
|
||||
|
||||
if (delimiterIndex == -1) {
|
||||
return text;
|
||||
}
|
||||
return text.substring(0, delimiterIndex+1);
|
||||
}
|
||||
|
||||
/**
|
||||
* 从文本中提取第一个 [] 包裹的键值对字符串并转换为 Map
|
||||
*
|
||||
* @param text 包含键值对的原始文本
|
||||
* @return 包含键值对的 Map
|
||||
* @throws IllegalArgumentException 如果格式不正确
|
||||
*/
|
||||
public static Map<String, String> parseKeyValuePairs(String text) {
|
||||
if (text == null || text.trim().isEmpty()) {
|
||||
throw new IllegalArgumentException("Input text cannot be null or empty");
|
||||
}
|
||||
|
||||
// 查找第一个 [ 和对应的 ]
|
||||
int start = text.indexOf('[');
|
||||
int end = text.indexOf(']', start + 1);
|
||||
|
||||
if (start == -1 || end == -1) {
|
||||
throw new IllegalArgumentException("No valid [] pair found in text");
|
||||
}
|
||||
|
||||
// 提取 [] 内的内容
|
||||
String content = text.substring(start + 1, end).trim();
|
||||
if (content.isEmpty()) {
|
||||
return new HashMap<>(); // 返回空Map
|
||||
}
|
||||
|
||||
// 分割键值对
|
||||
String[] pairs = content.split("\\s+");
|
||||
Map<String, String> result = new HashMap<>();
|
||||
|
||||
for (String pair : pairs) {
|
||||
// 分割键和值
|
||||
int equalSign = pair.indexOf('=');
|
||||
if (equalSign == -1) {
|
||||
throw new IllegalArgumentException("Invalid key-value pair format: " + pair);
|
||||
}
|
||||
|
||||
String key = pair.substring(0, equalSign).trim();
|
||||
String value = pair.substring(equalSign + 1).trim();
|
||||
|
||||
if (key.isEmpty()) {
|
||||
throw new IllegalArgumentException("Key cannot be empty in pair: " + pair);
|
||||
}
|
||||
|
||||
result.put(key, value);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
package com.common.util;
|
||||
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 分隔符文本解析工具类
|
||||
*/
|
||||
@Component
|
||||
public class TextParserUtil {
|
||||
|
||||
/**
|
||||
* 解析分隔符类型的文本数据
|
||||
* @param text 原始文本
|
||||
* @param sepKey 分隔符(字符或字符串)
|
||||
* @return LinkedHashMap对象,key为序号字符串,value为实际值
|
||||
*/
|
||||
public static LinkedHashMap<String, Object> parseSeparatedText(String text, String sepKey) {
|
||||
LinkedHashMap<String, Object> resultMap = new LinkedHashMap<>();
|
||||
|
||||
if (text == null || text.trim().isEmpty()) {
|
||||
return resultMap;
|
||||
}
|
||||
|
||||
if (sepKey == null || sepKey.isEmpty()) {
|
||||
// 如果分隔符为空,将整个文本作为第一个元素
|
||||
resultMap.put("1", text.trim());
|
||||
return resultMap;
|
||||
}
|
||||
|
||||
// 使用分隔符分割文本
|
||||
String[] parts = text.split(sepKey, -1); // 使用-1保留空字符串
|
||||
|
||||
// 将分割后的部分放入LinkedHashMap,键为字符串形式的序号
|
||||
for (int i = 0; i < parts.length; i++) {
|
||||
resultMap.put(String.valueOf(i + 1), parts[i].trim());
|
||||
}
|
||||
|
||||
return resultMap;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析分隔符文本并过滤空值
|
||||
* @param text 原始文本
|
||||
* @param sepKey 分隔符
|
||||
* @param removeEmpty 是否移除空值
|
||||
* @return LinkedHashMap对象
|
||||
*/
|
||||
public static LinkedHashMap<String, Object> parseSeparatedText(String text, String sepKey, boolean removeEmpty) {
|
||||
LinkedHashMap<String, Object> resultMap = parseSeparatedText(text, sepKey);
|
||||
|
||||
if (removeEmpty) {
|
||||
resultMap.entrySet().removeIf(entry ->
|
||||
entry.getValue() == null ||
|
||||
entry.getValue().toString().isEmpty());
|
||||
}
|
||||
|
||||
return resultMap;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析分隔符文本并转换为特定类型
|
||||
* @param text 原始文本
|
||||
* @param sepKey 分隔符
|
||||
* @param valueType 值类型(STRING, INTEGER, LONG, DOUBLE, BOOLEAN)
|
||||
* @return LinkedHashMap对象
|
||||
*/
|
||||
public static LinkedHashMap<String, Object> parseSeparatedTextWithType(
|
||||
String text, String sepKey, ValueType valueType) {
|
||||
LinkedHashMap<String, Object> resultMap = parseSeparatedText(text, sepKey);
|
||||
|
||||
if (valueType != ValueType.STRING) {
|
||||
resultMap.replaceAll((key, value) -> convertValue(value.toString(), valueType));
|
||||
}
|
||||
|
||||
return resultMap;
|
||||
}
|
||||
|
||||
/**
|
||||
* 值类型枚举
|
||||
*/
|
||||
public enum ValueType {
|
||||
STRING, INTEGER, LONG, DOUBLE, BOOLEAN
|
||||
}
|
||||
|
||||
/**
|
||||
* 值类型转换
|
||||
*/
|
||||
private static Object convertValue(String value, ValueType valueType) {
|
||||
if (value == null || value.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
switch (valueType) {
|
||||
case INTEGER:
|
||||
return Integer.parseInt(value);
|
||||
case LONG:
|
||||
return Long.parseLong(value);
|
||||
case DOUBLE:
|
||||
return Double.parseDouble(value);
|
||||
case BOOLEAN:
|
||||
return Boolean.parseBoolean(value) || "1".equals(value);
|
||||
case STRING:
|
||||
default:
|
||||
return value;
|
||||
}
|
||||
} catch (NumberFormatException e) {
|
||||
// 转换失败时返回原始字符串
|
||||
return value;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package com.config;
|
||||
|
||||
import com.typesafe.config.Config;
|
||||
import com.typesafe.config.ConfigFactory;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
public class AppConfig {
|
||||
private static final Config config;
|
||||
|
||||
static {
|
||||
// 加载配置文件
|
||||
File configFile = new File("application.properties");
|
||||
if (configFile.exists()) {
|
||||
config = ConfigFactory.parseFile(configFile);
|
||||
} else {
|
||||
config = ConfigFactory.load("application.properties");
|
||||
}
|
||||
}
|
||||
// Syslog 配置
|
||||
public static int getSyslogTcpPort() {
|
||||
return config.getInt("syslog.tcp.port");
|
||||
}
|
||||
|
||||
public static int getSyslogUdpPort() {
|
||||
return config.getInt("syslog.udp.port");
|
||||
}
|
||||
|
||||
public static int getSyslogMaxFrameLength() {
|
||||
return config.getInt("syslog.max.frame.length");
|
||||
}
|
||||
|
||||
public static int getSyslogBufferSize() {
|
||||
return config.getInt("syslog.buffer.size");
|
||||
}
|
||||
|
||||
// InfluxDB 配置
|
||||
public static String getInfluxUrl() {
|
||||
return config.getString("influxdb.url");
|
||||
}
|
||||
|
||||
public static String getInfluxToken() {
|
||||
return config.getString("influxdb.token");
|
||||
}
|
||||
|
||||
public static String getInfluxOrg() {
|
||||
return config.getString("influxdb.org");
|
||||
}
|
||||
|
||||
public static String getInfluxBucket() {
|
||||
return config.getString("influxdb.bucket");
|
||||
}
|
||||
|
||||
public static int getInfluxBatchSize() {
|
||||
return config.getInt("influxdb.batch.size");
|
||||
}
|
||||
|
||||
public static int getInfluxFlushInterval() {
|
||||
return config.getInt("influxdb.flush.interval");
|
||||
}
|
||||
|
||||
public static int getInfluxRetryAttempts() {
|
||||
return config.getInt("influxdb.retry.attempts");
|
||||
}
|
||||
|
||||
public static int getInfluxRetryDelay() {
|
||||
return config.getInt("influxdb.retry.delay");
|
||||
}
|
||||
|
||||
// 应用配置
|
||||
public static int getWorkerThreads() {
|
||||
return config.getInt("app.worker.threads");
|
||||
}
|
||||
|
||||
public static int getMaxQueueSize() {
|
||||
return config.getInt("app.max.queue.size");
|
||||
}
|
||||
|
||||
public static boolean isMetricsEnabled() { return config.getBoolean("app.metrics.enabled"); }
|
||||
|
||||
//kafka consumer应用配置
|
||||
|
||||
public static String getBootstrapServers() {
|
||||
return config.getString("spring.kafka.consumer.bootstrap-servers");
|
||||
}
|
||||
|
||||
public static String getGroupId() {
|
||||
return config.getString("spring.kafka.consumer.group-id");
|
||||
}
|
||||
|
||||
public static String getAutoOffsetReset() {
|
||||
return config.getString("spring.kafka.consumer.auto-offset-reset");
|
||||
}
|
||||
|
||||
public static boolean getEnableAutoCommit() { return config.getBoolean("spring.kafka.consumer.enable-auto-commit"); }
|
||||
|
||||
public static String getAutoCommitIntervalMS() { return config.getString("spring.kafka.consumer.auto-commit-interval");}
|
||||
|
||||
public static String getTopic() { return config.getString("spring.kafka.consumer.topic"); }
|
||||
|
||||
public static String geRunEnvironment() { return config.getString("server.run.environment"); }
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
package com.config;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.jsontype.BasicPolymorphicTypeValidator;
|
||||
import com.fasterxml.jackson.databind.jsontype.PolymorphicTypeValidator;
|
||||
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
|
||||
import org.springframework.cache.CacheManager;
|
||||
import org.springframework.cache.annotation.EnableCaching;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.data.redis.cache.RedisCacheConfiguration;
|
||||
import org.springframework.data.redis.cache.RedisCacheManager;
|
||||
import org.springframework.data.redis.connection.RedisConnectionFactory;
|
||||
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
|
||||
import org.springframework.data.redis.serializer.RedisSerializationContext;
|
||||
import org.springframework.data.redis.serializer.StringRedisSerializer;
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
import java.time.Duration;
|
||||
import java.util.Collections;
|
||||
import org.springframework.context.annotation.Primary;
|
||||
@Configuration
|
||||
@EnableCaching // 启用缓存
|
||||
public class CacheConfig {
|
||||
|
||||
/**
|
||||
* 配置支持类型信息的 ObjectMapper
|
||||
*/
|
||||
@Bean
|
||||
public ObjectMapper objectMapper() {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
// 注册 Java 8 日期时间支持
|
||||
mapper.registerModule(new JavaTimeModule());
|
||||
|
||||
// 禁用将日期序列化为时间戳
|
||||
mapper.disable(com.fasterxml.jackson.databind.SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
|
||||
|
||||
// 启用类型信息,解决 LinkedHashMap 转换问题
|
||||
PolymorphicTypeValidator ptv = BasicPolymorphicTypeValidator.builder()
|
||||
.allowIfSubType("com.common.entity.") // 允许你的实体类包
|
||||
.allowIfSubType("java.util.ArrayList") // 允许 ArrayList
|
||||
.allowIfSubType("java.util.LinkedList") // 允许 LinkedList
|
||||
.allowIfBaseType("java.util.List") // 允许 List 接口
|
||||
.allowIfBaseType("java.lang.Object") // 允许 Object 类型
|
||||
.build();
|
||||
|
||||
// 忽略未知属性
|
||||
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // [citation:1][citation:5][citation:7]
|
||||
// 遇到无效子类型时不立即失败,为你自定义反序列化逻辑留出空间
|
||||
mapper.configure(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE, false); // [citation:2][citation:5]
|
||||
|
||||
// 激活默认类型信息
|
||||
mapper.activateDefaultTyping(
|
||||
ptv,
|
||||
ObjectMapper.DefaultTyping.NON_FINAL,
|
||||
com.fasterxml.jackson.annotation.JsonTypeInfo.As.PROPERTY
|
||||
);
|
||||
|
||||
return mapper;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Redis 缓存配置
|
||||
*/
|
||||
@Bean
|
||||
public RedisCacheConfiguration redisCacheConfiguration() {
|
||||
ObjectMapper mapper = objectMapper();
|
||||
GenericJackson2JsonRedisSerializer serializer = new GenericJackson2JsonRedisSerializer(mapper);
|
||||
|
||||
return RedisCacheConfiguration.defaultCacheConfig()
|
||||
.entryTtl(Duration.ofMinutes(30))
|
||||
.disableCachingNullValues()
|
||||
.serializeKeysWith(RedisSerializationContext.SerializationPair
|
||||
.fromSerializer(new StringRedisSerializer()))
|
||||
.serializeValuesWith(RedisSerializationContext.SerializationPair
|
||||
.fromSerializer(serializer));
|
||||
}
|
||||
|
||||
@Bean
|
||||
public CacheManager cacheManager(RedisConnectionFactory factory) {
|
||||
ObjectMapper mapper = objectMapper();
|
||||
GenericJackson2JsonRedisSerializer serializer = new GenericJackson2JsonRedisSerializer(mapper);
|
||||
|
||||
RedisCacheConfiguration deviceConfig = RedisCacheConfiguration.defaultCacheConfig()
|
||||
.entryTtl(Duration.ofHours(1))
|
||||
.serializeKeysWith(RedisSerializationContext.SerializationPair
|
||||
.fromSerializer(new StringRedisSerializer()))
|
||||
.serializeValuesWith(RedisSerializationContext.SerializationPair
|
||||
.fromSerializer(serializer));
|
||||
|
||||
RedisCacheConfiguration collectTaskConfig = RedisCacheConfiguration.defaultCacheConfig()
|
||||
.entryTtl(Duration.ofHours(1))
|
||||
.serializeKeysWith(RedisSerializationContext.SerializationPair
|
||||
.fromSerializer(new StringRedisSerializer()))
|
||||
.serializeValuesWith(RedisSerializationContext.SerializationPair
|
||||
.fromSerializer(serializer));
|
||||
RedisCacheConfiguration normalizeRuleConfig = RedisCacheConfiguration.defaultCacheConfig()
|
||||
.entryTtl(Duration.ofHours(1))
|
||||
.serializeKeysWith(RedisSerializationContext.SerializationPair
|
||||
.fromSerializer(new StringRedisSerializer()))
|
||||
.serializeValuesWith(RedisSerializationContext.SerializationPair
|
||||
.fromSerializer(serializer));
|
||||
return RedisCacheManager.builder(factory)
|
||||
.cacheDefaults(redisCacheConfiguration())
|
||||
.withInitialCacheConfigurations(Collections.singletonMap(
|
||||
"device", deviceConfig
|
||||
))
|
||||
.withInitialCacheConfigurations(Collections.singletonMap(
|
||||
|
||||
"collectTask",collectTaskConfig
|
||||
))
|
||||
.withInitialCacheConfigurations(Collections.singletonMap(
|
||||
|
||||
"normalizeRule",normalizeRuleConfig
|
||||
))
|
||||
.transactionAware()
|
||||
.build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package com.config;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.data.redis.connection.RedisConnectionFactory;
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
|
||||
import org.springframework.data.redis.serializer.StringRedisSerializer;
|
||||
|
||||
@Configuration
|
||||
public class RedisConfig {
|
||||
|
||||
|
||||
@Bean
|
||||
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
|
||||
RedisTemplate<String, Object> template = new RedisTemplate<>();
|
||||
template.setConnectionFactory(factory);
|
||||
|
||||
// 使用 Jackson2JsonRedisSerializer 并指定类型
|
||||
Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>(Object.class);
|
||||
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
mapper.registerModule(new JavaTimeModule());
|
||||
mapper.activateDefaultTyping(
|
||||
mapper.getPolymorphicTypeValidator(),
|
||||
ObjectMapper.DefaultTyping.NON_FINAL
|
||||
);
|
||||
serializer.setObjectMapper(mapper);
|
||||
|
||||
template.setKeySerializer(new StringRedisSerializer());
|
||||
template.setValueSerializer(serializer);
|
||||
template.setHashKeySerializer(new StringRedisSerializer());
|
||||
template.setHashValueSerializer(serializer);
|
||||
template.afterPropertiesSet();
|
||||
|
||||
return template;
|
||||
}
|
||||
/**
|
||||
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
|
||||
RedisTemplate<String, Object> template = new RedisTemplate<>();
|
||||
template.setConnectionFactory(connectionFactory);
|
||||
|
||||
// 使用StringRedisSerializer来序列化和反序列化redis的key值
|
||||
template.setKeySerializer(new StringRedisSerializer());
|
||||
// 使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值
|
||||
Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>(Object.class);
|
||||
template.setValueSerializer(serializer);
|
||||
|
||||
// Hash的key和value也分别设置序列化器
|
||||
template.setHashKeySerializer(new StringRedisSerializer());
|
||||
template.setHashValueSerializer(serializer);
|
||||
|
||||
template.afterPropertiesSet();
|
||||
return template;
|
||||
}
|
||||
**/
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
|
||||
package com.config;
|
||||
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.http.client.ClientHttpRequestInterceptor;
|
||||
import org.springframework.http.client.SimpleClientHttpRequestFactory;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Configuration
|
||||
public class RestTemplateConfig {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(RestTemplateConfig.class);
|
||||
|
||||
@Bean
|
||||
public RestTemplate restTemplate() {
|
||||
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
|
||||
factory.setConnectTimeout(30000); // 30秒连接超时
|
||||
factory.setReadTimeout(60000); // 60秒读取超时
|
||||
|
||||
RestTemplate restTemplate = new RestTemplate(factory);
|
||||
|
||||
// 添加自定义日志拦截器,控制日志输出
|
||||
List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
|
||||
interceptors.add(new LoggingInterceptor());
|
||||
restTemplate.setInterceptors(interceptors);
|
||||
|
||||
return restTemplate;
|
||||
}
|
||||
|
||||
/**
|
||||
* 自定义日志拦截器,控制请求/响应日志
|
||||
*/
|
||||
public static class LoggingInterceptor implements ClientHttpRequestInterceptor {
|
||||
|
||||
@Override
|
||||
public org.springframework.http.client.ClientHttpResponse intercept(
|
||||
org.springframework.http.HttpRequest request,
|
||||
byte[] body,
|
||||
org.springframework.http.client.ClientHttpRequestExecution execution)
|
||||
throws java.io.IOException {
|
||||
|
||||
// 记录请求信息
|
||||
log.debug("请求URL: {}", request.getURI());
|
||||
log.debug("请求方法: {}", request.getMethod());
|
||||
log.debug("请求头: {}", request.getHeaders());
|
||||
|
||||
// 记录请求体(限制长度)
|
||||
if (log.isDebugEnabled() && body != null) {
|
||||
String requestBody = new String(body, "UTF-8");
|
||||
int printLength = Math.min(200, requestBody.length());
|
||||
log.debug("请求体 (前{}字符): {}", printLength, requestBody.substring(0, printLength));
|
||||
}
|
||||
|
||||
// 执行请求
|
||||
org.springframework.http.client.ClientHttpResponse response = execution.execute(request, body);
|
||||
|
||||
// 记录响应信息
|
||||
log.debug("响应状态码: {}", response.getStatusCode());
|
||||
log.debug("响应头: {}", response.getHeaders());
|
||||
|
||||
// 注意:这里不要直接读取响应体,否则会导致后续无法读取
|
||||
// 使用BufferingClientHttpResponseWrapper包装响应
|
||||
|
||||
return response;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.config;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
|
||||
@Configuration
|
||||
@EnableScheduling
|
||||
public class ScheduleConfig {
|
||||
// 启用定时任务支持
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.config;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.scheduling.annotation.EnableAsync;
|
||||
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
|
||||
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.concurrent.ThreadPoolExecutor;
|
||||
import org.springframework.context.annotation.Primary;
|
||||
@Configuration
|
||||
@EnableAsync
|
||||
public class ThreadPoolConfig {
|
||||
|
||||
@Value("${app.processor.thread-pool.core-pool-size:10}")
|
||||
private int corePoolSize;
|
||||
|
||||
@Value("${app.processor.thread-pool.max-pool-size:20}")
|
||||
private int maxPoolSize;
|
||||
|
||||
@Value("${app.processor.thread-pool.queue-capacity:2000}")
|
||||
private int queueCapacity;
|
||||
|
||||
@Value("${app.processor.thread-pool.keep-alive-seconds:60}")
|
||||
private int keepAliveSeconds;
|
||||
|
||||
@Bean("logNormalProcessorExecutor")
|
||||
@Primary // 添加这个注解
|
||||
public Executor logNormalProcessorExecutor() {
|
||||
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
|
||||
executor.setCorePoolSize(corePoolSize);
|
||||
executor.setMaxPoolSize(maxPoolSize);
|
||||
executor.setQueueCapacity(queueCapacity);
|
||||
executor.setKeepAliveSeconds(keepAliveSeconds);
|
||||
executor.setThreadNamePrefix("log-processor-");
|
||||
|
||||
// 拒绝策略:由调用线程处理该任务(保证不丢失消息)
|
||||
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
|
||||
|
||||
// 等待所有任务结束后再关闭线程池
|
||||
executor.setWaitForTasksToCompleteOnShutdown(true);
|
||||
executor.setAwaitTerminationSeconds(60);
|
||||
executor.initialize();
|
||||
return executor;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package com.config;
|
||||
|
||||
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.http.converter.HttpMessageConverter;
|
||||
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Configuration
|
||||
public class WebConfig implements WebMvcConfigurer {
|
||||
|
||||
/**
|
||||
* 创建专门用于 HTTP 请求的 ObjectMapper
|
||||
*/
|
||||
@Bean
|
||||
public ObjectMapper httpObjectMapper() {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
// 注册 Java 8 日期时间支持
|
||||
mapper.registerModule(new JavaTimeModule());
|
||||
|
||||
// 禁用将日期序列化为时间戳
|
||||
mapper.disable(com.fasterxml.jackson.databind.SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
|
||||
|
||||
// 忽略未知属性
|
||||
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
|
||||
|
||||
// 确保禁用所有类型信息
|
||||
mapper.deactivateDefaultTyping();
|
||||
|
||||
return mapper;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建 HTTP 消息转换器
|
||||
*/
|
||||
@Bean
|
||||
public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
|
||||
return new MappingJackson2HttpMessageConverter(httpObjectMapper());
|
||||
}
|
||||
|
||||
/**
|
||||
* 注册消息转换器到 Spring MVC
|
||||
*/
|
||||
@Override
|
||||
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
|
||||
// 将 Jackson 转换器添加到转换器列表的开头
|
||||
converters.add(0, mappingJackson2HttpMessageConverter());
|
||||
}
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
package com.controllers;
|
||||
|
||||
|
||||
import com.common.entity.AppLog;
|
||||
import com.common.service.ElasticsearchService;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
@Slf4j
|
||||
@RestController
|
||||
@RequestMapping("/api/applog")
|
||||
public class AppLogController {
|
||||
|
||||
@Autowired
|
||||
private ElasticsearchService elasticsearchService;
|
||||
|
||||
/**
|
||||
* 保存日志到ES
|
||||
*/
|
||||
@PostMapping
|
||||
public String saveAppLog(@RequestBody AppLog appLog) {
|
||||
// 生成唯一ID(如果前端没有提供)
|
||||
if (appLog.getId() == null) {
|
||||
appLog.setId(UUID.randomUUID().toString());
|
||||
}
|
||||
|
||||
elasticsearchService.saveAppLog(appLog);
|
||||
return "保存成功";
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user