增加定时器功能

Conflicts:
	src/main/webapp/WEB-INF/views/cfg/ipaddr/ipList.jsp
This commit is contained in:
zhangwei
2019-01-26 18:02:44 +06:00
parent 5c63f85483
commit 9d6e3a3d4a
41 changed files with 5184 additions and 335 deletions

View File

@@ -0,0 +1,43 @@
package com.nis.domain;
import com.nis.domain.configuration.BaseCfg;
/**
* 定时任务信息 schedule_info
* @author ThinkPad
*
*/
public class ScheduleCfg extends BaseCfg<ScheduleCfg>{
private static final long serialVersionUID = 7151915080876949497L;
private String name;//定时任务名称,预留
private String cronValid;//生效cron表达式
private String cronInvalid;//失效cron表达式
private String whereStr;//动态where 条件
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCronValid() {
return cronValid;
}
public void setCronValid(String cronValid) {
this.cronValid = cronValid;
}
public String getCronInvalid() {
return cronInvalid;
}
public void setCronInvalid(String cronInvalid) {
this.cronInvalid = cronInvalid;
}
public String getWhereStr() {
return whereStr;
}
public void setWhereStr(String whereStr) {
this.whereStr = whereStr;
}
}

View File

@@ -0,0 +1,66 @@
package com.nis.domain;
import java.util.Date;
import com.nis.domain.configuration.BaseCfg;
/**
* 定时任务执行信息 schedule_exce_log/schedule_exce_new
* `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键自增',
`schedule_id` bigint(20) NOT NULL COMMENT 'schedule_info 表的主键',
`exce_time` datetime DEFAULT NULL COMMENT '最新执行时间',
`issue_status` int(255) DEFAULT NULL COMMENT '下发状态1生效0失效',
`issue_result` int(255) DEFAULT NULL COMMENT '下发结果1成功0失败',
`error_info` varchar(255) DEFAULT NULL COMMENT '下发失败原因',
`compile_id` bigint(20) DEFAULT NULL COMMENT '编译id',
* @author fang
*
*/
public class ScheduleExceInfo extends BaseCfg<ScheduleExceInfo>{
private static final long serialVersionUID = 7151915080876949497L;
private Long scheduleId;//定时器id
private Date exceTime;//下发时间
private Integer issueStatus;//下发 的状态
private Integer issueResult;//下发结果
private String errorInfo;//动态where 条件
private Integer isIssue;//是否需要下发配置1需要0不需要
public Long getScheduleId() {
return scheduleId;
}
public void setScheduleId(Long scheduleId) {
this.scheduleId = scheduleId;
}
public Date getExceTime() {
return exceTime;
}
public void setExceTime(Date exceTime) {
this.exceTime = exceTime;
}
public Integer getIssueStatus() {
return issueStatus;
}
public void setIssueStatus(Integer issueStatus) {
this.issueStatus = issueStatus;
}
public Integer getIssueResult() {
return issueResult;
}
public void setIssueResult(Integer issueResult) {
this.issueResult = issueResult;
}
public String getErrorInfo() {
return errorInfo;
}
public void setErrorInfo(String errorInfo) {
this.errorInfo = errorInfo;
}
public Integer getIsIssue() {
return isIssue;
}
public void setIsIssue(Integer isIssue) {
this.isIssue = isIssue;
}
}

View File

@@ -16,6 +16,7 @@ import com.fasterxml.jackson.annotation.JsonFormat;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import com.nis.domain.BaseEntity;
import com.nis.domain.ScheduleCfg;
import com.nis.domain.SysMenu;
import com.nis.util.Constants;
import com.nis.util.StringUtil;
@@ -60,6 +61,14 @@ public class BaseCfg<T> extends BaseEntity<T> implements Cloneable{
protected Integer compileIsIssued;
protected String exType;//导出类型
protected String hColumns;//导出隐藏列
/**
* 定时任务信息
*/
//protected List<ScheduleCfg> schedules;
/**
* 定时任务信息2019年1月18日18:54:53 修改
*/
protected ScheduleCfg schedule;
public String getExType() {
return exType;
@@ -971,5 +980,12 @@ public class BaseCfg<T> extends BaseEntity<T> implements Cloneable{
public void setDoBlackList(Integer doBlackList) {
this.doBlackList = doBlackList;
}
public ScheduleCfg getSchedule() {
return schedule;
}
public void setSchedule(ScheduleCfg schedule) {
this.schedule = schedule;
}
}

View File

@@ -54,6 +54,8 @@ public class ToUpdateMaatBeanStatus implements Serializable{
@Expose
private Integer isValid;
@Expose
private Integer service;
@Expose
@SerializedName("opTime")
private Date auditTime;
public Integer getCompileId() {
@@ -74,6 +76,12 @@ public class ToUpdateMaatBeanStatus implements Serializable{
public void setAuditTime(Date auditTime) {
this.auditTime = auditTime;
}
public Integer getService() {
return service;
}
public void setService(Integer service) {
this.service = service;
}
}
public String getVersion() {

View File

@@ -0,0 +1,93 @@
package com.nis.persistence.interceptor;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.apache.log4j.Logger;
import com.nis.domain.ScheduleCfg;
import com.nis.domain.configuration.BaseCfg;
import com.nis.util.ServiceConfigTemplateUtil;
/**
* 定时任务 拦截器
* 1、拦截 select 操作
* 2、判断是否 form 查询配置主表
* 3、如果是配置主表查询对应的 scheduleCfg信息
* @author fang
*
*/
@Intercepts({@Signature(type = Executor.class,
method = "query",
args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})})
public class ScheduleSelectInterceptor extends BaseInterceptor{
private static final long serialVersionUID = -265785145929843646L;
private static final Logger logger = Logger.getLogger(ScheduleSelectInterceptor.class);
@Override
@SuppressWarnings("all")
public Object intercept(Invocation invocation) throws Throwable {
final MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
final Executor executor = (Executor)invocation.getTarget();
// select sql 查询结果
Object result = invocation.proceed();
if(result != null ) {
if(result instanceof Collection) {
Collection c = (Collection)result;
// if(c.size()==1) {//如果只查询一个 配置可以判定为是 form update 页面查询
if(c.size() >0) {//配置列表需要查询是否为定时任务,所以需要遍历
Iterator iterator = c.iterator();
while(iterator.hasNext()){
Object next = iterator.next();
if(next instanceof BaseCfg<?>) {
BaseCfg cfg = (BaseCfg)next;
//结果集的类名
String simpleName = next.getClass().getSimpleName();
//根据类名查找对应的 表名
String tableName = ServiceConfigTemplateUtil.getCfgTableNameByClassName(simpleName);
if(tableName != null) {//是配置主表
Configuration configuration = mappedStatement.getConfiguration();
MappedStatement scheduleStmt = configuration.getMappedStatement("com.nis.web.dao.SchedulerDao.findScheduleList");
ScheduleCfg sc = new ScheduleCfg();
sc.setTableName(tableName);
sc.setCfgId(cfg.getCfgId());
sc.setCompileId(cfg.getCompileId());
//executor.clearLocalCache();
List<ScheduleCfg> schedules = executor.query(scheduleStmt, sc, RowBounds.DEFAULT, Executor.NO_RESULT_HANDLER);
if(schedules != null&& schedules.size() > 0) {
cfg.setSchedule(schedules.get(0));
}
logger.debug(String.format("配置bean中赋值scheduleCfg,表名:%s,类名:%s,cfgId:%s,compileId:%s,schedules num:%s", tableName,simpleName,sc.getCfgId(),sc.getCompileId(),schedules==null?0:schedules.size()));
}
}else{
break;
}
}
}
}
}
return result;
}
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
@Override
public void setProperties(Properties properties) {
}
}

View File

@@ -0,0 +1,389 @@
package com.nis.persistence.interceptor;
import java.lang.reflect.Array;
import java.sql.SQLException;
import java.text.DateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Properties;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.type.TypeHandlerRegistry;
import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import com.alibaba.druid.sql.ast.statement.SQLUpdateSetItem;
import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlUpdateStatement;
import com.alibaba.druid.sql.dialect.mysql.parser.MySqlStatementParser;
import com.google.common.collect.Lists;
import com.nis.domain.ScheduleCfg;
import com.nis.domain.ScheduleExceInfo;
import com.nis.domain.configuration.BaseCfg;
import com.nis.util.ServiceConfigTemplateUtil;
import com.nis.web.security.UserUtils;
import jersey.repackaged.com.google.common.collect.Sets;
/**
* 定时任务 拦截器
* 1、拦截insert,update,delete操作
* 2、判断是否是需要下发配置的表
* 3、如果是需要下发配置的表则同时将数据保存到schedule_cfg表中并调用定时任务
* @author fang
*
*/
@Intercepts({@Signature(
type= Executor.class,
method = "update",
args = {MappedStatement.class,Object.class})})
public class ScheduleUpdateInterceptor extends BaseInterceptor{
private static final long serialVersionUID = -265785145929843646L;
private static final Logger logger = Logger.getLogger(ScheduleUpdateInterceptor.class);
private static final String TABLE_NAME_INSERT_REG = "^\\s*insert\\s+into\\s+([\\w_-]+)\\s*\\(";
private static final Pattern TABLE_NAME_INSERT_PATTERN = Pattern.compile(TABLE_NAME_INSERT_REG, Pattern.CASE_INSENSITIVE);//大小写
private static final String TABLE_NAME_UPDATE_REG = "^\\s*update\\s+([\\w_-]+)";
private static final Pattern TABLE_NAME_UPDATE_PATTERN = Pattern.compile(TABLE_NAME_UPDATE_REG, Pattern.CASE_INSENSITIVE);//大小写
private static final String TABLE_NAME_DELETE_REG = "^\\s*delete\\s+from\\s+([\\w_-]+)";
private static final Pattern TABLE_NAME_DELETE_PATTERN = Pattern.compile(TABLE_NAME_DELETE_REG, Pattern.CASE_INSENSITIVE);//大小写
/**
* 排除拦截的id
*/
private static final Set<String> EXCLUDE_MAPPER_IDS = Sets.newHashSet();
static {
EXCLUDE_MAPPER_IDS.add("com.nis.web.dao.SchedulerDao.updateCfgTableStatus");
EXCLUDE_MAPPER_IDS.add("com.nis.web.dao.basics.ServiceDictInfoDao");
}
/**
* is_valid 字段名
*/
private static final String IS_VALID_COLUMN = "is_valid";
/**
* is_audit 字段名
*/
private static final String IS_AUDIT_COLUMN = "is_audit";
@Override
@SuppressWarnings("all")
public Object intercept(Invocation invocation) throws Throwable {
final MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
final Executor executor = (Executor)invocation.getTarget();
Object parameter = invocation.getArgs()[1];//被拦截的 sql 参数
BoundSql boundSql = mappedStatement.getBoundSql(parameter);
Object result = invocation.proceed();//被拦截的 sql 操作 继续执行
String curProceedId = mappedStatement.getId();
//不需要拦截的操作直接返回结果
if(EXCLUDE_MAPPER_IDS.contains(curProceedId)) {
return result;
}
String tableName = null;//操作的表名
//mybatis 整个mapper 信息
Configuration configuration = mappedStatement.getConfiguration();
//被拦截的 sql语句
String sql = boundSql.getSql();
//所有需要拦截的表名
Set<String> tableNames = ServiceConfigTemplateUtil.getCompileTableName();
switch (mappedStatement.getSqlCommandType()) {
case INSERT://新增配置
Matcher insertMatcher = TABLE_NAME_INSERT_PATTERN.matcher(sql);
tableName = insertMatcher.find()?insertMatcher.group(1):tableName;
if(tableName != null && tableNames.contains(tableName.toLowerCase())) {
insertCfg(executor,parameter, configuration,tableName);
}
break;
case UPDATE://更新配置
Matcher updateMatcher = TABLE_NAME_UPDATE_PATTERN.matcher(sql);
tableName = updateMatcher.find()?updateMatcher.group(1):tableName;
if(tableName != null && tableNames.contains(tableName.toLowerCase())) {
updateCfg(executor,boundSql, configuration,tableName);
}
break;
case DELETE://删除配置
Matcher deleteMatcher = TABLE_NAME_DELETE_PATTERN.matcher(sql);
tableName = deleteMatcher.find()?deleteMatcher.group(1):tableName;
if(tableName != null && tableNames.contains(tableName.toLowerCase())) {
deleteCfg(executor,parameter, configuration,tableName);
}
break;
default:
break;
}
logger.debug(sql);
return result;
}
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
/**
* @throws SQLException
*
*/
@SuppressWarnings("all")
private void insertCfg(Executor executor,Object parameterObject,Configuration configuration,String tableName) throws SQLException {
List<BaseCfg> cfgList = Lists.newArrayList();
//确保 单个,批量都适用
if(parameterObject instanceof BaseCfg<?>) {//单个添加
BaseCfg<?> baseCfg = (BaseCfg<?>)parameterObject;
cfgList.add(baseCfg);
}else if(parameterObject instanceof Collection) {
Collection<BaseCfg<?>> bcCollection = (Collection<BaseCfg<?>>)parameterObject;
cfgList.addAll(bcCollection);
}else if(parameterObject.getClass().isArray()) {
int length = Array.getLength(parameterObject);
for(int i = 0;i< length;i++) {
BaseCfg<?> baseCfg = (BaseCfg<?>)Array.get(parameterObject, i);
cfgList.add(baseCfg);
}
}
//整理需要 insert 的 schedule_cfg 的数据
List<ScheduleCfg> scheduleList = Lists.newArrayList();
for(BaseCfg<?> baseCfg : cfgList) {
baseCfg.setIsValid(0);//设置默认值
baseCfg.setIsAudit(0);//设置默认值
ScheduleCfg scList = copyScheduleCfgFromBaseCfg(baseCfg, tableName);
if(scList!=null){
scheduleList.add(scList);
}
}
if(scheduleList.size() > 0) {
for(ScheduleCfg sc : scheduleList) {
MappedStatement statement = configuration.getMappedStatement("com.nis.web.dao.SchedulerDao.insert");
executor.update(statement, sc);
}
}
}
/**
*
*/
@SuppressWarnings("all")
private void updateCfg(Executor executor,BoundSql boundSql,Configuration configuration,String tableName) throws SQLException {
/*
* 条件1 is_valid=0,is_audit=0; 未生效之前修改,来自修改页面
*1、首先将所有相关定时任务信息取消
*2、 新增 定时任务信息
*/
Object parameterObject = boundSql.getParameterObject();
if(parameterObject instanceof BaseCfg) {
BaseCfg bc = (BaseCfg)parameterObject;
Integer isValid = bc.getIsValid();
Integer isAudit = bc.getIsAudit();
Integer compileId = bc.getCompileId();
Long cfgId = bc.getCfgId();
if(isValid == 0 && isAudit == 0) {
ScheduleCfg sc = new ScheduleCfg();
sc.setCompileId(compileId);
sc.setEditorId(bc.getEditorId());
sc.setEditTime(bc.getEditTime());
sc.setCfgId(cfgId);
//根据 compileId 删除之前的
MappedStatement statement = configuration.getMappedStatement("com.nis.web.dao.SchedulerDao.deleteByCompileId");
executor.update(statement, sc);
//新增 更改的
ScheduleCfg schedule = copyScheduleCfgFromBaseCfg(bc, tableName);
if(schedule != null ) {
statement = configuration.getMappedStatement("com.nis.web.dao.SchedulerDao.insert");
executor.update(statement, schedule);
//配置信息新增,或取消之后重新修改,需要修改 exce_new表的状态
statement = configuration.getMappedStatement("com.nis.web.dao.SchedulerDao.updateScheduleExceNew");
ScheduleExceInfo exceNew = new ScheduleExceInfo();
exceNew.setCompileId(compileId);
exceNew.setIssueStatus(1);
exceNew.setIsIssue(1);//定时任务执行时需要下发配置
executor.update(statement, exceNew);
}
return;
}
}
//完整的sql语句已经完成 ? 替换
String sql = showSql(configuration, boundSql);
log.debug(String.format("cfg update sql : " , sql));
//其它剩余基本判定为 修改状态的 update
MySqlStatementParser parser = new MySqlStatementParser(sql);
MySqlUpdateStatement updateSqlStmt = (MySqlUpdateStatement)parser.parseStatement();
List<SQLUpdateSetItem> items = updateSqlStmt.getItems();
/* 分别获取 is_audit & is_valid 的值*/
Integer isValid = null;
Integer isAudit = null;
for(SQLUpdateSetItem item : items) {
if(IS_VALID_COLUMN.equalsIgnoreCase(item.getColumn().toString())) {
isValid = Integer.valueOf(item.getValue().toString());
continue;
}
if(IS_AUDIT_COLUMN.equalsIgnoreCase(item.getColumn().toString())) {
isAudit = Integer.valueOf(item.getValue().toString());
continue;
}
if(isValid != null && isAudit != null) {
break;
}
}
//isValid 和 isAudit 同时为空,目前发现有 取消来函的 update 操作有此情况
if(isValid == null && isAudit == null) {
return;
}
//获取当前的update 条件
String whereStr = updateSqlStmt.getWhere().toString();
StringBuilder whereSb = new StringBuilder();
whereSb.append(" and table_name = '");
whereSb.append(tableName);
whereSb.append("' and ( ");
whereSb.append(whereStr);
whereSb.append(" )");
//根据当前的 update 条件 查出所有符合条件的 schedule_cfg 数据
MappedStatement scheduleStmt = configuration.getMappedStatement("com.nis.web.dao.SchedulerDao.findScheduleList");
ScheduleCfg sc = new ScheduleCfg();
sc.setWhereStr(whereSb.toString());
List<ScheduleCfg> schedules = executor.query(scheduleStmt, sc, RowBounds.DEFAULT, Executor.NO_RESULT_HANDLER);
if(schedules != null && schedules.size() > 0) {//有符合条件的 定时任务
Set<Integer> compileSet = Sets.newHashSet();//保存操作的所有 compileId
Date now = new Date();//当前时间
//1、将符合条件的是 ScheduleCfg update del_flag = 0
for(ScheduleCfg scfg : schedules) {
compileSet.add(scfg.getCompileId());
scfg.setEditorId(UserUtils.getUser().getId());
scfg.setEditTime(now);
MappedStatement statement = configuration.getMappedStatement("com.nis.web.dao.SchedulerDao.deleteByCompileId");
executor.update(statement, scfg);
}
//2、把原信息 重新保存,并修改 is_valid ,is_audit 状态
for(ScheduleCfg scfg : schedules) {
MappedStatement statement = configuration.getMappedStatement("com.nis.web.dao.SchedulerDao.insert");
scfg.setIsValid(isValid);
scfg.setIsAudit(isAudit);
executor.update(statement, scfg);
}
//手动 审核通过,立即生效时 已经下发,修改 exce_new 表的是否需要下发字段为 不需要 0
if(isValid == 1 && isAudit == 1) {
for(Integer ci : compileSet) {
MappedStatement statement = configuration.getMappedStatement("com.nis.web.dao.SchedulerDao.findScheduleExceNew");
ScheduleExceInfo se = new ScheduleExceInfo();
se.setCompileId(ci);
se.setIsValid(isValid);
List<ScheduleExceInfo> seList = executor.query(statement, se, RowBounds.DEFAULT, Executor.NO_RESULT_HANDLER);
if(seList == null || seList.size() < 1) {//没有执行记录,新增一条
//配置信息新增,或取消之后重新修改,需要修改 exce_new表的状态
statement = configuration.getMappedStatement("com.nis.web.dao.SchedulerDao.insertScheduleExceNew");
ScheduleExceInfo exceNew = new ScheduleExceInfo();
exceNew.setCompileId(ci);
exceNew.setIssueStatus(1);
exceNew.setIsIssue(0);//已经下发,定时任务不需要下发
exceNew.setExceTime(new Date());
executor.update(statement, exceNew);
}else {
//配置信息新增,或取消之后重新修改,需要修改 exce_new表的状态
statement = configuration.getMappedStatement("com.nis.web.dao.SchedulerDao.updateScheduleExceNew");
ScheduleExceInfo exceNew = new ScheduleExceInfo();
exceNew.setCompileId(ci);
exceNew.setIssueStatus(1);
exceNew.setIsIssue(0);//已经下发,定时任务不需要下发
executor.update(statement, exceNew);
}
}
}
}
}
/**
* 暂时没有发现有 删除操作
*/
@SuppressWarnings("all")
private void deleteCfg(Executor executor,Object parameterObject,Configuration configuration,String tableName) throws SQLException {
}
/**
* 从 basecfg 实体类中获取 schedule cfg
* @param baseCfg
* @param tableName
* @return
*/
private ScheduleCfg copyScheduleCfgFromBaseCfg(BaseCfg<?> baseCfg,String tableName){
ScheduleCfg schedule = baseCfg.getSchedule();
if(schedule != null ) {
BeanUtils.copyProperties(baseCfg, schedule,new String[]{"userRegion1","userRegion2","userRegion3","userRegion4","userRegion5"});
schedule.setTableName(tableName);
}
return schedule;
}
/*如果参数是String则添加单引号 如果是日期,则转换为时间格式器并加单引号; 对参数是null和不是null的情况作了处理*/
private static String getParameterValue(Object obj) {
String value = null;
if (obj instanceof String) {
value = "'" + obj.toString() + "'";
} else if (obj instanceof Date) {
DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.getDefault());
value = "'" + formatter.format(new Date()) + "'";
} else {
if (obj != null) {
value = obj.toString();
} else {
value = "null";
}
}
return value;
}
// 进行?的替换
public static String showSql(Configuration configuration, BoundSql boundSql) {
Object parameterObject = boundSql.getParameterObject(); // 获取参数
List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
String sql = boundSql.getSql().replaceAll("[\\s]+", " "); // sql语句中多个空格都用一个空格代替
if (parameterMappings != null && parameterMappings.size() >0 && parameterObject != null) {
TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry(); // 获取类型处理器注册器类型处理器的功能是进行java类型和数据库类型的转换<br>       // 如果根据parameterObject.getClass()可以找到对应的类型,则替换
if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
sql = sql.replaceFirst("\\?", Matcher.quoteReplacement(getParameterValue(parameterObject)));
} else {
MetaObject metaObject = configuration.newMetaObject(parameterObject);// MetaObject主要是封装了originalObject对象提供了get和set的方法用于获取和设置originalObject的属性值,主要支持对JavaBean、Collection、Map三种类型对象的操作
for (ParameterMapping parameterMapping : parameterMappings) {
String propertyName = parameterMapping.getProperty();
if (metaObject.hasGetter(propertyName)) {
Object obj = metaObject.getValue(propertyName);
sql = sql.replaceFirst("\\?", Matcher.quoteReplacement(getParameterValue(obj)));
} else if (boundSql.hasAdditionalParameter(propertyName)) {
Object obj = boundSql.getAdditionalParameter(propertyName); // 该分支是动态sql
sql = sql.replaceFirst("\\?", Matcher.quoteReplacement(getParameterValue(obj)));
}else{sql=sql.replaceFirst("\\?","缺失");}//打印出缺失,提醒该参数缺失并防止错位
}
}
}
return sql;
}
@Override
public void setProperties(Properties properties) {
// TODO Auto-generated method stub
}
}

View File

@@ -0,0 +1,519 @@
package com.nis.quartz;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.log4j.Logger;
import org.quartz.CalendarIntervalScheduleBuilder;
import org.quartz.CalendarIntervalTrigger;
import org.quartz.CronScheduleBuilder;
import org.quartz.DateBuilder;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobBuilder;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobKey;
import org.quartz.PersistJobDataAfterExecution;
import org.quartz.ScheduleBuilder;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.SimpleTrigger;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.quartz.impl.matchers.GroupMatcher;
import org.quartz.impl.triggers.CalendarIntervalTriggerImpl;
import org.quartz.impl.triggers.CronTriggerImpl;
import org.quartz.spi.MutableTrigger;
import com.nis.domain.ScheduleCfg;
import com.nis.util.Constants;
import com.nis.util.DateUtil;
import com.nis.util.DateUtils;
import com.nis.util.StringUtils;
import com.nis.web.dao.SchedulerDao;
import com.nis.web.service.SpringContextHolder;
/**
* 定时任务 配置定时任务加载
* 1、每 n s 执行一次,每次读取 schedule_cfg 最新的数据
* 2、删除或新增 定时任务
* 3、单线程执行
* @author fang
*
*/
@DisallowConcurrentExecution
@PersistJobDataAfterExecution
public class ScheduleCfgJob implements Job {
private static final Logger log = Logger.getLogger(ScheduleCfgJob.class);
/**
* 状态组格式statusGroup-compileId
*/
private static final String STATUS_GROUP = "statusGroup-";
private static final String STATUS_JOB = "STATUS-JOB";
/**
* 生效标识valid-cronexp
*/
private static final String VALID_KEY = "valid-";
/**
* 失效标识invalid-cronexp
*/
private static final String INVALID_KEY = "invalid-";
private static final JobKey STATUS_JOBKEY = JobKey.jobKey(STATUS_JOB, "statusGroup");
private static final JobDetail STATUS_JOBDETAIL = JobBuilder.newJob(ScheduleStatusJob.class)
.withIdentity(STATUS_JOBKEY)
.storeDurably(true)
.build();
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
Scheduler scheduler = context.getScheduler();
SchedulerDao dao = SpringContextHolder.getBean(SchedulerDao.class);
JobDataMap dataMap = context.getJobDetail().getJobDataMap();
long scheduleCfgId = dataMap.get("scheduleCfgId") == null ? 0:dataMap.getLong("scheduleCfgId");
long limit = dataMap.get("limit") == null ? 1000:dataMap.getLong("limit");
log.info(String.format("定时配置任务开始执行scheduleCfgId:%s,limit:%s",scheduleCfgId,limit ));
List<ScheduleCfg> newlyCfg = null;
int totalNum = 0;
do {
newlyCfg = dao.findNewlyCfg(scheduleCfgId, limit);
if(newlyCfg != null && newlyCfg.size() > 0) {
totalNum += newlyCfg.size();
for(ScheduleCfg cfg : newlyCfg) {//先取消之前的定时配置
Integer compileId = cfg.getCompileId();
try {
//取消之前所有的 trigger
GroupMatcher<TriggerKey> groupMatcher= GroupMatcher.triggerGroupEquals(STATUS_GROUP + compileId);
Set<TriggerKey> triggerKeys = scheduler.getTriggerKeys(groupMatcher);
if(triggerKeys != null && triggerKeys.size() > 0) {
for(TriggerKey tk : triggerKeys) {
scheduler.unscheduleJob(tk);
}
log.info(String.format("定时任务取消成功compile:%s", compileId));
}
} catch (Exception e) {
log.error(String.format("定时任务取消异常compileId:%s", compileId),e);
}
}
for(ScheduleCfg cfg : newlyCfg) {
Integer compileId = cfg.getCompileId();
try {
//判断状态,重新添加最新的 trigger
Integer isValid = cfg.getIsValid();
Integer isAudit = cfg.getIsAudit();
//添加定时任务的条件
if((isValid == 1 && isAudit == 1) || (isValid == 0 && isAudit == 0)) {
//添加定时任务包括valid 和 invalid
addJob(scheduler, cfg);
log.info(String.format("定时任务添加成功compile:%s", compileId));
}
} catch (Exception e) {
log.error(String.format("定时任务更新异常compileId:%s", compileId),e);
}
}
//最后 保存此次 最后的id
ScheduleCfg lastCfg = newlyCfg.get(newlyCfg.size() -1);
scheduleCfgId = lastCfg.getId();
dataMap.put("scheduleCfgId", scheduleCfgId);
log.info(String.format("加载定时任务total num :%s", newlyCfg.size()));
}
} while (newlyCfg != null && newlyCfg.size() > 0);
log.info(String.format("定时配置任务结束执行total num:%s",totalNum));
}
/**
* 将定时任务信息添加到 定时器框架中调度
* @param scheduler
* @param cfg
* @throws SchedulerException
*/
/*public static void addJob(Scheduler scheduler,ScheduleCfg cfg) throws SchedulerException {
Integer compileId = cfg.getCompileId();
String cronValid = cfg.getCronValid();
String cronInvalid = cfg.getCronInvalid();
Trigger validTrigger = createTrigger(cronValid, compileId, true, cfg);
Trigger invalidTrigger = createTrigger(cronInvalid, compileId, false, cfg);
boolean jobExist = scheduler.checkExists(STATUS_JOBKEY);
if(!jobExist) {//判断 job 是否存在,不存在添加
scheduler.addJob(STATUS_JOBDETAIL, false);
}
boolean checkExists = scheduler.checkExists(validTrigger.getKey());
if(!checkExists) {//判断 valid trigger 是否存在,不存在添加
scheduler.scheduleJob(validTrigger);
}else {
log.warn(String.format("Trigger already exists:%s ", validTrigger.getKey().toString()));
}
checkExists = scheduler.checkExists(invalidTrigger.getKey());
if(!checkExists) {//判断 invalid trigger 是否存在,不存在添加
scheduler.scheduleJob(invalidTrigger);
}else {
log.warn(String.format("Trigger already exists:%s ", invalidTrigger.getKey().toString()));
}
}*/
public static void addJob(Scheduler scheduler,ScheduleCfg cfg) throws SchedulerException {
List<Trigger> triList = createTrigger(cfg);
boolean jobExist = scheduler.checkExists(STATUS_JOBKEY);
if(!jobExist) {//判断 job 是否存在,不存在添加
scheduler.addJob(STATUS_JOBDETAIL, false);
}
for(Trigger tri : triList) {
boolean checkExists = scheduler.checkExists(tri.getKey());
if(!checkExists) {//判断 valid trigger 是否存在,不存在添加
log.debug(String.format("定时任务添加,%s", tri.getKey()));
scheduler.scheduleJob(tri);
log.info(String.format("定时任务添加成功,%s", tri.getKey()));
}else {
log.warn(String.format("Trigger already exists:%s ", tri.getKey().toString()));
}
}
}
/**
* 将页面配置的内容 转换成 trigger
* @param cfg
* @return
*/
public static List<Trigger> createTrigger(ScheduleCfg cfg){
String mode = cfg.getUserRegion1().toUpperCase();//定时任务运行模式:一次,每天,每周,每月
List<Trigger> triList = null;
switch (mode) {
case "SINGLE"://单次运行
triList = createSimpleTrigger(cfg);
break;
case "EVERYDAY"://每天运行 0 0 0 2/1 * ? ,不符合要求,定义每天都执行,然后在 代码判断 间隔时间
triList = createCalendarIntervalTrigger(cfg);
break;
case "EVERYWEEK"://每周运行
triList = createCalendarIntervalTrigger(cfg);
break;
case "EVERYMONTH"://每月运行
triList = createEveryMonthTrigger(cfg);
break;
default:
log.warn(String.format("unknown mode : %s ", mode));
break;
}
return triList;
}
/**
* 将时间转换成 时分秒
* @param time
* @return
*/
public static List<Integer> parseTime(String time) {
if(StringUtils.isNoneBlank(time)) {
String[] split = time.split(":");
List<Integer> tl = new ArrayList<Integer>(3);
for(String s : split) {
tl.add(Integer.valueOf(s));
}
return tl;
}
return null;
}
public static Trigger createCronTrigger(String cron,Integer compileId,boolean isValid,ScheduleCfg cfg) {
String triggerName = isValid ? (VALID_KEY + cron) : (INVALID_KEY + cron);
JobDataMap dataMap = new JobDataMap();
dataMap.put("isValid", isValid);
dataMap.put("cfg", cfg);
return TriggerBuilder.newTrigger()
.withIdentity(createTiggerKey(triggerName, STATUS_GROUP+compileId))
.withSchedule(CronScheduleBuilder.cronSchedule(cron))
.usingJobData(dataMap)
.forJob(STATUS_JOBDETAIL)
.build();
}
/**
* 一次执行
* @param cfg
* @return
*/
public static List<Trigger> createSimpleTrigger(ScheduleCfg cfg){
List<Trigger> triList = new ArrayList<Trigger>();
Integer compileId = cfg.getCompileId();
String cronValid = cfg.getCronValid();
String cronInvalid = cfg.getCronInvalid();
Date validDate = DateUtil.convertStringToDate(cronValid, Constants.COMMON_DATE_FORMAT);
Date invalidDate = DateUtil.convertStringToDate(cronInvalid, Constants.COMMON_DATE_FORMAT);
JobDataMap dataMap = new JobDataMap();
dataMap.put("isValid", true);
dataMap.put("cfg", cfg);
String triName = VALID_KEY + cfg.getUserRegion1() + "_" + cronValid;
Trigger trigger = TriggerBuilder.newTrigger()
.withIdentity(createTiggerKey(triName, STATUS_GROUP+compileId))
.withSchedule(SimpleScheduleBuilder.simpleSchedule())
.usingJobData(dataMap)
.forJob(STATUS_JOBDETAIL)
.startAt(validDate)
.build();
triList.add(trigger);
dataMap = new JobDataMap();
dataMap.put("isValid", false);
dataMap.put("cfg", cfg);
triName = INVALID_KEY + cfg.getUserRegion1() + "_" + cronInvalid;
trigger = TriggerBuilder.newTrigger()
.withIdentity(createTiggerKey(triName, STATUS_GROUP+compileId))
.withSchedule(SimpleScheduleBuilder.simpleSchedule())
.usingJobData(dataMap)
.forJob(STATUS_JOBDETAIL)
.startAt(invalidDate)
.build();
triList.add(trigger);
return triList;
}
/**
* 间隔 n 天 或 n 周执行
* @param cfg
* @return
*/
public static List<Trigger> createCalendarIntervalTrigger(ScheduleCfg cfg) {
List<Trigger> triList = new ArrayList<Trigger>();
Integer compileId = cfg.getCompileId();
String cronValid = cfg.getCronValid();
String cronInvalid = cfg.getCronInvalid();
String dayOrWeek = cfg.getUserRegion1();
Integer interval = Integer.valueOf(cfg.getUserRegion2());
List<Integer> validList = parseTime(cronValid);
List<Integer> invalidList = parseTime(cronInvalid);
Date validStartTime = DateBuilder.todayAt(validList.get(0), validList.get(1), validList.get(2));
Date invalidTime = DateBuilder.todayAt(invalidList.get(0), invalidList.get(1), invalidList.get(2));
CalendarIntervalScheduleBuilder intervalBuilder = null;
if("EVERYDAY".equalsIgnoreCase(dayOrWeek)) {
intervalBuilder = CalendarIntervalScheduleBuilder.calendarIntervalSchedule().withIntervalInDays(interval);
//valid
JobDataMap dataMap = new JobDataMap();
dataMap.put("isValid", true);
dataMap.put("cfg", cfg);
String triName = VALID_KEY + dayOrWeek+"("+interval+")" + "_" + DateUtils.formatDate(validStartTime, Constants.COMMON_DATE_FORMAT);
Trigger validTri = TriggerBuilder.newTrigger()
.withIdentity(createTiggerKey(triName, STATUS_GROUP+compileId))
.withSchedule(intervalBuilder)
.usingJobData(dataMap)
.forJob(STATUS_JOBDETAIL)
.startAt(validStartTime)
.build();
triList.add(validTri);
//invalid
dataMap = new JobDataMap();
dataMap.put("isValid", false);
dataMap.put("cfg", cfg);
triName = INVALID_KEY + dayOrWeek +"("+interval+")" + "_" + DateUtils.formatDate(invalidTime, Constants.COMMON_DATE_FORMAT);
validTri = TriggerBuilder.newTrigger()
.withIdentity(createTiggerKey(triName, STATUS_GROUP+compileId))
.withSchedule(intervalBuilder)
.usingJobData(dataMap)
.forJob(STATUS_JOBDETAIL)
.startAt(invalidTime)
.build();
triList.add(validTri);
}else if("EVERYWEEK".equalsIgnoreCase(dayOrWeek)) {
intervalBuilder = CalendarIntervalScheduleBuilder.calendarIntervalSchedule().withIntervalInWeeks(interval);
String[] weeks = cfg.getUserRegion3().split(",");
for(String week : weeks) {
if(StringUtils.isNoneBlank(week)) {
Date temp = closestAfterWeek(validStartTime, Integer.valueOf(week));
JobDataMap dataMap = new JobDataMap();
dataMap.put("isValid", true);
dataMap.put("cfg", cfg);
String triName = VALID_KEY + dayOrWeek +week+"("+interval+")" + "_" + DateUtils.formatDate(temp, Constants.COMMON_DATE_FORMAT);
Trigger validTri = TriggerBuilder.newTrigger()
.withIdentity(createTiggerKey(triName, STATUS_GROUP+compileId))
.withSchedule(intervalBuilder)
.usingJobData(dataMap)
.forJob(STATUS_JOBDETAIL)
.startAt(temp)
.build();
triList.add(validTri);
//invalid
dataMap = new JobDataMap();
dataMap.put("isValid", false);
dataMap.put("cfg", cfg);
temp = closestAfterWeek(invalidTime, Integer.valueOf(week));
triName = INVALID_KEY + dayOrWeek +week+"("+interval+")" + "_" + DateUtils.formatDate(temp, Constants.COMMON_DATE_FORMAT);
validTri = TriggerBuilder.newTrigger()
.withIdentity(createTiggerKey(triName, STATUS_GROUP+compileId))
.withSchedule(intervalBuilder)
.usingJobData(dataMap)
.forJob(STATUS_JOBDETAIL)
.startAt(temp)
.build();
triList.add(validTri);
}
}
}
return triList;
}
/**
* 每月 执行
* @param cfg
* @return
*/
public static List<Trigger> createEveryMonthTrigger(ScheduleCfg cfg){
String dayWeek = cfg.getUserRegion3();
String cronInvalid = cfg.getCronInvalid();
String cronValid = cfg.getCronValid();
StringBuilder cronSb = new StringBuilder();
Trigger trigger = null;
List<Integer> validList = parseTime(cronValid);//time 转换
List<Integer> invalidList = parseTime(cronInvalid);//time 转换
List<Trigger> triList = new ArrayList<Trigger>();
String userRegion4 = cfg.getUserRegion4().toUpperCase();
if("day".equalsIgnoreCase(dayWeek)) {//指定天
boolean hasL = userRegion4.contains("L");
StringBuilder chooseSb = new StringBuilder();
for(String str : userRegion4.split(",")) {
if(!"L".equalsIgnoreCase(str.trim())) {
chooseSb.append(",").append(str);
}
}
chooseSb.deleteCharAt(0);
cronSb.append(validList.get(2)).append(" ")//秒
.append(validList.get(1)).append(" ")//分
.append(validList.get(0)).append(" ")//小时
.append(chooseSb.toString()).append(" ")//日
.append(cfg.getUserRegion2()).append(" ")//月
.append("?").append(" ");//周
trigger = createCronTrigger(cronSb.toString(), cfg.getCompileId(), true, cfg);
triList.add(trigger);
cronSb.setLength(0);
cronSb.append(invalidList.get(2)).append(" ")//秒
.append(invalidList.get(1)).append(" ")//分
.append(invalidList.get(0)).append(" ")//小时
.append(chooseSb.toString()).append(" ")//日
.append(cfg.getUserRegion2()).append(" ")//月
.append("?").append(" ");//周
trigger = createCronTrigger(cronSb.toString(), cfg.getCompileId(), false, cfg);
triList.add(trigger);
if(hasL) {// 月的最后一天quartz 不支持 1,L 这种指定,所以 L单独处理一下
cronSb.setLength(0);
cronSb.append(validList.get(2)).append(" ")//秒
.append(validList.get(1)).append(" ")//分
.append(validList.get(0)).append(" ")//小时
.append("L").append(" ")//日
.append(cfg.getUserRegion2()).append(" ")//月
.append("?").append(" ");//周
trigger = createCronTrigger(cronSb.toString(), cfg.getCompileId(), true, cfg);
triList.add(trigger);
cronSb.setLength(0);
cronSb.append(invalidList.get(2)).append(" ")//秒
.append(invalidList.get(1)).append(" ")//分
.append(invalidList.get(0)).append(" ")//小时
.append("L").append(" ")//日
.append(cfg.getUserRegion2()).append(" ")//月
.append("?").append(" ");//周
trigger = createCronTrigger(cronSb.toString(), cfg.getCompileId(), false, cfg);
triList.add(trigger);
}
}else if ("week".equalsIgnoreCase(dayWeek)) {//指定周1#2: 第一周的周二4L:最后一周的周四
for(String nthWeek : userRegion4.split(",")) {//第几周
for(String week : cfg.getUserRegion5().split(",")) {//星期几
cronSb.setLength(0);
cronSb.append(validList.get(2)).append(" ")//秒
.append(validList.get(1)).append(" ")//分
.append(validList.get(0)).append(" ")//小时
.append("?").append(" ")//日
.append(cfg.getUserRegion2()).append(" ");//月
if("L".equalsIgnoreCase(nthWeek)) {
cronSb.append(week).append("L");//周
}else {
cronSb.append(week).append("#").append(nthWeek);//周
}
trigger = createCronTrigger(cronSb.toString(), cfg.getCompileId(), true, cfg);
triList.add(trigger);
cronSb.setLength(0);
cronSb.append(invalidList.get(2)).append(" ")//秒
.append(invalidList.get(1)).append(" ")//分
.append(invalidList.get(0)).append(" ")//小时
.append("?").append(" ")//日
.append(cfg.getUserRegion2()).append(" ");//月
if("L".equalsIgnoreCase(nthWeek)) {
cronSb.append(week).append("L");//周
}else {
cronSb.append(week).append("#").append(nthWeek);//周
}
trigger = createCronTrigger(cronSb.toString(), cfg.getCompileId(), false, cfg);
triList.add(trigger);
}
}
}
return triList;
}
/**
* 查找最近的 星期几 ,包括今天
* @param date
* @param w 周一开始 1 -7
* @return
*/
public static Date closestAfterWeek(Date date,int w) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int i = cal.get(Calendar.DAY_OF_WEEK);//周日开始 1-7
i = (i==1)? 7: i-1;//转换为 周一到 周日 1-7
cal.add(Calendar.DAY_OF_MONTH, (i>w)?(7-(i-w)) : (w-i));
return cal.getTime();
}
public static TriggerKey createTiggerKey(String name,String group) {
TriggerKey key = new TriggerKey(name, group);
return key;
}
/**
* jquery cron 生成的cron 表达式quartz 不能直接使用,需要做些修改
* @param cron
* @return
*/
public static String modifyCronExp(String cron) {
String[] cronArr = cron.split("\\s");
if("*".equals(cronArr[4])) {
cronArr[4] = "?";
}else {
cronArr[3] = "*";
cronArr[2] = "?";
}
return "0 " + StringUtils.join(cronArr, " ");
}
public static void main(String[] args) {
CronTriggerImpl cron = new CronTriggerImpl();
try {
String exp = "0 0 0 ? 1,2 1#4";
cron.setCronExpression(exp);
System.out.println(cron);
} catch (ParseException e) {
e.printStackTrace();
}
}
}

View File

@@ -0,0 +1,38 @@
package com.nis.quartz;
import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import com.nis.domain.ScheduleCfg;
import com.nis.web.service.ScheduleService;
import com.nis.web.service.SpringContextHolder;
/**
* 定时任务 真正执行类
* 配置状态下发
* 从trigger 的 jobDataMap 中取出 相关数据compile,isValid
* @author fang
*
*/
public class ScheduleStatusJob implements Job{
private static final Logger log = Logger.getLogger(ScheduleStatusJob.class);
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
//从trigger中 获取 配置信息
JobDataMap jobDataMap = context.getTrigger().getJobDataMap();
boolean isValid = jobDataMap.getBoolean("isValid");
ScheduleCfg cfg = (ScheduleCfg)jobDataMap.get("cfg");
Integer compileId = cfg.getCompileId();
log.debug(String.format("任务开始执行compileId:%s,isValid:%s",compileId,isValid ));
//配置下发,并修改 配置表的状态,保存下发记录等
ScheduleService scheduleService = SpringContextHolder.getBean(ScheduleService.class);
scheduleService.issueCompileInfo(cfg, isValid?1:0);
log.debug(String.format("任务开始执行compileId:%s,isValid:%s",compileId,isValid ));
}
}

View File

@@ -0,0 +1,690 @@
package com.nis.util;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringEscapeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import com.google.common.collect.Lists;
import com.googlecode.ipv6.IPv6Address;
import com.googlecode.ipv6.IPv6Network;
import com.nis.domain.basics.AsnIpCfg;
import com.nis.domain.configuration.AppIpCfg;
import com.nis.domain.configuration.BaseCfg;
import com.nis.domain.configuration.BaseIpCfg;
import com.nis.domain.configuration.BaseStringCfg;
import com.nis.domain.configuration.ComplexkeywordCfg;
import com.nis.domain.configuration.FileDigestCfg;
import com.nis.domain.configuration.IpPortCfg;
import com.nis.domain.maat.MaatCfg.DigestCfg;
import com.nis.domain.maat.MaatCfg.GroupCfg;
import com.nis.domain.maat.MaatCfg.IpCfg;
import com.nis.domain.maat.MaatCfg.NumBoundaryCfg;
import com.nis.domain.maat.MaatCfg.StringCfg;
public class ConfigConvertUtil {
private static Logger logger = LoggerFactory.getLogger(ConfigConvertUtil.class);
/**
* 配置域转换
* @param ipList
* @param strList
* @param complexStrList
* @param numList
* @param fileList
* @param regionIds
* @param groupIds
* @param entity
* @param compileId
* @param auditTime
* @param groupRelationList
* @param ipRegionList
* @param strRegionList
* @param numRegionList
* @param digestRegionList
* @param areaIpRegionList
* @param userRegion
*/
public static String configCovert(List<IpPortCfg> ipList,List<BaseStringCfg> strList,List<ComplexkeywordCfg> complexStrList,
List<com.nis.domain.configuration.NumBoundaryCfg > numList,
List<FileDigestCfg> fileList,List<Integer> regionIds,List<Integer> groupIds,BaseCfg entity,
Integer compileId,Date auditTime,List<GroupCfg> groupRelationList,
List<IpCfg> ipRegionList,
List<StringCfg> strRegionList,
List<NumBoundaryCfg> numRegionList,
List<DigestCfg> digestRegionList,
List<IpCfg> areaIpRegionList,String userRegion){
List list1 = new ArrayList();
List<BaseStringCfg> list2 = new ArrayList();
List<ComplexkeywordCfg> list3 = new ArrayList();
List<com.nis.domain.configuration.NumBoundaryCfg> list4 = new ArrayList();
List<FileDigestCfg> list5 = new ArrayList();
if(ipList.size()>0){
for(int index=0;index<ipList.size();index++){
IpPortCfg ip = ipList.get(index);
if(ip.getCompileId().equals(compileId)){
ip.setRegionId(regionIds.get(0));
regionIds.remove(0);
ip.setGroupId(groupIds.get(0));
groupIds.remove(0);
ip.setIsValid(entity.getIsValid());
ip.setAuditTime(auditTime);
list1.add(ip);
}
}
}
for(int index=0;index<strList.size();index++){
BaseStringCfg str = strList.get(index);
if(str.getCompileId().equals(compileId)){
str.setRegionId(regionIds.get(0));
regionIds.remove(0);
str.setGroupId(groupIds.get(0));
groupIds.remove(0);
str.setIsValid(entity.getIsValid());
str.setAuditTime(auditTime);
list2.add(str);
if(entity.getServiceId().equals(513)||entity.getServiceId().equals(515)){
if(userRegion.equals("")){
userRegion += Constants.USERREGION_DOMAIN_STR+"="+str.getCfgKeywords();
}else{
userRegion += Constants.USER_REGION_SPLIT+Constants.USERREGION_DOMAIN_STR+"="+str.getCfgKeywords();
}
}
}
}
for(int index=0;index<complexStrList.size();index++){
ComplexkeywordCfg str = complexStrList.get(index);
if(str.getCompileId().equals(compileId)){
str.setRegionId(regionIds.get(0));
regionIds.remove(0);
str.setGroupId(groupIds.get(0));
groupIds.remove(0);
str.setIsValid(entity.getIsValid());
str.setAuditTime(auditTime);
list3.add(str);
if(entity.getServiceId().equals(129) && str.getDistrict()!=null){//http监测
String dictValue = DictUtils.getDictCode(Constants.HTTP_HEADER_DICT_MODULE, str.getDistrict());
if(StringUtil.isEmpty(dictValue) || dictValue.equals("默认")){
if(userRegion.equals("")){
userRegion += Constants.HTTP_HEADER_USER_REGION_KEY+"="+str.getDistrict();
}else{
userRegion += Constants.USER_REGION_SPLIT+Constants.HTTP_HEADER_USER_REGION_KEY+"="+str.getDistrict();
}
}
}
}
}
for(int index=0;index<numList.size();index++){
com.nis.domain.configuration.NumBoundaryCfg num = numList.get(index);
if(num.getCompileId().equals(compileId)){
num.setRegionId(regionIds.get(0));
regionIds.remove(0);
num.setGroupId(groupIds.get(0));
groupIds.remove(0);
num.setIsValid(entity.getIsValid());
num.setAuditTime(auditTime);
list4.add(num);
}
}
for(int index=0;index<fileList.size();index++){
FileDigestCfg file = fileList.get(index);
if(file.getCompileId().equals(compileId)){
file.setRegionId(regionIds.get(0));
regionIds.remove(0);
file.setGroupId(groupIds.get(0));
groupIds.remove(0);
file.setIsValid(entity.getIsValid());
file.setAuditTime(auditTime);
list5.add(file);
}
}
if(list1.size()>0){
ipList.removeAll(list1);
Map<String,List> map = cfgToMaatConvert(ipRegionList,list1,1,groupRelationList);
groupRelationList=map.get("groupList");
ipRegionList=map.get("dstList");
if(map.get("numRegionList")!=null){
numRegionList.addAll(map.get("numRegionList"));
}
}
if(list2.size()>0){
strList.removeAll(list2);
Map<String,List> map = cfgToMaatConvert(strRegionList,list2,2,groupRelationList);
groupRelationList=map.get("groupList");
strRegionList=map.get("dstList");
}
if(list3.size()>0){
complexStrList.removeAll(list3);
Map<String,List> map = cfgToMaatConvert(strRegionList,list3,3,groupRelationList);
groupRelationList=map.get("groupList");
strRegionList=map.get("dstList");
}
if(list4.size()>0){
numList.removeAll(list4);
Map<String,List> map = cfgToMaatConvert(numRegionList,list4,4,groupRelationList);
groupRelationList=map.get("groupList");
numRegionList=map.get("dstList");
}
if(list5.size()>0){
fileList.removeAll(list5);
Map<String,List> map = cfgToMaatConvert(digestRegionList,list5,5,groupRelationList);
groupRelationList=map.get("groupList");
digestRegionList=map.get("dstList");
}
return userRegion;
}
// asn IP 复用转换
public static List<IpCfg> groupReuseCfgAddRemoveConvert(List<? extends BaseCfg<?>> ipCfgList, Integer isValid,
Integer groupId) {
logger.warn("convert data start");
long start = System.currentTimeMillis();
Date opTime = new Date();
List<IpCfg> maatIpList = new ArrayList<>();
if (ipCfgList.size() > 0) {
// 只用一次instanceof,取代循环中每次都用一次instanceof
if (ipCfgList.get(0) instanceof AsnIpCfg) {
for (BaseCfg<?> _cfg : ipCfgList) {
IpCfg cfg = new IpCfg();
BaseIpCfg baseIpCfg = new BaseIpCfg();
AsnIpCfg asnIpCfg = (AsnIpCfg) _cfg;
BeanUtils.copyProperties(asnIpCfg, baseIpCfg);
BeanUtils.copyProperties(baseIpCfg, cfg);
cfg.setGroupId(asnIpCfg.getAsnIpGroup());
cfg.setRegionId(asnIpCfg.getRegionId());
String userRegion = "ASN_ID=" + asnIpCfg.getUserRegion1();
cfg.setUserRegion(userRegion);
cfg.setIsValid(isValid);
cfg.setAuditTime(opTime);
List<IpCfg> cfgs = ipConvert(cfg, baseIpCfg);
maatIpList.addAll(cfgs);
}
} else if (ipCfgList.get(0) instanceof AppIpCfg) {
for (BaseCfg<?> _cfg : ipCfgList) {
IpCfg cfg = new IpCfg();
BaseIpCfg baseIpCfg = new BaseIpCfg();
AppIpCfg appIpCfg = (AppIpCfg) _cfg;
BeanUtils.copyProperties(appIpCfg, baseIpCfg);
BeanUtils.copyProperties(baseIpCfg, cfg);
cfg.setGroupId(groupId);
cfg.setRegionId(Integer.parseInt(appIpCfg.getUserRegion1()));
String userRegion = "APP_ID=" + appIpCfg.getAppCode();
cfg.setUserRegion(userRegion);
cfg.setIsValid(isValid);
cfg.setAuditTime(opTime);
List<IpCfg> cfgs = ipConvert(cfg, baseIpCfg);
maatIpList.addAll(cfgs);
}
}
}
long end = System.currentTimeMillis();
logger.warn("convert data finish,cost:" + (end - start));
return maatIpList;
}
/**
* 界面配置list转换为服务接口端的list用于批量下发时regionId,groupId已在该方法前被批量获取
*
* @param <T>
* @param <T>
* @param dstList
* @param srcList
* @param cfgType1为IP类型2为字符串类型3为增强字符串4数值类型5摘要类,6回调类[但字符串类域配置和增强字符串域配置在接口参数中同属于strRegionList]
* @param baseCfg配置基本信息
* @param groupRelationList
* 配置分组列表
* @return
*/
public static <T> Map<String, List> cfgToMaatConvert(List dstList, List<T> srcList, Integer cfgType,List groupRelationList) {
Map<String, List> map = new HashMap();
if (cfgType == 1) {
List numRegionList = new ArrayList();
Integer groupId = 0;
Integer numGroupId = 0;
for (int i = 0; i < srcList.size(); i++) {
List<Integer> regionIdList = Lists.newArrayList();
T srcCfg = srcList.get(i);
BaseIpCfg baseIpCfg = new BaseIpCfg();
BeanUtils.copyProperties(srcCfg, baseIpCfg);
regionIdList.add(baseIpCfg.getRegionId());
IpCfg cfg = new IpCfg();
BeanUtils.copyProperties(baseIpCfg, cfg);
//多条IP配置属于同一个分组
if (groupId == 0) {
GroupCfg group = new GroupCfg();
groupId = baseIpCfg.getGroupId();
group.setGroupId(groupId);
group.setCompileId(baseIpCfg.getCompileId());
group.setAuditTime(baseIpCfg.getAuditTime());
group.setIsValid(baseIpCfg.getIsValid());
groupRelationList.add(group);
}
cfg.setGroupId(groupId);
cfg.setAuditTime(baseIpCfg.getAuditTime());
cfg.setIsValid(baseIpCfg.getIsValid());
List<IpCfg> cfgs = ipConvert(cfg, baseIpCfg);
if (cfgs.size() > 1) {
List<Integer> ids = ConfigServiceUtil.getId(3, cfgs.size() - 1);
regionIdList.addAll(ids);
}
for (int j = i; j < cfgs.size() + i; j++) {
cfgs.get(j - i).setRegionId(regionIdList.get(j));
}
dstList.addAll(cfgs);
// 如果protocolId非空非零需要构造数值型域配置多条相同协议的IP只需要一条数值域配置目前没有不同协议IP&情况)
if (baseIpCfg.getProtocolId() != null && baseIpCfg.getProtocolId() != 0) {
if (numGroupId == 0) {
GroupCfg group1 = new GroupCfg();
group1.setGroupId(ConfigServiceUtil.getId(2, 1).get(0));
group1.setCompileId(baseIpCfg.getCompileId());
group1.setAuditTime(baseIpCfg.getAuditTime());
group1.setIsValid(baseIpCfg.getIsValid());
groupRelationList.add(group1);
NumBoundaryCfg numCfg = new NumBoundaryCfg();
numCfg.initDefaultValue();
numCfg.setLowBoundary(baseIpCfg.getProtocolId());
numCfg.setUpBoundary(baseIpCfg.getProtocolId());
numCfg.setRegionId(ConfigServiceUtil.getId(3, 1).get(0));
numCfg.setAuditTime(baseIpCfg.getAuditTime());
numCfg.setGroupId(group1.getGroupId());
numCfg.setIsValid(baseIpCfg.getIsValid());
numRegionList.add(numCfg);
map.put("numRegionList", numRegionList);
numGroupId++;
}
}
}
} else if (cfgType == 2 || cfgType == 3) {
for (int i = 0; i < srcList.size(); i++) {
// 一条业务配置创建一个分组
BaseCfg baseCfg = new BaseCfg();
BeanUtils.copyProperties(srcList.get(i), baseCfg,new String[]{"menuNameCode"});//拷贝公共属性
GroupCfg group = new GroupCfg();
StringCfg cfg = new StringCfg();
BeanUtils.copyProperties(srcList.get(i), cfg,new String[]{"menuNameCode"});//拷贝公共属性以及私有属性
group.setGroupId(baseCfg.getGroupId());
group.setCompileId(baseCfg.getCompileId());
group.setAuditTime(baseCfg.getAuditTime());
group.setIsValid(baseCfg.getIsValid());
groupRelationList.add(group);
cfg.setGroupId(group.getGroupId());
cfg.setRegionId(baseCfg.getRegionId());
cfg.setAuditTime(baseCfg.getAuditTime());
cfg.setIsValid(baseCfg.getIsValid());
// 处理配置关键字转译
cfg.setCfgKeywords(keywordsEscape(cfg.getCfgKeywords()));
// 增强字符串转换
cfg.setDistrict(keywordsEscape(cfg.getDistrict()));
dstList.add(cfg);
}
} else if (cfgType == 4) {
for (int i = 0; i < srcList.size(); i++) {
BaseCfg baseCfg = new BaseCfg();
BeanUtils.copyProperties(srcList.get(i), baseCfg);//拷贝公共属性
// 一条业务配置创建一个分组
com.nis.domain.maat.MaatCfg.NumBoundaryCfg cfg = new com.nis.domain.maat.MaatCfg.NumBoundaryCfg();
BeanUtils.copyProperties(srcList.get(i), cfg);
GroupCfg group = new GroupCfg();
group.setGroupId(baseCfg.getGroupId());
group.setCompileId(baseCfg.getCompileId());
group.setAuditTime(baseCfg.getAuditTime());
group.setIsValid(baseCfg.getIsValid());
groupRelationList.add(group);
cfg.setGroupId(group.getGroupId());
cfg.setRegionId(baseCfg.getRegionId());
cfg.setAuditTime(baseCfg.getAuditTime());
cfg.setIsValid(baseCfg.getIsValid());
dstList.add(cfg);
}
} else if (cfgType == 5) {
for (int i = 0; i < srcList.size(); i++) {
BaseCfg baseCfg = new BaseCfg();
BeanUtils.copyProperties(srcList.get(i), baseCfg);//拷贝公共属性
// 一条业务配置创建一个分组
com.nis.domain.maat.MaatCfg.DigestCfg cfg = new com.nis.domain.maat.MaatCfg.DigestCfg();
BeanUtils.copyProperties(srcList.get(i), cfg);
GroupCfg group = new GroupCfg();
group.setGroupId(baseCfg.getGroupId());
group.setCompileId(baseCfg.getCompileId());
group.setAuditTime(baseCfg.getAuditTime());
group.setIsValid(baseCfg.getIsValid());
groupRelationList.add(group);
cfg.setGroupId(group.getGroupId());
cfg.setRegionId(baseCfg.getRegionId());
cfg.setAuditTime(baseCfg.getAuditTime());
cfg.setIsValid(baseCfg.getIsValid());
dstList.add(cfg);
}
} else {
dstList.addAll(srcList);
}
map.put("groupList", groupRelationList);
map.put("dstList", dstList);
return map;
}
/**
* 关键字特殊字符转义处理
* @param cfgKeywords
* @return
*/
public static String keywordsEscape(String cfgKeywords) {
if (StringUtils.isNotEmpty(cfgKeywords)) {
// 不转译特殊字符
cfgKeywords = cfgKeywords.trim();// 首先去掉首尾空格
cfgKeywords = StringEscapeUtils.unescapeHtml4(cfgKeywords);
cfgKeywords = cfgKeywords.replace("\\", "\\\\");
cfgKeywords = cfgKeywords.replace("&", "\\&");
cfgKeywords = cfgKeywords.replace(" ", "\\b");
// ***and***在界面表示多个关键字的与表达式此特殊字符串在common.js中使用定义maat端以&表示
cfgKeywords = cfgKeywords.replace(Constants.KEYWORD_EXPR, "&");
}
return cfgKeywords;
}
/**
* 界面IP配置转换为MAAT类或者回调类IP配置
*
* @param dstIp
* @param srcIp
* @return
*/
public static List<IpCfg> ipConvert(IpCfg dstIp, BaseIpCfg srcIp) {
List<IpCfg> ipConvertList = Lists.newArrayList();
boolean isRange = ((srcIp.getIpPattern() != null && srcIp.getIpPattern() == 2)
|| (srcIp.getSrcIpAddress() != null && srcIp.getSrcIpAddress().indexOf("-") > -1)
|| (srcIp.getDestIpAddress() != null && srcIp.getDestIpAddress().indexOf("-") > -1));
if (isRange) {
List<IpCfg> tempList = Lists.newArrayList();
List<IpCfg> tempList1 = Lists.newArrayList();
if (srcIp.getIpType().intValue() == 4) {
if (srcIp.getSrcIpAddress() != null) {
String startIpPart = srcIp.getSrcIpAddress().split("-")[0];
String endIpPart = srcIp.getSrcIpAddress().split("-")[1];
Integer startNum = Integer.parseInt(startIpPart.split("\\.")[3]);
Integer endNum = Integer.parseInt(endIpPart.split("\\.")[3]);
for (int i = startNum; i <= endNum; i++) {
IpCfg tempIp = new IpCfg();
BeanUtils.copyProperties(dstIp, tempIp);
tempIp.setSrcIp(startIpPart.substring(0, startIpPart.lastIndexOf(".") + 1) + i);
tempIp.setSrcIpMask("255.255.255.255");
tempList.add(tempIp);
}
} else {
dstIp.setSrcIp("0.0.0.0");
dstIp.setSrcIpMask("255.255.255.255");
tempList.add(dstIp);
}
if (srcIp.getDestIpAddress() != null) {
String startIpPart = srcIp.getDestIpAddress().split("-")[0];
String endIpPart = srcIp.getDestIpAddress().split("-")[1];
Integer startNum = Integer.parseInt(startIpPart.split("\\.")[3]);
Integer endNum = Integer.parseInt(endIpPart.split("\\.")[3]);
for (IpCfg _cfg : tempList) {
for (int i = startNum; i <= endNum; i++) {
IpCfg tempIp = new IpCfg();
BeanUtils.copyProperties(_cfg, tempIp);
tempIp.setDstIp(startIpPart.substring(0, startIpPart.lastIndexOf(".") + 1) + i);
tempIp.setDstIpMask("255.255.255.255");
// 处理
convertPortValues(tempIp, srcIp);
if (!tempIp.getSrcIp().equals(tempIp.getDstIp())) {
tempList1.add(tempIp);
}
}
}
tempList.clear();
} else {
for (IpCfg _cfg : tempList) {
_cfg.setDstIp("0.0.0.0");
_cfg.setSrcIpMask("255.255.255.255");
convertPortValues(_cfg, srcIp);
}
}
if (tempList1.size() > 0) {
ipConvertList.addAll(tempList1);
} else {
ipConvertList.addAll(tempList);
}
} else if (srcIp.getIpType().intValue() == 6) {
if (srcIp.getSrcIpAddress() != null) {
IPv6Address address1 = IPv6Address.fromString(srcIp.getSrcIpAddress().split("-")[0]);
IPv6Address address2 = IPv6Address.fromString(srcIp.getSrcIpAddress().split("-")[1]);
IPv6Network network = IPv6Network.fromTwoAddresses(address1, address2);
dstIp.setSrcIp(address1.toString());
dstIp.setSrcIpMask(network.getNetmask().asAddress().toString());
} else {
dstIp.setSrcIp("::");
dstIp.setSrcIpMask("FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF");
}
if (srcIp.getDestIpAddress() != null) {
IPv6Address address1 = IPv6Address.fromString(srcIp.getDestIpAddress().split("-")[0]);
IPv6Address address2 = IPv6Address.fromString(srcIp.getDestIpAddress().split("-")[1]);
IPv6Network network = IPv6Network.fromTwoAddresses(address1, address2);
dstIp.setDstIp(address1.toString());
dstIp.setDstIpMask(network.getNetmask().asAddress().toString());
} else {
dstIp.setDstIp("::");
dstIp.setDstIpMask("FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF");
}
ipConvertList.add(dstIp);
} else {
throw new RuntimeException("Unsupported IP type " + srcIp.getIpType());
}
} else {
if (srcIp.getSrcIpAddress() != null) {
if (srcIp.getSrcIpAddress().indexOf("/") != -1) {
if (srcIp.getIpType() == 4 /* || srcIp.getIpType()==46 */) {// 46表示源ip为ipv4目的ip为ipv6
Integer srcMaskNum = Integer.parseInt(srcIp.getSrcIpAddress().split("/")[1]);
if (srcMaskNum == 0) {
dstIp.setSrcIpMask("0.0.0.0");
} else {
dstIp.setSrcIpMask(IpUtil.convertMask(srcMaskNum));
}
dstIp.setSrcIp(srcIp.getSrcIpAddress().split("/")[0]);
} else if (srcIp.getIpType() == 6/* || srcIp.getIpType()==64 */) {// 64表示源ip为ipv6目的ip为ipv4
IPv6Network strangeNetwork = IPv6Network.fromString(srcIp.getSrcIpAddress());
dstIp.setSrcIp(srcIp.getSrcIpAddress().split("/")[0]);
dstIp.setSrcIpMask(strangeNetwork.getNetmask().asAddress().toString());
} /*
* else { Pattern
* patternV4Subnet=Pattern.compile(Constants.IPV4_IP_SUBNET_REGEXP); Pattern
* patternV6Subnet=Pattern.compile(Constants.IPV6_IP_SUBNET_REGEXP); Matcher
* matchernV4Subnet=patternV4Subnet.matcher(srcIp.getSrcIpAddress()); Matcher
* matcherV6Subnet=patternV6Subnet.matcher(srcIp.getSrcIpAddress());
* if(matchernV4Subnet.matches()) { Integer srcMaskNum =
* Integer.parseInt(srcIp.getSrcIpAddress().split("/")[1]); if(srcMaskNum==0){
* dstIp.setSrcIpMask("0.0.0.0"); }else{
* dstIp.setSrcIpMask(IpUtil.convertMask(srcMaskNum)); }
* dstIp.setSrcIp(srcIp.getSrcIpAddress().split("/")[0]); }else
* if(matcherV6Subnet.matches()){ IPv6Network strangeNetwork =
* IPv6Network.fromString(srcIp.getSrcIpAddress());
* dstIp.setSrcIp(srcIp.getSrcIpAddress().split("/")[0]);
* dstIp.setSrcIpMask(strangeNetwork.getNetmask().asAddress().toString()); }else
* { throw new RuntimeException("Invalid IP/subnet mask format"); } }
*/
else {
throw new RuntimeException("Unsupported IP type " + srcIp.getIpType());
}
} else {
if (srcIp.getIpType() == 4/* || srcIp.getIpType()==46 */) {// 46表示源ip为ipv4目的ip为ipv6
dstIp.setSrcIp(srcIp.getSrcIpAddress());
dstIp.setSrcIpMask("255.255.255.255");
} else if (srcIp.getIpType() == 6/* || srcIp.getIpType()==64 */) {// 64表示源ip为ipv6目的ip为ipv4
dstIp.setSrcIp(srcIp.getSrcIpAddress());
dstIp.setSrcIpMask("FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF");
} /*
* else {//all Pattern patternV4=Pattern.compile(Constants.IPV4_IP_REGEXP);
* Pattern patternV6=Pattern.compile(Constants.IPV6_IP_REGEXP); Matcher
* matcherV4=patternV4.matcher(srcIp.getSrcIpAddress()); Matcher
* matcherV6=patternV6.matcher(srcIp.getSrcIpAddress()); if(matcherV4.matches())
* { dstIp.setSrcIp(srcIp.getSrcIpAddress());
* dstIp.setSrcIpMask("255.255.255.255"); }else if(matcherV6.matches()) {
* dstIp.setSrcIp(srcIp.getSrcIpAddress());
* dstIp.setSrcIpMask("FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF"); }else { throw
* new RuntimeException("Invalid IP format"); } }
*/
else {
throw new RuntimeException("Unsupported IP type " + srcIp.getIpType());
}
}
} else {
if (srcIp.getIpType() == 4/* || srcIp.getIpType()==46 */) {// 46表示源ip为ipv4目的ip为ipv6
dstIp.setSrcIp(srcIp.getSrcIpAddress());
dstIp.setSrcIpMask("255.255.255.255");
} else if (srcIp.getIpType() == 6/* || srcIp.getIpType()==64 */) {// 64表示源ip为ipv6目的ip为ipv4
dstIp.setSrcIp(srcIp.getSrcIpAddress());
dstIp.setSrcIpMask("FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF");
} /*
* else {//all dstIp.setSrcIp(srcIp.getSrcIpAddress());
* dstIp.setSrcIpMask("255.255.255.255"); }
*/
else {
throw new RuntimeException("Unsupported IP type " + srcIp.getIpType());
}
}
if (srcIp.getDestIpAddress() != null) {
if (srcIp.getDestIpAddress().indexOf("/") != -1) {
if (srcIp.getIpType() == 4/* || srcIp.getIpType()==64 */) {// 64表示源ip为ipv6目的ip为ipv4
Integer dstMaskNum = Integer.parseInt(srcIp.getDestIpAddress().split("/")[1]);
if (dstMaskNum == 0) {
dstIp.setDstIpMask("0.0.0.0");
} else {
dstIp.setDstIpMask(IpUtil.convertMask(dstMaskNum));
;
}
dstIp.setDstIp(srcIp.getDestIpAddress().split("/")[0]);
} else if (srcIp.getIpType() == 6/* || srcIp.getIpType()==46 */) {// 46表示源ip为ipv4目的ip为ipv6
IPv6Network strangeNetwork = IPv6Network.fromString(srcIp.getDestIpAddress());
dstIp.setDstIp(srcIp.getDestIpAddress().split("/")[0]);
dstIp.setDstIpMask(strangeNetwork.getNetmask().asAddress().toString());
} /*
* else { Pattern
* patternV4Subnet=Pattern.compile(Constants.IPV4_IP_SUBNET_REGEXP); Pattern
* patternV6Subnet=Pattern.compile(Constants.IPV6_IP_SUBNET_REGEXP); Matcher
* matchernV4Subnet=patternV4Subnet.matcher(srcIp.getDestIpAddress()); Matcher
* matcherV6Subnet=patternV6Subnet.matcher(srcIp.getDestIpAddress());
* if(matchernV4Subnet.matches()) { Integer dstMaskNum =
* Integer.parseInt(srcIp.getDestIpAddress().split("/")[1]); if(dstMaskNum==0){
* dstIp.setDstIpMask("0.0.0.0"); }else{
* dstIp.setDstIpMask(IpUtil.convertMask(dstMaskNum));; }
* dstIp.setDstIp(srcIp.getDestIpAddress().split("/")[0]); }else
* if(matcherV6Subnet.matches()){ IPv6Network strangeNetwork =
* IPv6Network.fromString(srcIp.getDestIpAddress());
* dstIp.setDstIp(srcIp.getDestIpAddress().split("/")[0]);
* dstIp.setDstIpMask(strangeNetwork.getNetmask().asAddress().toString()); }else
* { throw new RuntimeException("Invalid IP/subnet mask format"); } }
*/
else {
throw new RuntimeException("Unsupported IP type " + srcIp.getIpType());
}
} else {
if (srcIp.getIpType() == 4/* || srcIp.getIpType()==64 */) {// 64表示源ip为ipv6目的ip为ipv4
dstIp.setDstIp(srcIp.getDestIpAddress());
dstIp.setDstIpMask("255.255.255.255");
} else if (srcIp.getIpType() == 6/* || srcIp.getIpType()==46 */) {// 46表示源ip为ipv4目的ip为ipv6
dstIp.setDstIp(srcIp.getDestIpAddress());
dstIp.setDstIpMask("FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF");
} /*
* else {//all Pattern patternV4=Pattern.compile(Constants.IPV4_IP_REGEXP);
* Pattern patternV6=Pattern.compile(Constants.IPV6_IP_REGEXP); Matcher
* matcherV4=patternV4.matcher(srcIp.getDestIpAddress()); Matcher
* matcherV6=patternV6.matcher(srcIp.getDestIpAddress());
* if(matcherV4.matches()) { dstIp.setDstIp(srcIp.getDestIpAddress());
* dstIp.setDstIpMask("255.255.255.255"); }else if(matcherV6.matches()) {
* dstIp.setDstIp(srcIp.getDestIpAddress());
* dstIp.setDstIpMask("FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF"); }else { throw
* new RuntimeException("invalid ip format"); } }
*/
else {
throw new RuntimeException("Unsupported IP type " + srcIp.getIpType());
}
}
} else {
if (srcIp.getIpType() == 4/* || srcIp.getIpType()==64 */) {// 64表示源ip为ipv6目的ip为ipv4
dstIp.setDstIp(srcIp.getDestIpAddress());
dstIp.setDstIpMask("255.255.255.255");
} else if (srcIp.getIpType() == 6/* || srcIp.getIpType()==46 */) {// 46表示源ip为ipv4目的ip为ipv6
dstIp.setDstIp(srcIp.getDestIpAddress());
dstIp.setDstIpMask("FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF");
} /*
* else {//all dstIp.setDstIp(srcIp.getDestIpAddress());
* dstIp.setDstIpMask("255.255.255.255"); }
*/
else {
throw new RuntimeException("Unsupported IP type " + srcIp.getIpType());
}
}
if (srcIp.getSrcPort() != null) {
if (srcIp.getSrcPort().indexOf("/") != -1) {
String srcMaskNum = srcIp.getSrcPort().split("/")[1];
dstIp.setSrcPortMask(srcMaskNum);
dstIp.setSrcPort(srcIp.getSrcPort().split("/")[0]);
} else {
dstIp.setSrcPort(srcIp.getSrcPort());
dstIp.setSrcPortMask("65535");
}
} else {
dstIp.setSrcPort("0");
dstIp.setSrcPortMask("65535");
}
if (srcIp.getDestPort() != null) {
if (srcIp.getDestPort().indexOf("/") != -1) {
String dstMaskNum = srcIp.getDestPort().split("/")[1];
dstIp.setDstPortMask(dstMaskNum);
dstIp.setDstPort(srcIp.getDestPort().split("/")[0]);
} else {
dstIp.setDstPort(srcIp.getDestPort());
dstIp.setDstPortMask("65535");
}
} else {
dstIp.setDstPort("0");
dstIp.setDstPortMask("65535");
}
ipConvertList.add(dstIp);
}
return ipConvertList;
}
/**
* 设置端口值
*
* @param dstIp
* @param srcIp
*/
public static void convertPortValues(IpCfg dstIp, BaseIpCfg srcIp) {
if (srcIp.getSrcPort() != null) {
if (srcIp.getSrcPort().indexOf("/") != -1) {
String srcMaskNum = srcIp.getSrcPort().split("/")[1];
dstIp.setSrcPortMask(srcMaskNum);
dstIp.setSrcPort(srcIp.getSrcPort().split("/")[0]);
} else {
dstIp.setSrcPort(srcIp.getSrcPort());
dstIp.setSrcPortMask("65535");
}
} else {
dstIp.setSrcPort("0");
dstIp.setSrcPortMask("65535");
}
if (srcIp.getDestPort() != null) {
if (srcIp.getDestPort().indexOf("/") != -1) {
String dstMaskNum = srcIp.getDestPort().split("/")[1];
dstIp.setDstPortMask(dstMaskNum);
dstIp.setDstPort(srcIp.getDestPort().split("/")[0]);
} else {
dstIp.setDstPort(srcIp.getDestPort());
dstIp.setDstPortMask("65535");
}
} else {
dstIp.setDstPort("0");
dstIp.setDstPortMask("65535");
}
}
}

View File

@@ -814,4 +814,12 @@ public final class Constants {
* 流量日志的HTTP泛收接口URL
*/
public static final String NTC_HTTP_RECORD_LOG = Configurations.getStringProperty("ntcHttpRecordLog","");
/**
* 日期格式化
*/
public static final String COMMON_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
/**
* 时间格式化
*/
public static final String COMMON_TIME_FORMAT = "HH:mm:ss";
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,46 +1,66 @@
package com.nis.util;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.collections.map.CaseInsensitiveMap;
import org.apache.log4j.Logger;
import org.dom4j.Attribute;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import com.beust.jcommander.internal.Sets;
import com.nis.domain.FunctionServiceDict;
import jersey.repackaged.com.google.common.collect.Lists;
@SuppressWarnings("all")
public class ServiceConfigTemplateUtil {
private Logger logger = Logger.getLogger(getClass());
private static final Logger logger = Logger.getLogger(ServiceConfigTemplateUtil.class);
private Node root;
private static Node root;
static {
if(root == null) {//2018年12月28日11:37:50 fang 改为只加载一次,且方法改为 static
SAXReader reader = new SAXReader();
org.dom4j.Document document = null;
String configPath = "/service/service_config.xml";
InputStream is = null;
try {
is = ServiceConfigTemplateUtil.class.getResourceAsStream(configPath);
document = reader.read(is);
root = document.getRootElement();
} catch (Exception e) {
logger.error(e.getMessage());
e.printStackTrace();
} finally {
if(is != null ){
try {
is.close();
} catch (IOException e) { }
}
}
}
}
/**
* 配置文件内容
* @return
*/
public ServiceConfigTemplateUtil(){
SAXReader reader = new SAXReader();
org.dom4j.Document document = null;
String configPath = "/service/service_config.xml";
try {
document = reader.read(ServiceConfigTemplateUtil.class.getResourceAsStream(configPath));
root = document.getRootElement();
} catch (Exception e) {
logger.error(e.getMessage());
e.printStackTrace();
}
}
/**
* 获取业务节点列表
* @return
*/
public List<Node> getServiceNodeList(){
public static List<Node> getServiceNodeList(){
List<Node> nodes = root.selectNodes("service");
return nodes;
}
@@ -48,7 +68,7 @@ public class ServiceConfigTemplateUtil {
* 获取业务列表
* @return
*/
public List<Map<String,Object>> getServiceList(){
public static List<Map<String,Object>> getServiceList(){
List<Map<String,Object>> list =new ArrayList();
List<Element> elements = root.selectNodes("service");
for(Element element:elements){
@@ -63,12 +83,47 @@ public class ServiceConfigTemplateUtil {
}
return list;
}
/**
*
* @return
*/
public static Set<String> getCompileTableName(){
Set<String> result = Sets.newHashSet();
List<Element> elements = root.selectNodes("service");
for(Element element:elements){
String ev = element.attribute("tableName").getStringValue();
if(StringUtils.isNotBlank(ev)) {
result.add(ev.toLowerCase());
}
}
return result;
}
/**
* 根据类名 获取对应的 表名
* @param className
* @return
*/
public static String getCfgTableNameByClassName(String className) {
if(className == null) return null;
List<Element> elements = root.selectNodes("service");
for(Element element:elements){
String ev = element.attribute("tableName").getStringValue();
String cn = element.attribute("className").getStringValue();
if(className.equalsIgnoreCase(cn)) {
return ev.toLowerCase();
}
}
return null;
}
/**
*
* @param functionId
* @return
*/
public List<Map<String,Object>> getServiceListByFunctionId(Integer functionId){
public static List<Map<String,Object>> getServiceListByFunctionId(Integer functionId){
List<Map<String,Object>> list =new ArrayList();
if(!StringUtil.isEmpty(functionId)) {
List<FunctionServiceDict> serviceList = DictUtils.getFunctionServiceDictList(functionId);
@@ -133,7 +188,7 @@ public class ServiceConfigTemplateUtil {
* 获取业务配置列表
* @return
*/
public List<Map<String,Object>> getServiceCfgList(Element serviceNode){
public static List<Map<String,Object>> getServiceCfgList(Element serviceNode){
List<Map<String,Object>> list = new ArrayList();
List<Element> elements = serviceNode.selectNodes("serviceCfg");
for(Element element:elements){
@@ -149,7 +204,7 @@ public class ServiceConfigTemplateUtil {
* 获取用户自定义域列表
* @return
*/
public List<Map<String,Object>> getUserRegionList(Element serviceNode){
public static List<Map<String,Object>> getUserRegionList(Element serviceNode){
List<Map<String,Object>> list = new ArrayList();
List<Element> elements = serviceNode.selectNodes("userRegion");
for(Element element:elements){
@@ -167,7 +222,7 @@ public class ServiceConfigTemplateUtil {
* @param attribute
* @return
*/
public List getXmlParamListByTag(String tag,String attribute){
public static List getXmlParamListByTag(String tag,String attribute){
List list =new ArrayList();
List<Element> elements = root.selectNodes(tag);
for(Element element:elements){
@@ -196,6 +251,7 @@ public class ServiceConfigTemplateUtil {
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();

View File

@@ -0,0 +1,76 @@
package com.nis.web.dao;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.nis.domain.ScheduleCfg;
import com.nis.domain.ScheduleExceInfo;
import com.nis.domain.configuration.BaseCfg;
@MyBatisDao
public interface SchedulerDao extends CrudDao<ScheduleCfg> {
List<ScheduleCfg> findScheduleList(ScheduleCfg cfg);
/**
* 查找最新的修改数据
* @param id
* @param size
* @return
*/
List<ScheduleCfg> findNewlyCfg(@Param("id")Long id,@Param("limit")Long limit);
/**
* 更新 del_flag 字段为删除标识
* @param cfg
* @return
*/
int deleteByCompileId(ScheduleCfg cfg);
/**
* 查找 配置 下发 最新记录
* @param compileId
* @param isValid
* @return
*/
ScheduleExceInfo findScheduleExceNew(ScheduleExceInfo se);
/**
* 修改配置表状态
* @param tableName
* @param compileId
* @param isValid
* @return
*/
int updateCfgTableStatus(@Param("tableName")String tableName,@Param("compileId")Integer compileId,@Param("isValid")Integer isValid);
/**
* 查询 配置信息
* @param compileId
* @return
*/
BaseCfg getCfgTableInfo(@Param("tableName")String tableName,@Param("compileId")Integer compileId);
/**
* 保存执行记录
* @param exceInfo
* @return
*/
int insertScheduleExceLog(ScheduleExceInfo exceInfo);
/**
* 保存最新记录表
* @param exceInfo
* @return
*/
int insertScheduleExceNew(ScheduleExceInfo exceInfo);
/**
* 更新最新记录表
* @param exceInfo
* @return
*/
int updateScheduleExceNew(ScheduleExceInfo exceInfo);
}

View File

@@ -0,0 +1,315 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.nis.web.dao.SchedulerDao" >
<resultMap type="com.nis.domain.ScheduleCfg" id="scheduleCfgMap">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="cronValid" column="cron_valid"/>
<result property="cronInvalid" column="cron_invalid"/>
<result property="cfgId" column="cfg_id"/>
<result property="compileId" column="compile_id"/>
<result property="serviceId" column="service_id"/>
<result property="isValid" column="is_valid"/>
<result property="isAudit" column="is_audit"/>
<result property="functionId" column="function_id"/>
<result property="creatorId" column="creator_id"/>
<result property="createTime" column="create_time"/>
<result property="editorId" column="editor_id"/>
<result property="editTime" column="edit_time"/>
<result property="tableName" column="table_name"/>
<result property="userRegion1" column="user_region1"/>
<result property="userRegion2" column="user_region2"/>
<result property="userRegion3" column="user_region3"/>
<result property="userRegion4" column="user_region4"/>
<result property="userRegion5" column="user_region5"/>
<result property="delFlag" column="del_flag"/>
</resultMap>
<resultMap type="com.nis.domain.ScheduleExceInfo" id="scheduleExceInfoMap">
<id property="id" column="id"/>
<result property="scheduleId" column="schedule_id"/>
<result property="exceTime" column="exce_time"/>
<result property="issueStatus" column="issue_status"/>
<result property="issueResult" column="issue_result"/>
<result property="errorInfo" column="error_info"/>
<result property="compileId" column="compile_id"/>
<result property="isIssue" column="is_issue"/>
</resultMap>
<resultMap id="baseCfgMap" type="com.nis.domain.configuration.BaseCfg" >
<id column="cfg_id" property="cfgId" jdbcType="BIGINT" />
<result column="cfg_desc" property="cfgDesc" jdbcType="VARCHAR" />
<result column="action" property="action" jdbcType="INTEGER" />
<result column="is_valid" property="isValid" jdbcType="INTEGER" />
<result column="is_audit" property="isAudit" jdbcType="INTEGER" />
<result column="creator_id" property="creatorId" jdbcType="INTEGER" />
<result column="create_time" property="createTime" jdbcType="TIMESTAMP" />
<result column="editor_id" property="editorId" jdbcType="INTEGER" />
<result column="edit_time" property="editTime" jdbcType="TIMESTAMP" />
<result column="auditor_id" property="auditorId" jdbcType="INTEGER" />
<result column="audit_time" property="auditTime" jdbcType="TIMESTAMP" />
<result column="service_id" property="serviceId" jdbcType="INTEGER" />
<result column="request_id" property="requestId" jdbcType="INTEGER" />
<result column="compile_id" property="compileId" jdbcType="INTEGER" />
<result column="is_area_effective" property="isAreaEffective" jdbcType="INTEGER" />
<result column="classify" property="classify" jdbcType="VARCHAR" />
<result column="attribute" property="attribute" jdbcType="VARCHAR" />
<result column="lable" property="lable" jdbcType="VARCHAR" />
<result column="area_effective_ids" property="areaEffectiveIds" jdbcType="VARCHAR" />
<result column="function_id" property="functionId" jdbcType="INTEGER" />
<result column="do_log" property="doLog" jdbcType="INTEGER" />
<result column="do_blacklist" property="doBlackList" jdbcType="INTEGER" />
</resultMap>
<sql id="scheduleCfgColumns">
a.ID,
a.NAME,
a.cron_valid,
a.cron_invalid,
a.SERVICE_ID,
a.COMPILE_ID,
a.CFG_ID,
a.IS_VALID,
a.IS_AUDIT,
a.function_id,
a.CREATOR_ID,
a.CREATE_TIME,
a.EDITOR_ID,
a.EDIT_TIME,
a.table_name,
a.user_region1,
a.user_region2,
a.user_region3,
a.user_region4,
a.user_region5
</sql>
<select id="findScheduleList" resultMap="scheduleCfgMap">
select
<include refid="scheduleCfgColumns"/>
from schedule_cfg a
<where>
del_Flag = #{DEL_FLAG_NORMAL}
<if test="id != null">
and id = #{id}
</if>
<if test="compileId != null">
and compile_id = #{compileId}
</if>
<if test="isValid != null">
and IS_VALID = #{isValid}
</if>
<if test="isAudit != null">
and IS_AUDIT = #{isAudit}
</if>
<if test="compileId != null">
and CFG_ID = #{cfgId}
</if>
<if test="functionId != null">
and function_id = #{functionId}
</if>
<if test="tableName != null and tableName != ''">
and table_name = #{tableName}
</if>
<!-- 动态where条件 -->
<if test=" whereStr != null and whereStr !=''">
${whereStr}
</if>
</where>
order by a.id
</select>
<!-- 查找最新的更新数据 -->
<select id="findNewlyCfg" resultMap="scheduleCfgMap">
select
a.ID,
a.NAME,
a.cron_valid,
a.cron_invalid,
a.SERVICE_ID,
a.COMPILE_ID,
a.CFG_ID,
a.IS_VALID,
a.IS_AUDIT,
a.CREATOR_ID,
a.CREATE_TIME,
a.EDITOR_ID,
a.EDIT_TIME,
a.table_name,
a.user_region1,
a.user_region2,
a.user_region3,
a.user_region4,
a.user_region5
from schedule_cfg a
<where>
del_Flag = 1
and id > #{id}
</where>
order by a.id
limit #{limit}
</select>
<insert id="insert" parameterType="com.nis.domain.ScheduleCfg" useGeneratedKeys="true" keyProperty="id" >
insert into schedule_cfg (
NAME,
cron_valid,
cron_invalid,
SERVICE_ID,
COMPILE_ID,
CFG_ID,
IS_VALID,
IS_AUDIT,
function_id,
CREATOR_ID,
CREATE_TIME,
EDITOR_ID,
EDIT_TIME,
table_name,
user_region1,
user_region2,
user_region3,
user_region4,
user_region5
) values (
#{name,jdbcType=VARCHAR},
#{cronValid,jdbcType=VARCHAR},
#{cronInvalid,jdbcType=VARCHAR},
#{serviceId,jdbcType=INTEGER},
#{compileId,jdbcType=INTEGER},
#{cfgId,jdbcType=INTEGER},
#{isValid,jdbcType=INTEGER},
#{isAudit,jdbcType=INTEGER},
#{functionId,jdbcType=INTEGER},
#{creatorId,jdbcType=INTEGER},
#{createTime,jdbcType=TIMESTAMP},
#{editorId,jdbcType=INTEGER},
#{editTime,jdbcType=TIMESTAMP},
#{tableName,jdbcType=VARCHAR},
#{userRegion1,jdbcType=VARCHAR},
#{userRegion2,jdbcType=VARCHAR},
#{userRegion3,jdbcType=VARCHAR},
#{userRegion4,jdbcType=VARCHAR},
#{userRegion5,jdbcType=VARCHAR}
)
</insert>
<!-- 根据 compileId 将定时任务失效,定时任务的修改策略为:删除之前的所有配置,新增 -->
<update id="deleteByCompileId" parameterType="com.nis.domain.ScheduleCfg">
update schedule_cfg
<set>
<if test="editorId != null ">
editor_Id = #{editorId,jdbcType=VARCHAR},
</if>
<if test="editTime != null ">
edit_Time = #{editTime,jdbcType=TIMESTAMP},
</if>
del_flag = #{DEL_FLAG_DELETE}
</set>
WHERE compile_Id = #{compileId} and del_flag =1
</update>
<!-- 查找 配置 下发 最新记录 -->
<select id="findScheduleExceNew" resultMap="scheduleExceInfoMap" >
SELECT
id,
schedule_id,
exce_time,
issue_status,
issue_result,
error_info,
compile_id,
is_issue
FROM
schedule_exce_new
WHERE
compile_id = #{compileId} and issue_status = #{isValid}
</select>
<!-- 修改配置表状态 -->
<update id="updateCfgTableStatus">
update ${tableName} set is_valid = #{isValid} ,is_audit = 1 where compile_id = #{compileId}
</update>
<!-- 查询最新的配置状态 -->
<select id="getCfgTableInfo" resultMap="baseCfgMap">
select * from ${tableName} where compile_id = #{compileId};
</select>
<!-- 保存执行记录 -->
<insert id="insertScheduleExceLog" parameterType="com.nis.domain.ScheduleExceInfo">
INSERT INTO schedule_exce_log (
schedule_id,
exce_time,
issue_status,
issue_result,
error_info,
compile_id,
is_issue
) VALUES (
#{scheduleId},
#{exceTime},
#{issueStatus},
#{issueResult},
#{errorInfo},
#{compileId},
0
);
</insert>
<!-- 保存最新记录表 -->
<insert id="insertScheduleExceNew" parameterType="com.nis.domain.ScheduleExceInfo">
INSERT INTO schedule_exce_new (
schedule_id,
exce_time,
issue_status,
issue_result,
error_info,
compile_id,
is_issue
) VALUES (
#{scheduleId},
#{exceTime},
#{issueStatus},
#{issueResult},
#{errorInfo},
#{compileId},
0
);
</insert>
<!-- 更新最新记录表 -->
<update id="updateScheduleExceNew" parameterType="com.nis.domain.ScheduleExceInfo">
UPDATE schedule_exce_new
<set>
<if test="scheduleId != null">
schedule_id = #{scheduleId},
</if>
<if test=" exceTime != null">
exce_time = #{exceTime},
</if>
<if test=" issueResult != null">
issue_result = #{issueResult},
</if>
<if test=" errorInfo != null">
error_info = #{errorInfo},
</if>
<if test=" isIssue != null">
is_issue = #{isIssue},
</if>
</set>
WHERE
compile_Id = #{compileId} and issue_status = #{issueStatus}
</update>
</mapper>

View File

@@ -99,4 +99,6 @@ public interface ConfigSynchronizationDao {
public List<AppIpCfg> getAppIpFeatureList(BaseCfg entity);
public void updateCfgStatus(BaseCfg entity);
public PxyObjSpoofingIpPool getPxyObjSpoofingIpPool(Long cfgId);
}

View File

@@ -733,6 +733,39 @@
<result column="dns_strategy_id" property="dnsStrategyId" jdbcType="INTEGER" />
<result column="dns_strategy_name" property="dnsStrategyName" jdbcType="VARCHAR" />
</resultMap>
<resultMap id="PxyObjSpoofingPoolMap" type="com.nis.domain.configuration.PxyObjSpoofingIpPool" >
<id column="cfg_id" property="cfgId" jdbcType="BIGINT" />
<result column="cfg_desc" property="cfgDesc" jdbcType="VARCHAR" />
<result column="cfg_region_code" property="cfgRegionCode" jdbcType="INTEGER" />
<result column="ip_type" property="ipType" jdbcType="INTEGER" />
<result column="ip_address" property="ipAddress" jdbcType="VARCHAR" />
<result column="direction" property="direction" jdbcType="INTEGER" />
<result column="protocol" property="protocol" jdbcType="INTEGER" />
<result column="location" property="location" jdbcType="INTEGER" />
<result column="port" property="port" jdbcType="VARCHAR" />
<!-- <result column="action" property="action" jdbcType="INTEGER" /> -->
<result column="is_valid" property="isValid" jdbcType="INTEGER" />
<result column="is_audit" property="isAudit" jdbcType="INTEGER" />
<result column="creator_id" property="creatorId" jdbcType="INTEGER" />
<result column="create_time" property="createTime" jdbcType="TIMESTAMP" />
<result column="editor_id" property="editorId" jdbcType="INTEGER" />
<result column="edit_time" property="editTime" jdbcType="TIMESTAMP" />
<result column="auditor_id" property="auditorId" jdbcType="INTEGER" />
<result column="audit_time" property="auditTime" jdbcType="TIMESTAMP" />
<result column="service_id" property="serviceId" jdbcType="INTEGER" />
<result column="request_id" property="requestId" jdbcType="INTEGER" />
<result column="compile_id" property="compileId" jdbcType="INTEGER" />
<result column="location" property="location" jdbcType="INTEGER"/>
<result column="is_area_effective" property="isAreaEffective" jdbcType="INTEGER" />
<result column="classify" property="classify" jdbcType="VARCHAR" />
<result column="attribute" property="attribute" jdbcType="VARCHAR" />
<result column="lable" property="lable" jdbcType="VARCHAR" />
<result column="area_effective_ids" property="areaEffectiveIds" jdbcType="VARCHAR" />
<result column="function_id" property="functionId" jdbcType="INTEGER" />
<result column="group_id" property="groupId" jdbcType="INTEGER" />
<result column="group_name" property="groupName" jdbcType="INTEGER" />
<result column="user_region" property="userRegion" jdbcType="VARCHAR" />
</resultMap>
<sql id="BaseCfg_Column" >
a.cfg_id,a.cfg_desc,a.action,a.is_valid,a.is_audit,a.creator_id,a.audit_time,
a.service_id,a.request_id,a.compile_id,a.is_area_effective,a.classify,a.attribute,a.lable,
@@ -877,12 +910,13 @@
a.ip_type,a.src_ip_address,a.ip_pattern,a.port_pattern,a.src_port
,a.protocol,a.direction,a.dest_port,a.dest_ip_address,a.cfg_type,a.compile_id
</sql>
<sql id="PxyObjSpoofingIpPoolColumns">
a.CFG_ID, a.CFG_DESC,a.CFG_REGION_CODE, a.IP_TYPE, a.IP_ADDRESS,
a.DIRECTION,a.PROTOCOL,a.IS_VALID,a.IS_AUDIT,a.location,a.port,
a.CREATOR_ID,a.CREATE_TIME,a.EDITOR_ID,a.EDIT_TIME,a.AUDITOR_ID,a.AUDIT_TIME,
a.SERVICE_ID,a.REQUEST_ID,a.COMPILE_ID,a.IS_AREA_EFFECTIVE,a.CLASSIFY,
a.ATTRIBUTE,a.LABLE,a.AREA_EFFECTIVE_IDS,a.FUNCTION_ID,a.GROUP_ID,a.user_region
<sql id="PxyObjSpoofingIpPoolColumns">
r.CFG_ID, r.CFG_DESC,r.CFG_REGION_CODE, r.IP_TYPE, r.IP_ADDRESS,
r.DIRECTION,r.PROTOCOL,r.IS_VALID,r.IS_AUDIT,r.location,r.port,
r.CREATOR_ID,r.CREATE_TIME,r.EDITOR_ID,r.EDIT_TIME,r.AUDITOR_ID,r.AUDIT_TIME,
r.SERVICE_ID,r.REQUEST_ID,r.COMPILE_ID,r.IS_AREA_EFFECTIVE,r.CLASSIFY,
r.ATTRIBUTE,r.LABLE,r.AREA_EFFECTIVE_IDS,r.FUNCTION_ID,r.GROUP_ID,r.user_region
</sql>
<!-- <sql id="WebsiteDomainTopic_Column">
id,website_service_id websiteServiceId,domain,topic_id topicId,create_time createTime,creator_id creatorId,is_valid isValid
@@ -938,7 +972,16 @@
<if test="action != null">
AND a.action=#{action,jdbcType=INTEGER}
</if>
and a.is_valid=#{isValid} and a.is_audit=#{isAudit} and a.is_valid!=-1
<if test="isValid != null">
AND a.is_valid=#{isValid,jdbcType=INTEGER}
</if>
<if test="isAudit != null">
AND a.is_audit=#{isAudit,jdbcType=INTEGER}
</if>
<if test="compileId != null">
AND a.compile_id=#{compileId,jdbcType=INTEGER}
</if>
and a.is_valid!=-1
</trim>
ORDER BY a.CFG_ID
</select>
@@ -961,7 +1004,16 @@
<if test="action != null">
AND a.action=#{action,jdbcType=INTEGER}
</if>
and a.is_valid=#{isValid} and a.is_audit=#{isAudit} and a.is_valid!=-1
<if test="isValid != null">
AND a.is_valid=#{isValid,jdbcType=INTEGER}
</if>
<if test="isAudit != null">
AND a.is_audit=#{isAudit,jdbcType=INTEGER}
</if>
<if test="compileId != null">
AND a.compile_id=#{compileId,jdbcType=INTEGER}
</if>
and a.is_valid!=-1
</trim>
ORDER BY a.CFG_ID
</select>
@@ -1602,6 +1654,13 @@
and function_id=#{functionId,jdbcType=INTEGER}
</trim>
</update>
<select id="getPxyObjSpoofingIpPool" resultMap="PxyObjSpoofingPoolMap" >
SELECT
<include refid="PxyObjSpoofingIpPoolColumns"/>
FROM pxy_obj_spoofing_ip_pool r
where r.CFG_ID=#{cfgId,jdbcType=BIGINT}
</select>
<!-- <select id="findAppPolicyList" resultMap="AppPolicyCfgMap" parameterType="com.nis.domain.configuration.AppPolicyCfg" >
select
<include refid="AppPolicyCfg_Column"/>

View File

@@ -0,0 +1,116 @@
package com.nis.web.service;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.nis.domain.ScheduleCfg;
import com.nis.domain.ScheduleExceInfo;
import com.nis.domain.configuration.BaseCfg;
import com.nis.util.SchedulerTaskUtil;
import com.nis.util.ServiceConfigTemplateUtil;
import com.nis.web.dao.SchedulerDao;
import com.nis.web.dao.configuration.ConfigSynchronizationDao;
@Service
public class ScheduleService extends BaseService{
@Autowired
private SchedulerDao dao ;
@Autowired
private ConfigSynchronizationDao configSynchronizationDao;
@SuppressWarnings("rawtypes")
@Transactional(readOnly=false,rollbackFor=RuntimeException.class)
public void issueCompileInfo(ScheduleCfg cfg,Integer isValid) {
Integer compileId = cfg.getCompileId();
BaseCfg baseCfg = dao.getCfgTableInfo(cfg.getTableName(),compileId);//查询当前配置的最新状态
Integer curIsValid = baseCfg.getIsValid();//当前配置的最新 是否有效信息
if(curIsValid == isValid) {
logger.info(String.format("当前isValid状态没有变化,不需执行,compileId:%s,isValid : %s", compileId,isValid));
return;
}
//1、根据 compileId isvalid 查找new 判断是否已经下发过
ScheduleExceInfo se = new ScheduleExceInfo();
se.setCompileId(compileId);
se.setIsValid(isValid);
ScheduleExceInfo exceNew = dao.findScheduleExceNew(se);
//2、如果已经下发直接下发状态否则下发配置
Integer issueResult = 1;
String errorInfo = null;
String tableName = cfg.getTableName();
SchedulerTaskUtil scheduler = new SchedulerTaskUtil();
boolean udpateConfigStatus = false;
try {
if(isValid == 1 && (exceNew == null || exceNew.getIsIssue() == 1)) {//生效配置需要下发
udpateConfigStatus = scheduler.updateConfigByServiceAndCompile(cfg.getServiceId(), compileId, isValid, 1,configSynchronizationDao);
logger.info(String.format("定时器下发配置内容compileId:%s,isValid:%s,issueResult:%s,errorInfo:%s",compileId,isValid,issueResult,errorInfo));
}else{//只需修改状态
udpateConfigStatus = scheduler.updateConfigByServiceAndCompile(cfg.getServiceId(), compileId, isValid, 0,configSynchronizationDao);
logger.info(String.format("定时器修改配置状态compileId:%s,isValid:%s,issueResult:%s,errorInfo:%s",compileId,isValid,issueResult,errorInfo));
}
} catch (NoSuchFieldException e) {
udpateConfigStatus = false;
e.printStackTrace();
} catch (SecurityException e) {
udpateConfigStatus = false;
e.printStackTrace();
} catch (IllegalArgumentException e) {
udpateConfigStatus = false;
e.printStackTrace();
} catch (IllegalAccessException e) {
udpateConfigStatus = false;
e.printStackTrace();
}
// logger.info(String.format("配置状态更新compileId:%s,isValid:%s,issueResult:%s,errorInfo:%s",compileId,isValid,issueResult,errorInfo));
if(udpateConfigStatus){//配置更新成功
if(exceNew == null) {
//新增exce_new 表状态
exceNew = new ScheduleExceInfo();
exceNew.setCompileId(compileId);
exceNew.setIssueStatus(isValid);
exceNew.setExceTime(new Date());
exceNew.setIssueResult(issueResult);
exceNew.setErrorInfo(errorInfo);
exceNew.setIsIssue(0);
exceNew.setScheduleId(cfg.getId());
dao.insertScheduleExceNew(exceNew);
}else {
//修改 exce_new 表状态
exceNew.setExceTime(new Date());
exceNew.setIssueResult(issueResult);
exceNew.setErrorInfo(errorInfo);
exceNew.setScheduleId(cfg.getId());
dao.updateScheduleExceNew(exceNew);
}
ServiceConfigTemplateUtil serviceTemplate = new ServiceConfigTemplateUtil();
List<Map<String,Object>> serviceList = serviceTemplate.getServiceListByServiceId(cfg.getServiceId());
//根据编译ID查询配置表中的配置信息
for(Map<String,Object> service:serviceList){
//获取业务下的配置域
List<Map<String,Object>> cfgList = (List<Map<String, Object>>) service.get("cfgList");
//查询子域配置详情
if(cfgList!=null){
for(Map<String,Object> m:cfgList){
String regionTable = m.get("tableName").toString();
//更新配置域表的isValid字段
dao.updateCfgTableStatus(regionTable, compileId, isValid);
}
}
}
//3、更新 配置表的 isValid 字段,添加 exce_log 记录
dao.insertScheduleExceLog(exceNew);
dao.updateCfgTableStatus(tableName, compileId, isValid);
}
}
}