作者 钟来

修改登录的bug

正在显示 38 个修改的文件 包含 4292 行增加223 行删除

要显示太多修改。

为保证性能只显示 38 of 38+ 个文件。

... ... @@ -9,7 +9,6 @@
<version>1.0-SNAPSHOT</version>
</parent>
<groupId>com.luhui</groupId>
<artifactId>lh-service-dao</artifactId>
<properties>
... ... @@ -18,4 +17,32 @@
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- 数据库 -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>commons-dbutils</groupId>
<artifactId>commons-dbutils</artifactId>
<version>1.6</version>
</dependency>
<dependency>
<groupId>commons-pool</groupId>
<artifactId>commons-pool</artifactId>
<version>1.6</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!--常用工具类 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
</dependencies>
</project>
\ No newline at end of file
... ...
package com.zhonglai.luhui.service.dao;
import com.zhonglai.luhui.service.dao.annotation.PublicSQLConfig;
import com.zhonglai.luhui.service.dao.util.StringUtils;
import org.apache.commons.dbutils.*;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* 数据库操作
* Created by zhonglai on 2016/12/15.
*/
public class BaseDao {
private DBFactory dBFactory = new DBFactoryImp();
public BaseDao(DBFactory dBFactory)
{
this.dBFactory = dBFactory;
}
public BaseDao()
{
}
/**
* 指定表名插入对象
* @param object 传值对象
*/
public void insert(Object object )
{
QueryRunner runner = new QueryRunner(dBFactory.getDataSource());
String sql = "insert into ";
sql += changTableNameFromObject(object) + "(";
Field[] fields = object.getClass().getDeclaredFields( );
String values = "(";
List<Object> valueList = new ArrayList<Object>();
for(Field field:fields)
{//
PublicSQLConfig publicSQLConfig = field.getAnnotation(PublicSQLConfig.class);
if(null !=publicSQLConfig && !publicSQLConfig.isSelect())
{
continue;
}
Method method;
try {
method = object.getClass().getMethod("get"+ StringUtils.getName(field.getName()));
Object value = method.invoke(object);
if(null != value)
{
if(!"(".equals(values) )
{
sql += ",";
values += ",";
}
sql += "`"+ StringUtils.toUnderScoreCase(field.getName())+"`";
values += "?";
valueList.add(value);
}
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
sql += ")";
values += ")";
sql = sql+" values "+values;
try {
// 创建一个BeanProcessor对象
// GenerousBeanProcessor 仅仅重写了父类BeanProcessor的mapColumnsToProperties方法
BeanProcessor bean = new GenerousBeanProcessor();
// 将GenerousBeanProcessor对象传递给BasicRowProcessor
RowProcessor processor = new BasicRowProcessor(bean);
object = runner.insert(sql,new BeanHandler<Object>(Object.class,processor),valueList.toArray());
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 插入对象集合
* @param objectList
*/
public int insertList(List<Object> objectList)
{
return insertList(objectList,null);
}
/**
* 指定表名插入对象集合
* @param objectList
*/
public int insertList(List<?> objectList ,String tableName)
{
QueryRunner runner = new QueryRunner(dBFactory.getDataSource());
Object object = objectList.get(0);
String sql = "insert into ";
if(StringUtils.isBlank(tableName))
{
tableName = StringUtils.toUnderScoreCase(object.getClass().getSimpleName());
}
List<Object> valueList = new ArrayList<Object>();
sql += tableName + msaicAttribute(object) + " values " +msaicValues(objectList,valueList);
try {
return runner.update(sql,valueList.toArray());
} catch (SQLException e) {
e.printStackTrace();
}
return 0;
}
/**
* 拼接属性条件
* @param object
* @return
*/
private String msaicAttribute(Object object)
{
Field[] fields = object.getClass().getDeclaredFields( );
String attributeStr = "(";
List<Object> valueList = new ArrayList<Object>();
for(Field field:fields)
{//
if(!"(".equals(attributeStr) )
{
attributeStr += ",";
}
attributeStr += "`"+ StringUtils.toUnderScoreCase(field.getName())+"`";
}
attributeStr += ")";
return attributeStr;
}
private String msaicValues(List<?> objectList,List<Object> valueList)
{
StringBuffer returnValues = new StringBuffer();
for(Object object:objectList)
{
Field[] fields = object.getClass().getDeclaredFields( );
String values = "(";
for(Field field:fields)
{//
PublicSQLConfig publicSQLConfig = field.getAnnotation(PublicSQLConfig.class);
if(null !=publicSQLConfig && !publicSQLConfig.isSelect())
{
continue;
}
Method method;
try {
method = object.getClass().getMethod("get"+ StringUtils.getName(field.getName()));
Object value = method.invoke(object);
if(!"(".equals(values) )
{
values += ",";
}
values += "?";
valueList.add(value);
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
values += ")";
if(returnValues.length()!=0)
{
returnValues.append(",");
}
returnValues.append(values);
}
return returnValues.toString();
}
/**
* 以主键id更新对象
* @param object
*/
public int update(Object object)
{
return update(object,null);
}
/**
* 根据条件更新对象
* @param object 传值对象
* @param whereFieldNames 条件(多个用,分割)
*/
public int update(Object object,String whereFieldNames)
{
QueryRunner runner = new QueryRunner(dBFactory.getDataSource());
String sql = "update ";
sql += changTableNameFromObject(object);
Field[] fields = object.getClass().getDeclaredFields();
List<Object> valueList = new ArrayList<Object>();
if(null != fields && fields.length !=0 )
{
sql += " set ";
int j = 0;
for(int i=0;i<fields.length;i++)
{
Field field = fields[i];
try {
PublicSQLConfig publicSQLConfig = field.getAnnotation(PublicSQLConfig.class);
if(null !=publicSQLConfig && !publicSQLConfig.isSelect())
{
continue;
}
Method method = null;
try {
method = object.getClass().getMethod("get"+ StringUtils.getName(field.getName()));
} catch (NoSuchMethodException e) {
continue;
}
Object value = method.invoke(object);
if(null != value)
{
if(j!=0)
{
sql += ",";
}
sql += "`"+ StringUtils.toUnderScoreCase(field.getName())+"`"+"=?";
j++;
valueList.add(value);
}
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
sql += " where 1=1 ";
if(StringUtils.isNoneBlank(whereFieldNames))
{
String[] wheres = whereFieldNames.split(",");
if(StringUtils.isNotBlank(whereFieldNames))
{
for(int i =0;i<wheres.length;i++)
{
try {
Method method = object.getClass().getMethod("get"+ StringUtils.getName(wheres[i]));
Object value = method.invoke(object);
sql += " and ";
sql += StringUtils.toUnderScoreCase(wheres[i]) + "=?";
valueList.add(value);
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}else{
Method method = null;
try {
String idName = "id";
for(Field field:fields)
{
PublicSQLConfig publicSQLConfig1 = field.getAnnotation(PublicSQLConfig.class);
if(null !=publicSQLConfig1 && !publicSQLConfig1.isSelect())
{
continue;
}
PublicSQLConfig publicSQLConfig = field.getAnnotation(PublicSQLConfig.class);
if(null != publicSQLConfig && publicSQLConfig.isPrimarykey())
{
idName = field.getName();
}
}
method = object.getClass().getMethod("get"+ StringUtils.getName(idName));
Object value = method.invoke(object);
sql += " and ";
sql += idName+"=?";
valueList.add(value);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
try {
return runner.update(sql,valueList.toArray());
} catch (SQLException e) {
e.printStackTrace();
}
return 0;
}
/**
* 根据条件获取对象
* @param clas 对象
* @param where 条件
* @param <T>
* @return
*/
public <T> Object get(Class<T> clas,Map<String,Object> where)
{
QueryRunner runner = new QueryRunner(dBFactory.getDataSource());
String tableName = StringUtils.toUnderScoreCase(clas.getSimpleName());
String sql = "select * from "+tableName+" where 1=1 ";
try {
List<Object> valueList = new ArrayList<Object>();
sql += getCountFrommapWhere(where,valueList);
return runner.query(sql, new BeanHandler<T>(clas, getRowProcessor()),valueList.toArray());
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
/**
* 根据条件获取对象
* @param clas 对象
* @param where 条件
* @param <T>
* @return
*/
public <T> Object get(Class<T> clas,String where,String tableName)
{
QueryRunner runner = new QueryRunner(dBFactory.getDataSource());
String sql = "select * from "+tableName+" where 1=1 ";
try {
sql += "and "+where;
return runner.query(sql, new BeanHandler<T>(clas, getRowProcessor()));
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
/**
* 根据id获取对象
* @param clas 对象
* @param id 主键id
* @param <T>
* @return
*/
public <T> Object get(Class<T> clas,Object id)
{
QueryRunner runner = new QueryRunner(dBFactory.getDataSource());
String tableName = StringUtils.toUnderScoreCase(clas.getSimpleName());
String sql = "select * from "+tableName+" where 1=1 ";
String idName = "id";
Field[] fields = clas.getDeclaredFields();
for(Field field:fields)
{
PublicSQLConfig publicSQLConfig1 = field.getAnnotation(PublicSQLConfig.class);
if(null !=publicSQLConfig1 && !publicSQLConfig1.isSelect())
{
continue;
}
PublicSQLConfig publicSQLConfig = field.getAnnotation(PublicSQLConfig.class);
if(null != publicSQLConfig && publicSQLConfig.isPrimarykey())
{
idName = field.getName();
}
}
try {
sql += " and "+idName+"=?";
Object[] params = {id};
return runner.query(sql, new BeanHandler<T>(clas, getRowProcessor()),params);
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
/**
* 根据条件删除对象
* @param clas 对象
* @param where 条件
* @return
*/
public int delete(Class<?> clas, Map<String,Object> where)
{
QueryRunner runner = new QueryRunner(dBFactory.getDataSource());
String tableName = StringUtils.toUnderScoreCase(clas.getSimpleName());
String sql = "DELETE FROM "+tableName+" WHERE 1=1 ";
try {
List<Object> valueList = new ArrayList<Object>();
sql += getCountFrommapWhere(where,valueList);
return runner.update(sql,valueList.toArray());
} catch (SQLException e) {
e.printStackTrace();
}
return 0;
}
/**
* 根据id删除对象
* @param clas 对象
* @param id 主键id
*/
public int delete(Class<?> clas,Object id)
{
return delete(clas,id,null);
}
/**
* 根据id删除对象
* @param clas 对象
* @param id 主键id
*/
public int delete(Class<?> clas,Object id,String tableName)
{
QueryRunner runner = new QueryRunner(dBFactory.getDataSource());
if(StringUtils.isBlank(tableName))
{
tableName = StringUtils.toUnderScoreCase(clas.getSimpleName());
}
String sql = "DELETE FROM "+tableName+" WHERE 1=1 ";
try {
sql += " and id=?";
Object[] params = {id};
return runner.update(sql,params);
} catch (SQLException e) {
e.printStackTrace();
}
return 0;
}
/**
* 对象条件获取对象列表
* @param object 对象条件
* @param <T>
* @return
*/
public <T> T find(Object object)
{
return find(object,"*");
}
/**
* 对象条件获取对象指定属性值列表
* @param object 对象条件
* @param selectStr 指定属性值(用数据库表字段多个,分割)
* @param <T>
* @return
*/
public <T> T find(Object object,String selectStr)
{
return find(object,selectStr,null);
}
/**
* 对象条件的条件获取对象列表
* @param object 对象条件
* @param selectStr 指定属性值(用数据库表字段多个,分割)
* @param whereMap 对象条件的条件
* @param <T>
* @return
*/
public <T> T find(Object object,String selectStr,Map<String,String> whereMap)
{
return find(object,selectStr,whereMap,null);
}
/**
* 对象条件的条件按一定排序获取对象列表
* @param object 对象条件
* @param selectStr 指定属性值(用数据库表字段多个,分割)
* @param whereMap 对象条件的条件
* @param order 排序条件
* @param <T>
* @return
*/
public <T> T find(Object object,String selectStr,Map<String,String> whereMap,String order)
{
return find(object,selectStr,whereMap,order,0,0);
}
/**
* 对象条件获取对象列表
* @param object 对象条件
* @param selectStr 指定属性值(用数据库表字段多个,分割)
* @param whereMap 对象条件的条件
* @param order 排序条件
* @param pageSize 页面大小
* @param pageNo 页码
* @param <T>
* @return
*/
public <T> T find(Object object,String selectStr,Map<String,String> whereMap,String order,Integer pageSize,Integer pageNo )
{
QueryRunner runner = new QueryRunner(dBFactory.getDataSource());
if(StringUtils.isBlank(order))
{
order = "";
}
if(null == pageSize)
{
pageSize = 0;
}
if(null == pageNo)
{
pageNo = 0;
}
if(StringUtils.isBlank("selectStr"))
{
selectStr = "*";
}
List<Object> valueList = new ArrayList<Object>();
String sql = getFindSql(object,selectStr,whereMap,valueList);
if(StringUtils.isNotBlank(order))
{
sql += " order by "+order;
}
if(0 != pageSize && 0 != pageNo)
{
sql += " limit "+((pageNo-1)*pageSize)+","+pageSize;
}
try {
return (T) runner.
query(sql,new BeanListHandler(object.getClass(),getRowProcessor()),valueList.toArray());
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
/**
* sql执行查询
* @param sql
* @return
*/
public <T> T findBysql(String sql,Class type,Object... params)
{
QueryRunner runner = new QueryRunner(dBFactory.getDataSource());
try {
return (T) runner.
query(sql,new BeanListHandler(type,getRowProcessor()),params);
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
/**
* 对象条件获取总数
* @param object 对象条件
* @return
*/
public Long getTotle(Object object )
{
QueryRunner runner = new QueryRunner(dBFactory.getDataSource());
List<Object> valueList = new ArrayList<Object>();
String sql = getFindSql(object,"count(*)",null,valueList);
try {
return runner.query(sql,new ScalarHandler<Long>(),valueList.toArray());
} catch (SQLException e) {
e.printStackTrace();
}
return 0l;
}
/**
* 对象条件的条件获取总数
* @param object 对象条件
* @param whereMap 对象条件的条件
* @return
*/
public Long getTotle(Object object,Map<String,String> whereMap)
{
QueryRunner runner = new QueryRunner(dBFactory.getDataSource());
List<Object> valueList = new ArrayList<Object>();
String sql = getFindSql(object,"count(*)",whereMap,valueList);
try {
return runner.query(sql,new ScalarHandler<Long>(),valueList.toArray());
} catch (SQLException e) {
e.printStackTrace();
}
return 0l;
}
/**
* sql执行查询
* @param sql
* @return
*/
public List findListBysql(String sql)
{
QueryRunner runner = new QueryRunner(dBFactory.getDataSource());
List list = null;
try {
list = runner.query(sql,new MapListHandler());
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}
/**
* sql执行查询
* @param sql
* @return
*/
public List<Map<String,Object>> findBysql(String sql)
{
QueryRunner runner = new QueryRunner(dBFactory.getDataSource());
List list = null;
try {
list = runner.query(sql,new MapListHandler());
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}
/**
* sql执行更新
* @param sql
* @param params
* @return
*/
public int updateBySql(String sql,Object... params)
{
QueryRunner runner = new QueryRunner(dBFactory.getDataSource());
try {
return runner.update(sql,params);
} catch (SQLException e) {
e.printStackTrace();
}
return 0;
}
/**
* 生成查询条件
* @param object
* @param selectStr
* @param whereMap
* @param valueList
* @return
*/
private String getFindSql(Object object,String selectStr,Map<String,String> whereMap,List<Object> valueList )
{
String sql = null;
sql = "select "+selectStr+" from "+ changTableNameFromObject(object);
String where = " where 1=1 ";
String like = "";
Field[] fields = object.getClass().getDeclaredFields();
if(null != fields && fields.length !=0 )
{
for(int i=0;i<fields.length;i++)
{
Field field = fields[i];
PublicSQLConfig publicSQLConfig = field.getAnnotation(PublicSQLConfig.class);
if(null !=publicSQLConfig && !publicSQLConfig.isSelect())
{
continue;
}
try {
Method method;
method = object.getClass().getMethod("get"+ StringUtils.getName(field.getName()));
Object value = method.invoke(object);
if(!(null == value))
{
String orther = "";
String s = "=";
if(!(null == whereMap || null == whereMap.get(field.getName())))
{
s = whereMap.get(field.getName());
if("like".equals(s))
{
value = "%"+value+"%";
like += " or " + "`"+ StringUtils.toUnderScoreCase(field.getName())+"`"+s+" ?"+orther ;
valueList.add(value);
continue;
}
if("time".equals(s))
{
s = ">";
orther = " and `"+ StringUtils.toUnderScoreCase(field.getName())+"`< '"+whereMap.get("end_"+field.getName())+"'";
}
}
where += " and `"+ StringUtils.toUnderScoreCase(field.getName())+"`"+s+" ?"+orther;
valueList.add(value);
}
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
sql += where;
if(StringUtils.isNoneBlank(like))
{
sql += "and (1=2 "+like+")";
}
return sql;
}
/**
* 添加或更新对象
* INSERT INTO test(`in1`,`str1`) VALUES ('1','1');
* @param object 对象
* @return
*/
public void saveOrUpdateObject(Object object)
{
String sql = "insert into ";
sql += changTableNameFromObject(object) + "(";
Field[] fields = object.getClass().getDeclaredFields( );
String values = "(";
String update = "";
for(Field field:fields)
{//
Method method;
try {
PublicSQLConfig publicSQLConfig = field.getAnnotation(PublicSQLConfig.class);
if(null !=publicSQLConfig && !publicSQLConfig.isSelect())
{
continue;
}
method = object.getClass().getMethod("get"+ StringUtils.getName(field.getName()));
Object value = method.invoke(object);
if(null != value)
{
if(!"(".equals(values) )
{
sql += ",";
values += ",";
update += ",";
}
sql += "`"+ StringUtils.toUnderScoreCase(field.getName())+"`";
values += "'"+ value+"'";
update += "`"+ StringUtils.toUnderScoreCase(field.getName())+"`"+"=VALUES("+"`"+ StringUtils.toUnderScoreCase(field.getName())+"`)";
}
} catch (NoSuchMethodException e) {
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
sql += ")";
values += ")";
try {
QueryRunner runner = new QueryRunner(dBFactory.getDataSource());
runner.update(sql+" values "+values+" ON DUPLICATE KEY UPDATE "+update);
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 添加或更新对象列表
* INSERT INTO `test` (`in1`,`str1`)VALUES ('1','2'),('2','2') ON DUPLICATE KEY UPDATE `in1`=VALUES(`in1`),`str1`=VALUES(`str1`);
* @param objectlist 对象列表
* @return
*/
public void saveOrUpdateObjectList(List<Object> objectlist)
{
StringBuffer sb =new StringBuffer();
String update = "";
for(int i = 0; i<objectlist.size();i++)
{
Object object = objectlist.get(i);
Field[] fields = object.getClass().getDeclaredFields( );
if(i==0)
{
sb.append("INSERT INTO `"+changTableNameFromObject(object)+"` ");
sb.append("(");
for(Field field:fields)
{
PublicSQLConfig publicSQLConfig = field.getAnnotation(PublicSQLConfig.class);
if(null !=publicSQLConfig && !publicSQLConfig.isSelect())
{
continue;
}
if(!"".equals(update) )
{
sb.append(",");
update += ",";
}
sb.append("`"+ StringUtils.toUnderScoreCase(field.getName())+"`");
update += "`"+ StringUtils.toUnderScoreCase(field.getName())+"`"+"=VALUES("+"`"+ StringUtils.toUnderScoreCase(field.getName())+"`)";
}
sb.append(")");
sb.append("VALUES ");
}else{
sb.append(",");
}
for(int j=0;j<fields.length;j++)
{
Field field = fields[j];
Method method;
try {
method = object.getClass().getMethod("get"+ StringUtils.getName(field.getName()));
Object value = method.invoke(object);
if(null == value)
{
value = "";
}
if(j!=0)
{
sb.append(",");
}else{
sb.append("(");
}
sb.append("'"+ value+"'");
if(j==fields.length-1)
{
sb.append(")");
}
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
sb.append(" ON DUPLICATE KEY UPDATE ");
sb.append(update);
try {
QueryRunner runner = new QueryRunner(dBFactory.getDataSource());
runner.update(sb.toString());
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 将map条件转换成sql条件
* @param mapwhere map条件
* @param valueList sql条件参数
* @return
*/
private String getCountFrommapWhere(Map<String,Object> mapwhere,List<Object> valueList)
{
String where = "";
for(String key:mapwhere.keySet())
{
Object value = mapwhere.get(key);
where += " and ";
where += StringUtils.toUnderScoreCase(key) + "=?";
valueList.add(value);
}
return where;
}
/**
* 获取一个驼峰过滤规则类
* @return
*/
private RowProcessor getRowProcessor()
{
// 创建一个BeanProcessor对象
// GenerousBeanProcessor 仅仅重写了父类BeanProcessor的mapColumnsToProperties方法
BeanProcessor bean = new GenerousBeanProcessor();
// 将GenerousBeanProcessor对象传递给BasicRowProcessor
return new BasicRowProcessor(bean);
}
/**
* 对象转变数据库名
* @param object 对象
* @return
*/
public static String changTableNameFromObject(Object object) {
Class clas = object.getClass();
String tableNmae = clas.getSimpleName();
Method method = null; // 父类对象调用子类方法(反射原理)
try {
method = clas.getMethod("getTableName");
Object tObject = method.invoke(object);
if(null != tObject)
{
tableNmae = (String) tObject;
}
} catch (NoSuchMethodException e) {
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return StringUtils.toUnderScoreCase(tableNmae);
}
public QueryRunner query()
{
return new QueryRunner(dBFactory.getDataSource());
}
}
... ...
/**
* @version 0.1
* @describe 数据库链接工厂
* @author yushigui
* @date 2014-1-19
*/
package com.zhonglai.luhui.service.dao;
import javax.sql.DataSource;
public interface DBFactory {
public DataSource getDataSource();
}
... ...
/**
* @version 0.1
* @describe 数据库链接工厂
* @author yushigui
* @date 2014-1-19
*/
package com.zhonglai.luhui.service.dao;
import org.apache.commons.dbcp.BasicDataSourceFactory;
import javax.sql.DataSource;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
public class DBFactoryImp implements DBFactory{
private static DataSource ds = null;
static {
try {
if(null==ds )
{
String dbPath = System.getProperty("dbPath");
String path = null != dbPath?dbPath:System.getProperty("user.dir")+"/configs/";
Properties p = new Properties();
System.out.println("》》》》》》》》》》》》》数据库配置文件地址:"+path+"dbcpconfig.properties");
p.load(new FileInputStream(path+"dbcpconfig.properties"));
// p.load(DBFactory.class
// .getClassLoader().getResourceAsStream("configs/dbcpconfig.properties"));
ds = BasicDataSourceFactory.createDataSource(p);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConnection() {
try {
return ds.getConnection();
} catch (SQLException e) {
e.printStackTrace();
return null;
}
}
public DataSource getDataSource(){
return ds;
}
}
... ...
package com.zhonglai.luhui.service.dao.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface PublicSQLConfig {
boolean isSelect() default true;
boolean isPrimarykey() default false;
}
... ...
package com.zhonglai.luhui.service.dao.util;
import org.apache.commons.lang3.ArrayUtils;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.text.NumberFormat;
import java.util.Set;
/**
* 类型转换器
*
* @author ruoyi
*/
public class Convert
{
/** UTF-8 */
public static final String UTF_8 = "UTF-8";
public static final Charset CHARSET_UTF_8 = Charset.forName(UTF_8);
/**
* 转换为字符串<br>
* 如果给定的值为null,或者转换失败,返回默认值<br>
* 转换失败不会报错
*
* @param value 被转换的值
* @param defaultValue 转换错误时的默认值
* @return 结果
*/
public static String toStr(Object value, String defaultValue)
{
if (null == value)
{
return defaultValue;
}
if (value instanceof String)
{
return (String) value;
}
return value.toString();
}
/**
* 转换为字符串<br>
* 如果给定的值为<code>null</code>,或者转换失败,返回默认值<code>null</code><br>
* 转换失败不会报错
*
* @param value 被转换的值
* @return 结果
*/
public static String toStr(Object value)
{
return toStr(value, null);
}
/**
* 转换为字符<br>
* 如果给定的值为null,或者转换失败,返回默认值<br>
* 转换失败不会报错
*
* @param value 被转换的值
* @param defaultValue 转换错误时的默认值
* @return 结果
*/
public static Character toChar(Object value, Character defaultValue)
{
if (null == value)
{
return defaultValue;
}
if (value instanceof Character)
{
return (Character) value;
}
final String valueStr = toStr(value, null);
return StringUtils.isEmpty(valueStr) ? defaultValue : valueStr.charAt(0);
}
/**
* 转换为字符<br>
* 如果给定的值为<code>null</code>,或者转换失败,返回默认值<code>null</code><br>
* 转换失败不会报错
*
* @param value 被转换的值
* @return 结果
*/
public static Character toChar(Object value)
{
return toChar(value, null);
}
/**
* 转换为byte<br>
* 如果给定的值为<code>null</code>,或者转换失败,返回默认值<br>
* 转换失败不会报错
*
* @param value 被转换的值
* @param defaultValue 转换错误时的默认值
* @return 结果
*/
public static Byte toByte(Object value, Byte defaultValue)
{
if (value == null)
{
return defaultValue;
}
if (value instanceof Byte)
{
return (Byte) value;
}
if (value instanceof Number)
{
return ((Number) value).byteValue();
}
final String valueStr = toStr(value, null);
if (StringUtils.isEmpty(valueStr))
{
return defaultValue;
}
try
{
return Byte.parseByte(valueStr);
}
catch (Exception e)
{
return defaultValue;
}
}
/**
* 转换为byte<br>
* 如果给定的值为<code>null</code>,或者转换失败,返回默认值<code>null</code><br>
* 转换失败不会报错
*
* @param value 被转换的值
* @return 结果
*/
public static Byte toByte(Object value)
{
return toByte(value, null);
}
/**
* 转换为Short<br>
* 如果给定的值为<code>null</code>,或者转换失败,返回默认值<br>
* 转换失败不会报错
*
* @param value 被转换的值
* @param defaultValue 转换错误时的默认值
* @return 结果
*/
public static Short toShort(Object value, Short defaultValue)
{
if (value == null)
{
return defaultValue;
}
if (value instanceof Short)
{
return (Short) value;
}
if (value instanceof Number)
{
return ((Number) value).shortValue();
}
final String valueStr = toStr(value, null);
if (StringUtils.isEmpty(valueStr))
{
return defaultValue;
}
try
{
return Short.parseShort(valueStr.trim());
}
catch (Exception e)
{
return defaultValue;
}
}
/**
* 转换为Short<br>
* 如果给定的值为<code>null</code>,或者转换失败,返回默认值<code>null</code><br>
* 转换失败不会报错
*
* @param value 被转换的值
* @return 结果
*/
public static Short toShort(Object value)
{
return toShort(value, null);
}
/**
* 转换为Number<br>
* 如果给定的值为空,或者转换失败,返回默认值<br>
* 转换失败不会报错
*
* @param value 被转换的值
* @param defaultValue 转换错误时的默认值
* @return 结果
*/
public static Number toNumber(Object value, Number defaultValue)
{
if (value == null)
{
return defaultValue;
}
if (value instanceof Number)
{
return (Number) value;
}
final String valueStr = toStr(value, null);
if (StringUtils.isEmpty(valueStr))
{
return defaultValue;
}
try
{
return NumberFormat.getInstance().parse(valueStr);
}
catch (Exception e)
{
return defaultValue;
}
}
/**
* 转换为Number<br>
* 如果给定的值为空,或者转换失败,返回默认值<code>null</code><br>
* 转换失败不会报错
*
* @param value 被转换的值
* @return 结果
*/
public static Number toNumber(Object value)
{
return toNumber(value, null);
}
/**
* 转换为int<br>
* 如果给定的值为空,或者转换失败,返回默认值<br>
* 转换失败不会报错
*
* @param value 被转换的值
* @param defaultValue 转换错误时的默认值
* @return 结果
*/
public static Integer toInt(Object value, Integer defaultValue)
{
if (value == null)
{
return defaultValue;
}
if (value instanceof Integer)
{
return (Integer) value;
}
if (value instanceof Number)
{
return ((Number) value).intValue();
}
final String valueStr = toStr(value, null);
if (StringUtils.isEmpty(valueStr))
{
return defaultValue;
}
try
{
return Integer.parseInt(valueStr.trim());
}
catch (Exception e)
{
return defaultValue;
}
}
/**
* 转换为int<br>
* 如果给定的值为<code>null</code>,或者转换失败,返回默认值<code>null</code><br>
* 转换失败不会报错
*
* @param value 被转换的值
* @return 结果
*/
public static Integer toInt(Object value)
{
return toInt(value, null);
}
/**
* 转换为Integer数组<br>
*
* @param str 被转换的值
* @return 结果
*/
public static Integer[] toIntArray(String str)
{
return toIntArray(",", str);
}
/**
* 转换为Long数组<br>
*
* @param str 被转换的值
* @return 结果
*/
public static Long[] toLongArray(String str)
{
return toLongArray(",", str);
}
/**
* 转换为Integer数组<br>
*
* @param split 分隔符
* @param split 被转换的值
* @return 结果
*/
public static Integer[] toIntArray(String split, String str)
{
if (StringUtils.isEmpty(str))
{
return new Integer[] {};
}
String[] arr = str.split(split);
final Integer[] ints = new Integer[arr.length];
for (int i = 0; i < arr.length; i++)
{
final Integer v = toInt(arr[i], 0);
ints[i] = v;
}
return ints;
}
/**
* 转换为Long数组<br>
*
* @param split 分隔符
* @param str 被转换的值
* @return 结果
*/
public static Long[] toLongArray(String split, String str)
{
if (StringUtils.isEmpty(str))
{
return new Long[] {};
}
String[] arr = str.split(split);
final Long[] longs = new Long[arr.length];
for (int i = 0; i < arr.length; i++)
{
final Long v = toLong(arr[i], null);
longs[i] = v;
}
return longs;
}
/**
* 转换为String数组<br>
*
* @param str 被转换的值
* @return 结果
*/
public static String[] toStrArray(String str)
{
return toStrArray(",", str);
}
/**
* 转换为String数组<br>
*
* @param split 分隔符
* @param split 被转换的值
* @return 结果
*/
public static String[] toStrArray(String split, String str)
{
return str.split(split);
}
/**
* 转换为long<br>
* 如果给定的值为空,或者转换失败,返回默认值<br>
* 转换失败不会报错
*
* @param value 被转换的值
* @param defaultValue 转换错误时的默认值
* @return 结果
*/
public static Long toLong(Object value, Long defaultValue)
{
if (value == null)
{
return defaultValue;
}
if (value instanceof Long)
{
return (Long) value;
}
if (value instanceof Number)
{
return ((Number) value).longValue();
}
final String valueStr = toStr(value, null);
if (StringUtils.isEmpty(valueStr))
{
return defaultValue;
}
try
{
// 支持科学计数法
return new BigDecimal(valueStr.trim()).longValue();
}
catch (Exception e)
{
return defaultValue;
}
}
/**
* 转换为long<br>
* 如果给定的值为<code>null</code>,或者转换失败,返回默认值<code>null</code><br>
* 转换失败不会报错
*
* @param value 被转换的值
* @return 结果
*/
public static Long toLong(Object value)
{
return toLong(value, null);
}
/**
* 转换为double<br>
* 如果给定的值为空,或者转换失败,返回默认值<br>
* 转换失败不会报错
*
* @param value 被转换的值
* @param defaultValue 转换错误时的默认值
* @return 结果
*/
public static Double toDouble(Object value, Double defaultValue)
{
if (value == null)
{
return defaultValue;
}
if (value instanceof Double)
{
return (Double) value;
}
if (value instanceof Number)
{
return ((Number) value).doubleValue();
}
final String valueStr = toStr(value, null);
if (StringUtils.isEmpty(valueStr))
{
return defaultValue;
}
try
{
// 支持科学计数法
return new BigDecimal(valueStr.trim()).doubleValue();
}
catch (Exception e)
{
return defaultValue;
}
}
/**
* 转换为double<br>
* 如果给定的值为空,或者转换失败,返回默认值<code>null</code><br>
* 转换失败不会报错
*
* @param value 被转换的值
* @return 结果
*/
public static Double toDouble(Object value)
{
return toDouble(value, null);
}
/**
* 转换为Float<br>
* 如果给定的值为空,或者转换失败,返回默认值<br>
* 转换失败不会报错
*
* @param value 被转换的值
* @param defaultValue 转换错误时的默认值
* @return 结果
*/
public static Float toFloat(Object value, Float defaultValue)
{
if (value == null)
{
return defaultValue;
}
if (value instanceof Float)
{
return (Float) value;
}
if (value instanceof Number)
{
return ((Number) value).floatValue();
}
final String valueStr = toStr(value, null);
if (StringUtils.isEmpty(valueStr))
{
return defaultValue;
}
try
{
return Float.parseFloat(valueStr.trim());
}
catch (Exception e)
{
return defaultValue;
}
}
/**
* 转换为Float<br>
* 如果给定的值为空,或者转换失败,返回默认值<code>null</code><br>
* 转换失败不会报错
*
* @param value 被转换的值
* @return 结果
*/
public static Float toFloat(Object value)
{
return toFloat(value, null);
}
/**
* 转换为boolean<br>
* String支持的值为:true、false、yes、ok、no,1,0 如果给定的值为空,或者转换失败,返回默认值<br>
* 转换失败不会报错
*
* @param value 被转换的值
* @param defaultValue 转换错误时的默认值
* @return 结果
*/
public static Boolean toBool(Object value, Boolean defaultValue)
{
if (value == null)
{
return defaultValue;
}
if (value instanceof Boolean)
{
return (Boolean) value;
}
String valueStr = toStr(value, null);
if (StringUtils.isEmpty(valueStr))
{
return defaultValue;
}
valueStr = valueStr.trim().toLowerCase();
switch (valueStr)
{
case "true":
return true;
case "false":
return false;
case "yes":
return true;
case "ok":
return true;
case "no":
return false;
case "1":
return true;
case "0":
return false;
default:
return defaultValue;
}
}
/**
* 转换为boolean<br>
* 如果给定的值为空,或者转换失败,返回默认值<code>null</code><br>
* 转换失败不会报错
*
* @param value 被转换的值
* @return 结果
*/
public static Boolean toBool(Object value)
{
return toBool(value, null);
}
/**
* 转换为Enum对象<br>
* 如果给定的值为空,或者转换失败,返回默认值<br>
*
* @param clazz Enum的Class
* @param value 值
* @param defaultValue 默认值
* @return Enum
*/
public static <E extends Enum<E>> E toEnum(Class<E> clazz, Object value, E defaultValue)
{
if (value == null)
{
return defaultValue;
}
if (clazz.isAssignableFrom(value.getClass()))
{
@SuppressWarnings("unchecked")
E myE = (E) value;
return myE;
}
final String valueStr = toStr(value, null);
if (StringUtils.isEmpty(valueStr))
{
return defaultValue;
}
try
{
return Enum.valueOf(clazz, valueStr);
}
catch (Exception e)
{
return defaultValue;
}
}
/**
* 转换为Enum对象<br>
* 如果给定的值为空,或者转换失败,返回默认值<code>null</code><br>
*
* @param clazz Enum的Class
* @param value 值
* @return Enum
*/
public static <E extends Enum<E>> E toEnum(Class<E> clazz, Object value)
{
return toEnum(clazz, value, null);
}
/**
* 转换为BigInteger<br>
* 如果给定的值为空,或者转换失败,返回默认值<br>
* 转换失败不会报错
*
* @param value 被转换的值
* @param defaultValue 转换错误时的默认值
* @return 结果
*/
public static BigInteger toBigInteger(Object value, BigInteger defaultValue)
{
if (value == null)
{
return defaultValue;
}
if (value instanceof BigInteger)
{
return (BigInteger) value;
}
if (value instanceof Long)
{
return BigInteger.valueOf((Long) value);
}
final String valueStr = toStr(value, null);
if (StringUtils.isEmpty(valueStr))
{
return defaultValue;
}
try
{
return new BigInteger(valueStr);
}
catch (Exception e)
{
return defaultValue;
}
}
/**
* 转换为BigInteger<br>
* 如果给定的值为空,或者转换失败,返回默认值<code>null</code><br>
* 转换失败不会报错
*
* @param value 被转换的值
* @return 结果
*/
public static BigInteger toBigInteger(Object value)
{
return toBigInteger(value, null);
}
/**
* 转换为BigDecimal<br>
* 如果给定的值为空,或者转换失败,返回默认值<br>
* 转换失败不会报错
*
* @param value 被转换的值
* @param defaultValue 转换错误时的默认值
* @return 结果
*/
public static BigDecimal toBigDecimal(Object value, BigDecimal defaultValue)
{
if (value == null)
{
return defaultValue;
}
if (value instanceof BigDecimal)
{
return (BigDecimal) value;
}
if (value instanceof Long)
{
return new BigDecimal((Long) value);
}
if (value instanceof Double)
{
return new BigDecimal((Double) value);
}
if (value instanceof Integer)
{
return new BigDecimal((Integer) value);
}
final String valueStr = toStr(value, null);
if (StringUtils.isEmpty(valueStr))
{
return defaultValue;
}
try
{
return new BigDecimal(valueStr);
}
catch (Exception e)
{
return defaultValue;
}
}
/**
* 转换为BigDecimal<br>
* 如果给定的值为空,或者转换失败,返回默认值<br>
* 转换失败不会报错
*
* @param value 被转换的值
* @return 结果
*/
public static BigDecimal toBigDecimal(Object value)
{
return toBigDecimal(value, null);
}
/**
* 将对象转为字符串<br>
* 1、Byte数组和ByteBuffer会被转换为对应字符串的数组 2、对象数组会调用Arrays.toString方法
*
* @param obj 对象
* @return 字符串
*/
public static String utf8Str(Object obj)
{
return str(obj, CHARSET_UTF_8);
}
/**
* 将对象转为字符串<br>
* 1、Byte数组和ByteBuffer会被转换为对应字符串的数组 2、对象数组会调用Arrays.toString方法
*
* @param obj 对象
* @param charsetName 字符集
* @return 字符串
*/
public static String str(Object obj, String charsetName)
{
return str(obj, Charset.forName(charsetName));
}
/**
* 将对象转为字符串<br>
* 1、Byte数组和ByteBuffer会被转换为对应字符串的数组 2、对象数组会调用Arrays.toString方法
*
* @param obj 对象
* @param charset 字符集
* @return 字符串
*/
public static String str(Object obj, Charset charset)
{
if (null == obj)
{
return null;
}
if (obj instanceof String)
{
return (String) obj;
}
else if (obj instanceof byte[])
{
return str((byte[]) obj, charset);
}
else if (obj instanceof Byte[])
{
byte[] bytes = ArrayUtils.toPrimitive((Byte[]) obj);
return str(bytes, charset);
}
else if (obj instanceof ByteBuffer)
{
return str((ByteBuffer) obj, charset);
}
return obj.toString();
}
/**
* 将byte数组转为字符串
*
* @param bytes byte数组
* @param charset 字符集
* @return 字符串
*/
public static String str(byte[] bytes, String charset)
{
return str(bytes, StringUtils.isEmpty(charset) ? Charset.defaultCharset() : Charset.forName(charset));
}
/**
* 解码字节码
*
* @param data 字符串
* @param charset 字符集,如果此字段为空,则解码的结果取决于平台
* @return 解码后的字符串
*/
public static String str(byte[] data, Charset charset)
{
if (data == null)
{
return null;
}
if (null == charset)
{
return new String(data);
}
return new String(data, charset);
}
/**
* 将编码的byteBuffer数据转换为字符串
*
* @param data 数据
* @param charset 字符集,如果为空使用当前系统字符集
* @return 字符串
*/
public static String str(ByteBuffer data, String charset)
{
if (data == null)
{
return null;
}
return str(data, Charset.forName(charset));
}
/**
* 将编码的byteBuffer数据转换为字符串
*
* @param data 数据
* @param charset 字符集,如果为空使用当前系统字符集
* @return 字符串
*/
public static String str(ByteBuffer data, Charset charset)
{
if (null == charset)
{
charset = Charset.defaultCharset();
}
return charset.decode(data).toString();
}
// ----------------------------------------------------------------------- 全角半角转换
/**
* 半角转全角
*
* @param input String.
* @return 全角字符串.
*/
public static String toSBC(String input)
{
return toSBC(input, null);
}
/**
* 半角转全角
*
* @param input String
* @param notConvertSet 不替换的字符集合
* @return 全角字符串.
*/
public static String toSBC(String input, Set<Character> notConvertSet)
{
char c[] = input.toCharArray();
for (int i = 0; i < c.length; i++)
{
if (null != notConvertSet && notConvertSet.contains(c[i]))
{
// 跳过不替换的字符
continue;
}
if (c[i] == ' ')
{
c[i] = '\u3000';
}
else if (c[i] < '\177')
{
c[i] = (char) (c[i] + 65248);
}
}
return new String(c);
}
/**
* 全角转半角
*
* @param input String.
* @return 半角字符串
*/
public static String toDBC(String input)
{
return toDBC(input, null);
}
/**
* 替换全角为半角
*
* @param text 文本
* @param notConvertSet 不替换的字符集合
* @return 替换后的字符
*/
public static String toDBC(String text, Set<Character> notConvertSet)
{
char c[] = text.toCharArray();
for (int i = 0; i < c.length; i++)
{
if (null != notConvertSet && notConvertSet.contains(c[i]))
{
// 跳过不替换的字符
continue;
}
if (c[i] == '\u3000')
{
c[i] = ' ';
}
else if (c[i] > '\uFF00' && c[i] < '\uFF5F')
{
c[i] = (char) (c[i] - 65248);
}
}
String returnString = new String(c);
return returnString;
}
/**
* 数字金额大写转换 先写个完整的然后将如零拾替换成零
*
* @param n 数字
* @return 中文大写数字
*/
public static String digitUppercase(double n)
{
String[] fraction = { "角", "分" };
String[] digit = { "零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖" };
String[][] unit = { { "元", "万", "亿" }, { "", "拾", "佰", "仟" } };
String head = n < 0 ? "负" : "";
n = Math.abs(n);
String s = "";
for (int i = 0; i < fraction.length; i++)
{
s += (digit[(int) (Math.floor(n * 10 * Math.pow(10, i)) % 10)] + fraction[i]).replaceAll("(零.)+", "");
}
if (s.length() < 1)
{
s = "整";
}
int integerPart = (int) Math.floor(n);
for (int i = 0; i < unit[0].length && integerPart > 0; i++)
{
String p = "";
for (int j = 0; j < unit[1].length && n > 0; j++)
{
p = digit[integerPart % 10] + unit[1][j] + p;
integerPart = integerPart / 10;
}
s = p.replaceAll("(零.)*零$", "").replaceAll("^$", "零") + unit[0][i] + s;
}
return head + s.replaceAll("(零.)*零元", "元").replaceFirst("(零.)+", "").replaceAll("(零.)+", "零").replaceAll("^整$", "零元整");
}
}
... ...
package com.zhonglai.luhui.service.dao.util;
/**
* 字符串格式化
*
* @author ruoyi
*/
public class StrFormatter
{
public static final String EMPTY_JSON = "{}";
public static final char C_BACKSLASH = '\\';
public static final char C_DELIM_START = '{';
public static final char C_DELIM_END = '}';
/**
* 格式化字符串<br>
* 此方法只是简单将占位符 {} 按照顺序替换为参数<br>
* 如果想输出 {} 使用 \\转义 { 即可,如果想输出 {} 之前的 \ 使用双转义符 \\\\ 即可<br>
* 例:<br>
* 通常使用:format("this is {} for {}", "a", "b") -> this is a for b<br>
* 转义{}: format("this is \\{} for {}", "a", "b") -> this is \{} for a<br>
* 转义\: format("this is \\\\{} for {}", "a", "b") -> this is \a for b<br>
*
* @param strPattern 字符串模板
* @param argArray 参数列表
* @return 结果
*/
public static String format(final String strPattern, final Object... argArray)
{
if (StringUtils.isEmpty(strPattern) || StringUtils.isEmpty(argArray))
{
return strPattern;
}
final int strPatternLength = strPattern.length();
// 初始化定义好的长度以获得更好的性能
StringBuilder sbuf = new StringBuilder(strPatternLength + 50);
int handledPosition = 0;
int delimIndex;// 占位符所在位置
for (int argIndex = 0; argIndex < argArray.length; argIndex++)
{
delimIndex = strPattern.indexOf(EMPTY_JSON, handledPosition);
if (delimIndex == -1)
{
if (handledPosition == 0)
{
return strPattern;
}
else
{ // 字符串模板剩余部分不再包含占位符,加入剩余部分后返回结果
sbuf.append(strPattern, handledPosition, strPatternLength);
return sbuf.toString();
}
}
else
{
if (delimIndex > 0 && strPattern.charAt(delimIndex - 1) == C_BACKSLASH)
{
if (delimIndex > 1 && strPattern.charAt(delimIndex - 2) == C_BACKSLASH)
{
// 转义符之前还有一个转义符,占位符依旧有效
sbuf.append(strPattern, handledPosition, delimIndex - 1);
sbuf.append(Convert.utf8Str(argArray[argIndex]));
handledPosition = delimIndex + 2;
}
else
{
// 占位符被转义
argIndex--;
sbuf.append(strPattern, handledPosition, delimIndex - 1);
sbuf.append(C_DELIM_START);
handledPosition = delimIndex + 1;
}
}
else
{
// 正常占位符
sbuf.append(strPattern, handledPosition, delimIndex);
sbuf.append(Convert.utf8Str(argArray[argIndex]));
handledPosition = delimIndex + 2;
}
}
}
// 加入最后一个占位符后所有的字符
sbuf.append(strPattern, handledPosition, strPattern.length());
return sbuf.toString();
}
}
... ...
package com.zhonglai.luhui.service.dao.util;
import java.util.*;
/**
* 字符串工具类
*
* @author ruoyi
*/
public class StringUtils extends org.apache.commons.lang3.StringUtils
{
/**
* http请求
*/
public static final String HTTP = "http://";
/**
* https请求
*/
public static final String HTTPS = "https://";
/** 空字符串 */
private static final String NULLSTR = "";
/** 下划线 */
private static final char SEPARATOR = '_';
/**
* 获取参数不为空值
*
* @param value defaultValue 要判断的value
* @return value 返回值
*/
public static <T> T nvl(T value, T defaultValue)
{
return value != null ? value : defaultValue;
}
/**
* * 判断一个Collection是否为空, 包含List,Set,Queue
*
* @param coll 要判断的Collection
* @return true:为空 false:非空
*/
public static boolean isEmpty(Collection<?> coll)
{
return isNull(coll) || coll.isEmpty();
}
/**
* * 判断一个Collection是否非空,包含List,Set,Queue
*
* @param coll 要判断的Collection
* @return true:非空 false:空
*/
public static boolean isNotEmpty(Collection<?> coll)
{
return !isEmpty(coll);
}
/**
* * 判断一个对象数组是否为空
*
* @param objects 要判断的对象数组
** @return true:为空 false:非空
*/
public static boolean isEmpty(Object[] objects)
{
return isNull(objects) || (objects.length == 0);
}
/**
* * 判断一个对象数组是否非空
*
* @param objects 要判断的对象数组
* @return true:非空 false:空
*/
public static boolean isNotEmpty(Object[] objects)
{
return !isEmpty(objects);
}
/**
* * 判断一个Map是否为空
*
* @param map 要判断的Map
* @return true:为空 false:非空
*/
public static boolean isEmpty(Map<?, ?> map)
{
return isNull(map) || map.isEmpty();
}
/**
* * 判断一个Map是否为空
*
* @param map 要判断的Map
* @return true:非空 false:空
*/
public static boolean isNotEmpty(Map<?, ?> map)
{
return !isEmpty(map);
}
/**
* * 判断一个字符串是否为空串
*
* @param str String
* @return true:为空 false:非空
*/
public static boolean isEmpty(String str)
{
return isNull(str) || NULLSTR.equals(str.trim());
}
/**
* * 判断一个字符串是否为非空串
*
* @param str String
* @return true:非空串 false:空串
*/
public static boolean isNotEmpty(String str)
{
return !isEmpty(str);
}
/**
* * 判断一个对象是否为空
*
* @param object Object
* @return true:为空 false:非空
*/
public static boolean isNull(Object object)
{
return object == null;
}
/**
* * 判断一个对象是否非空
*
* @param object Object
* @return true:非空 false:空
*/
public static boolean isNotNull(Object object)
{
return !isNull(object);
}
/**
* * 判断一个对象是否是数组类型(Java基本型别的数组)
*
* @param object 对象
* @return true:是数组 false:不是数组
*/
public static boolean isArray(Object object)
{
return isNotNull(object) && object.getClass().isArray();
}
/**
* 去空格
*/
public static String trim(String str)
{
return (str == null ? "" : str.trim());
}
/**
* 截取字符串
*
* @param str 字符串
* @param start 开始
* @return 结果
*/
public static String substring(final String str, int start)
{
if (str == null)
{
return NULLSTR;
}
if (start < 0)
{
start = str.length() + start;
}
if (start < 0)
{
start = 0;
}
if (start > str.length())
{
return NULLSTR;
}
return str.substring(start);
}
/**
* 截取字符串
*
* @param str 字符串
* @param start 开始
* @param end 结束
* @return 结果
*/
public static String substring(final String str, int start, int end)
{
if (str == null)
{
return NULLSTR;
}
if (end < 0)
{
end = str.length() + end;
}
if (start < 0)
{
start = str.length() + start;
}
if (end > str.length())
{
end = str.length();
}
if (start > end)
{
return NULLSTR;
}
if (start < 0)
{
start = 0;
}
if (end < 0)
{
end = 0;
}
return str.substring(start, end);
}
/**
* 格式化文本, {} 表示占位符<br>
* 此方法只是简单将占位符 {} 按照顺序替换为参数<br>
* 如果想输出 {} 使用 \\转义 { 即可,如果想输出 {} 之前的 \ 使用双转义符 \\\\ 即可<br>
* 例:<br>
* 通常使用:format("this is {} for {}", "a", "b") -> this is a for b<br>
* 转义{}: format("this is \\{} for {}", "a", "b") -> this is \{} for a<br>
* 转义\: format("this is \\\\{} for {}", "a", "b") -> this is \a for b<br>
*
* @param template 文本模板,被替换的部分用 {} 表示
* @param params 参数值
* @return 格式化后的文本
*/
public static String format(String template, Object... params)
{
if (isEmpty(params) || isEmpty(template))
{
return template;
}
return StrFormatter.format(template, params);
}
/**
* 是否为http(s)://开头
*
* @param link 链接
* @return 结果
*/
public static boolean ishttp(String link)
{
return StringUtils.startsWithAny(link, HTTP, HTTPS);
}
/**
* 字符串转set
*
* @param str 字符串
* @param sep 分隔符
* @return set集合
*/
public static final Set<String> str2Set(String str, String sep)
{
return new HashSet<String>(str2List(str, sep, true, false));
}
/**
* 字符串转list
*
* @param str 字符串
* @param sep 分隔符
* @param filterBlank 过滤纯空白
* @param trim 去掉首尾空白
* @return list集合
*/
public static final List<String> str2List(String str, String sep, boolean filterBlank, boolean trim)
{
List<String> list = new ArrayList<String>();
if (StringUtils.isEmpty(str))
{
return list;
}
// 过滤空白字符串
if (filterBlank && StringUtils.isBlank(str))
{
return list;
}
String[] split = str.split(sep);
for (String string : split)
{
if (filterBlank && StringUtils.isBlank(string))
{
continue;
}
if (trim)
{
string = string.trim();
}
list.add(string);
}
return list;
}
/**
* 查找指定字符串是否包含指定字符串列表中的任意一个字符串同时串忽略大小写
*
* @param cs 指定字符串
* @param searchCharSequences 需要检查的字符串数组
* @return 是否包含任意一个字符串
*/
public static boolean containsAnyIgnoreCase(CharSequence cs, CharSequence... searchCharSequences)
{
if (isEmpty(cs) || isEmpty(searchCharSequences))
{
return false;
}
for (CharSequence testStr : searchCharSequences)
{
if (containsIgnoreCase(cs, testStr))
{
return true;
}
}
return false;
}
/**
* 驼峰转下划线命名
*/
public static String toUnderScoreCase(String str)
{
if (str == null)
{
return null;
}
StringBuilder sb = new StringBuilder();
// 前置字符是否大写
boolean preCharIsUpperCase = true;
// 当前字符是否大写
boolean curreCharIsUpperCase = true;
// 下一字符是否大写
boolean nexteCharIsUpperCase = true;
for (int i = 0; i < str.length(); i++)
{
char c = str.charAt(i);
if (i > 0)
{
preCharIsUpperCase = Character.isUpperCase(str.charAt(i - 1));
}
else
{
preCharIsUpperCase = false;
}
curreCharIsUpperCase = Character.isUpperCase(c);
if (i < (str.length() - 1))
{
nexteCharIsUpperCase = Character.isUpperCase(str.charAt(i + 1));
}
if (preCharIsUpperCase && curreCharIsUpperCase && !nexteCharIsUpperCase)
{
sb.append(SEPARATOR);
}
else if ((i != 0 && !preCharIsUpperCase) && curreCharIsUpperCase)
{
sb.append(SEPARATOR);
}
sb.append(Character.toLowerCase(c));
}
return sb.toString();
}
/**
* 是否包含字符串
*
* @param str 验证字符串
* @param strs 字符串组
* @return 包含返回true
*/
public static boolean inStringIgnoreCase(String str, String... strs)
{
if (str != null && strs != null)
{
for (String s : strs)
{
if (str.equalsIgnoreCase(trim(s)))
{
return true;
}
}
}
return false;
}
/**
* 将下划线大写方式命名的字符串转换为驼峰式。如果转换前的下划线大写方式命名的字符串为空,则返回空字符串。 例如:HELLO_WORLD->HelloWorld
*
* @param name 转换前的下划线大写方式命名的字符串
* @return 转换后的驼峰式命名的字符串
*/
public static String convertToCamelCase(String name)
{
StringBuilder result = new StringBuilder();
// 快速检查
if (name == null || name.isEmpty())
{
// 没必要转换
return "";
}
else if (!name.contains("_"))
{
// 不含下划线,仅将首字母大写
return name.substring(0, 1).toUpperCase() + name.substring(1);
}
// 用下划线将原始字符串分割
String[] camels = name.split("_");
for (String camel : camels)
{
// 跳过原始字符串中开头、结尾的下换线或双重下划线
if (camel.isEmpty())
{
continue;
}
// 首字母大写
result.append(camel.substring(0, 1).toUpperCase());
result.append(camel.substring(1).toLowerCase());
}
return result.toString();
}
/**
* 驼峰式命名法 例如:user_name->userName
*/
public static String toCamelCase(String s)
{
if (s == null)
{
return null;
}
s = s.toLowerCase();
StringBuilder sb = new StringBuilder(s.length());
boolean upperCase = false;
for (int i = 0; i < s.length(); i++)
{
char c = s.charAt(i);
if (c == SEPARATOR)
{
upperCase = true;
}
else if (upperCase)
{
sb.append(Character.toUpperCase(c));
upperCase = false;
}
else
{
sb.append(c);
}
}
return sb.toString();
}
@SuppressWarnings("unchecked")
public static <T> T cast(Object obj)
{
return (T) obj;
}
/**
* 数字左边补齐0,使之达到指定长度。注意,如果数字转换为字符串后,长度大于size,则只保留 最后size个字符。
*
* @param num 数字对象
* @param size 字符串指定长度
* @return 返回数字的字符串格式,该字符串为指定长度。
*/
public static final String padl(final Number num, final int size)
{
return padl(num.toString(), size, '0');
}
/**
* 字符串左补齐。如果原始字符串s长度大于size,则只保留最后size个字符。
*
* @param s 原始字符串
* @param size 字符串指定长度
* @param c 用于补齐的字符
* @return 返回指定长度的字符串,由原字符串左补齐或截取得到。
*/
public static final String padl(final String s, final int size, final char c)
{
final StringBuilder sb = new StringBuilder(size);
if (s != null)
{
final int len = s.length();
if (s.length() <= size)
{
for (int i = size - len; i > 0; i--)
{
sb.append(c);
}
sb.append(s);
}
else
{
return s.substring(len - size, len);
}
}
else
{
for (int i = size; i > 0; i--)
{
sb.append(c);
}
}
return sb.toString();
}
/**
* [简要描述]:首字母大写
*
* @author com.zhonglai
* @param str
* @return
*/
public static String getName(String str) {
char ch = str.toCharArray()[0];
ch = (char) ((ch - 97) + 'A');
str = ch + str.substring(1);
return str;
}
public static void main(String[] args) {
System.out.println(StringUtils.toUnderScoreCase("deviceInfoId"));
}
}
\ No newline at end of file
... ...
package com.zhonglai.luhui.security.filter;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.zhonglai.luhui.security.dto.BaseLoginUser;
import com.zhonglai.luhui.security.service.TokenService;
import com.zhonglai.luhui.security.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
... ... @@ -29,12 +31,16 @@ public abstract class JwtAuthenticationTokenFilter extends OncePerRequestFilter
throws ServletException, IOException
{
BaseLoginUser loginUser = getBaseLoginUser(request);
if(verifyToken(loginUser))
if( StringUtils.isNotNull(loginUser) && verifyToken(loginUser))
{
UsernamePasswordAuthenticationToken authenticationToken = getUsernamePasswordAuthenticationToken(loginUser);
authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authenticationToken);
}else {
throw new ServiceException("token验证失败");
}
chain.doFilter(request, response);
}
public abstract BaseLoginUser getBaseLoginUser(HttpServletRequest request);
... ...
... ... @@ -49,8 +49,9 @@ public class SecurityConfigService {
private String antMatchers;
public void configHttpSecurity(HttpSecurity httpSecurity) throws Exception{
httpSecurity.logout().logoutUrl("/logout").logoutSuccessHandler(logoutSuccessHandler);
defaultConfigHttpSecurity(httpSecurity);
httpSecurity.logout().logoutUrl("/logout").logoutSuccessHandler(logoutSuccessHandler);
// 添加JWT filter
httpSecurity.addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
// 添加CORS filter
... ...
... ... @@ -25,6 +25,9 @@ public class GlobalExceptionHandler
{
private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
{
log.info("全局异常处理器");
}
/**
* 请求方式不支持
*/
... ...
... ... @@ -2,6 +2,8 @@ package com.zhonglai.luhui.device.domain;
import com.ruoyi.common.annotation.PublicSQLConfig;
import com.ruoyi.common.tool.BaseEntity;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
... ... @@ -11,33 +13,46 @@ import org.apache.commons.lang3.builder.ToStringStyle;
* @author kerwincui
* @date 2022-01-13
*/
@ApiModel("设备告警对象")
public class IotAlert extends BaseEntity
{
@PublicSQLConfig(isSelect=false)
private static final long serialVersionUID = 1L;
/** 告警ID */
@ApiModelProperty("告警ID")
private Long alertId;
/** 告警名称 */
@ApiModelProperty("告警名称")
private String alertName;
/** 告警级别(1=提醒通知,2=轻微问题,3=严重警告) */
@ApiModelProperty("告警级别(1=提醒通知,2=轻微问题,3=严重警告)")
private Long alertLevel;
/** 告警类型(1属性告警,2触发告警,3定时告警) */
@ApiModelProperty("告警类型(1属性告警,2触发告警,3定时告警)")
private Integer alertType;
/** 产品ID */
@ApiModelProperty("产品ID")
private Long productId;
/** 产品名称 */
@ApiModelProperty("产品名称")
private String productName;
/** 触发器 */
@ApiModelProperty("触发器")
private String triggers;
/** 执行动作 */
@ApiModelProperty("执行动作")
private String actions;
/** 告警状态 (1-启动,2-停止)**/
@ApiModelProperty("告警状态 (1-启动,2-停止)")
private Integer status;
public Integer getStatus() {
... ... @@ -112,12 +127,21 @@ public class IotAlert extends BaseEntity
return actions;
}
public Integer getAlertType() {
return alertType;
}
public void setAlertType(Integer alertType) {
this.alertType = alertType;
}
@Override
public String toString() {
return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)
.append("alertId", getAlertId())
.append("alertName", getAlertName())
.append("alertLevel", getAlertLevel())
.append("alertType", getAlertType())
.append("productId", getProductId())
.append("productName", getProductName())
.append("triggers", getTriggers())
... ...
... ... @@ -2,6 +2,8 @@ package com.zhonglai.luhui.device.domain;
import com.ruoyi.common.annotation.PublicSQLConfig;
import com.ruoyi.common.tool.BaseEntity;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
... ... @@ -11,77 +13,62 @@ import org.apache.commons.lang3.builder.ToStringStyle;
* @author kerwincui
* @date 2022-01-13
*/
@ApiModel("设备告警记录对象")
public class IotAlertLog extends BaseEntity
{
@PublicSQLConfig(isSelect=false)
private static final long serialVersionUID = 1L;
/** 告警ID */
@ApiModelProperty("主键")
private Long alertLogId;
/** 告警名称 */
@ApiModelProperty("告警名称")
private String alertName;
@ApiModelProperty("告警ID")
private Long alertId; // bigint DEFAULT NULL COMMENT '告警ID',
/** 告警级别(1=提醒通知,2=轻微问题,3=严重警告,4=场景联动) */
@ApiModelProperty("告警级别(1=提醒通知,2=轻微问题,3=严重警告,4=场景联动)")
private Long alertLevel;
/** 处理状态(0=不需要处理,1=未处理,2=已处理) */
@ApiModelProperty("处理状态(0=不需要处理,1=未处理,2=已处理)")
private Long status;
/** 产品ID */
private Long productId;
/** 产品名称 */
private String productName;
/** 设备ID */
private Long deviceId;
/** 设备名称 */
private String deviceName;
/** 用户ID */
private Long userId;
/** 用户昵称 */
private String userName;
/** 租户ID */
private Long tenantId;
@ApiModelProperty("设备ID")
private String deviceId;
/** 租户名称 */
private String tenantName;
@ApiModelProperty("创建时间")
private Long create_time; // datetime DEFAULT NULL COMMENT '创建时间',
@ApiModelProperty("类型(1=告警,2=场景联动)")
private Integer type; // tinyint DEFAULT NULL COMMENT '类型(1=告警,2=场景联动)',
public Long getUserId() {
return userId;
public Long getAlertId() {
return alertId;
}
public void setUserId(Long userId) {
this.userId = userId;
public void setAlertId(Long alertId) {
this.alertId = alertId;
}
public String getUserName() {
return userName;
public Long getCreate_time() {
return create_time;
}
public void setUserName(String userName) {
this.userName = userName;
public void setCreate_time(Long create_time) {
this.create_time = create_time;
}
public Long getTenantId() {
return tenantId;
public Integer getType() {
return type;
}
public void setTenantId(Long tenantId) {
this.tenantId = tenantId;
}
public String getTenantName() {
return tenantName;
}
public void setTenantName(String tenantName) {
this.tenantName = tenantName;
public void setType(Integer type) {
this.type = type;
}
public void setAlertLogId(Long alertLogId)
... ... @@ -120,42 +107,15 @@ public class IotAlertLog extends BaseEntity
{
return status;
}
public void setProductId(Long productId)
{
this.productId = productId;
}
public Long getProductId()
{
return productId;
}
public void setProductName(String productName)
{
this.productName = productName;
}
public String getProductName()
{
return productName;
}
public void setDeviceId(Long deviceId)
public void setDeviceId(String deviceId)
{
this.deviceId = deviceId;
}
public Long getDeviceId()
public String getDeviceId()
{
return deviceId;
}
public void setDeviceName(String deviceName)
{
this.deviceName = deviceName;
}
public String getDeviceName()
{
return deviceName;
}
@Override
public String toString() {
... ... @@ -164,10 +124,7 @@ public class IotAlertLog extends BaseEntity
.append("alertName", getAlertName())
.append("alertLevel", getAlertLevel())
.append("status", getStatus())
.append("productId", getProductId())
.append("productName", getProductName())
.append("deviceId", getDeviceId())
.append("deviceName", getDeviceName())
.append("createBy", getCreateBy())
.append("createTime", getCreateTime())
.append("updateBy", getUpdateBy())
... ...
... ... @@ -72,13 +72,13 @@ public class IotProduct implements Serializable
private Integer purification_clas; // varchar(100) DEFAULT 'com.zhonglai.luhui.device.protocol.factory.purification.DefaultProtocolPurificationFactoryImpl' COMMENT '清洗服务',
@ApiModelProperty("订阅服务器id")
private Integer subscribe_service_ip;
private String subscribe_service_ip;
public Integer getSubscribe_service_ip() {
public String getSubscribe_service_ip() {
return subscribe_service_ip;
}
public void setSubscribe_service_ip(Integer subscribe_service_ip) {
public void setSubscribe_service_ip(String subscribe_service_ip) {
this.subscribe_service_ip = subscribe_service_ip;
}
... ...
... ... @@ -7,5 +7,9 @@ public enum CommandType {
cleanDeviceHost,
cleanDeviceInfo,
upIotThingsModel,
upIotThingsModelTranslate
upIotThingsModelTranslate,
/**
* 添加订阅
*/
addSubscribe
}
... ...
... ... @@ -7,39 +7,28 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<resultMap type="com.zhonglai.luhui.device.domain.IotAlertLog" id="AlertLogResult">
<result property="alertLogId" column="alert_log__id" />
<result property="alertName" column="alert_name" />
<result property="alertId" column="alert_id" />
<result property="alertLevel" column="alert_level" />
<result property="status" column="status" />
<result property="productId" column="product_id" />
<result property="productName" column="product_name" />
<result property="deviceId" column="device_id" />
<result property="deviceName" column="device_name" />
<result property="createBy" column="create_by" />
<result property="createTime" column="create_time" />
<result property="updateBy" column="update_by" />
<result property="updateTime" column="update_time" />
<result property="remark" column="remark" />
<result property="userId" column="user_id" />
<result property="userName" column="user_name" />
<result property="tenantId" column="tenant_id" />
<result property="tenantName" column="tenant_name" />
<result property="create_time" column="create_time" />
<result property="type" column="type" />
</resultMap>
<sql id="selectAlertLogVo">
select alert_log__id, alert_name, alert_level, status, product_id, product_name, device_id, device_name,user_id, user_name, tenant_id, tenant_name, create_by, create_time, update_by, update_time, remark from iot_alert_log
select alert_log__id, alert_name,alert_id, alert_level, status, device_id, create_time, type from iot_alert_log
</sql>
<select id="selectAlertLogList" parameterType="com.zhonglai.luhui.device.domain.IotAlertLog" resultMap="AlertLogResult">
<include refid="selectAlertLogVo"/>
<where>
<if test="userId != null and userId != 0"> and user_id = #{userId}</if>
<if test="tenantId != null and tenantId != 0"> and tenant_id = #{tenantId}</if>
<if test="alertName != null and alertName != ''"> and alert_name like concat('%', #{alertName}, '%')</if>
<if test="alertLevel != null "> and alert_level = #{alertLevel}</if>
<if test="status != null "> and status = #{status}</if>
<if test="productId != null "> and product_id = #{productId}</if>
<if test="productName != null and productName != ''"> and product_name like concat('%', #{productName}, '%')</if>
<if test="deviceId != null "> and device_id = #{deviceId}</if>
<if test="deviceName != null and deviceName != ''"> and device_name like concat('%', #{deviceName}, '%')</if>
<if test="type != null "> and type = #{type}</if>
<if test="params.beginTime != null "> and create_time &gt;= #{params.beginTime}</if>
<if test="params.endTime != null "> and create_time &lt;= #{params.endTime}</if>
</where>
</select>
... ... @@ -52,39 +41,21 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
insert into iot_alert_log
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="alertName != null and alertName != ''">alert_name,</if>
<if test="alertId != null">alert_id,</if>
<if test="alertLevel != null">alert_level,</if>
<if test="status != null">status,</if>
<if test="productId != null">product_id,</if>
<if test="productName != null and productName != ''">product_name,</if>
<if test="deviceId != null">device_id,</if>
<if test="deviceName != null and deviceName != ''">device_name,</if>
<if test="createBy != null">create_by,</if>
<if test="createTime != null">create_time,</if>
<if test="updateBy != null">update_by,</if>
<if test="updateTime != null">update_time,</if>
<if test="remark != null">remark,</if>
<if test="userId != null">user_id,</if>
<if test="userName != null and userName != ''">user_name,</if>
<if test="tenantId != null">tenant_id,</if>
<if test="tenantName != null and tenantName != ''">tenant_name,</if>
<if test="create_time != null">create_time,</if>
<if test="type != null">`type`,</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="alertName != null and alertName != ''">#{alertName},</if>
<if test="alertId != null">#{alertId},</if>
<if test="alertLevel != null">#{alertLevel},</if>
<if test="status != null">#{status},</if>
<if test="productId != null">#{productId},</if>
<if test="productName != null and productName != ''">#{productName},</if>
<if test="deviceId != null">#{deviceId},</if>
<if test="deviceName != null and deviceName != ''">#{deviceName},</if>
<if test="createBy != null">#{createBy},</if>
<if test="createTime != null">#{createTime},</if>
<if test="updateBy != null">#{updateBy},</if>
<if test="updateTime != null">#{updateTime},</if>
<if test="remark != null">#{remark},</if>
<if test="userId != null">#{userId},</if>
<if test="userName != null and userName != ''">#{userName},</if>
<if test="tenantId != null">#{tenantId},</if>
<if test="tenantName != null and tenantName != ''">#{tenantName},</if>
<if test="create_time != null">#{createTime},</if>
<if test="type != null">#{type},</if>
</trim>
</insert>
... ... @@ -92,21 +63,12 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
update iot_alert_log
<trim prefix="SET" suffixOverrides=",">
<if test="alertName != null and alertName != ''">alert_name = #{alertName},</if>
<if test="alertId != null">alert_id = #{alertId},</if>
<if test="alertLevel != null">alert_level = #{alertLevel},</if>
<if test="status != null">status = #{status},</if>
<if test="productId != null">product_id = #{productId},</if>
<if test="productName != null and productName != ''">product_name = #{productName},</if>
<if test="deviceId != null">device_id = #{deviceId},</if>
<if test="deviceName != null and deviceName != ''">device_name = #{deviceName},</if>
<if test="createBy != null">create_by = #{createBy},</if>
<if test="createTime != null">create_time = #{createTime},</if>
<if test="updateBy != null">update_by = #{updateBy},</if>
<if test="updateTime != null">update_time = #{updateTime},</if>
<if test="remark != null">remark = #{remark},</if>
<if test="userId != null">user_id = #{userId},</if>
<if test="userName != null and userName != ''">user_name = #{userName},</if>
<if test="tenantId != null">tenant_id = #{tenantId},</if>
<if test="tenantName != null and tenantName != ''">tenant_name = #{tenantName},</if>
<if test="create_time != null">create_time = #{create_time},</if>
<if test="type != null">`type` = #{type},</if>
</trim>
where alert_log__id = #{alertLogId}
</update>
... ...
... ... @@ -8,6 +8,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<result property="alertId" column="alert_id" />
<result property="alertName" column="alert_name" />
<result property="alertLevel" column="alert_level" />
<result property="alertType" column="alert_type" />
<result property="status" column="status" />
<result property="productId" column="product_id" />
<result property="productName" column="product_name" />
... ... @@ -21,7 +22,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
</resultMap>
<sql id="selectAlertVo">
select alert_id, alert_name, alert_level,status, product_id, product_name, triggers, actions, create_by, create_time, update_by, update_time, remark from iot_alert
select alert_id, alert_name, alert_type,alert_level,status, product_id, product_name, triggers, actions, create_by, create_time, update_by, update_time, remark from iot_alert
</sql>
<select id="selectAlertList" parameterType="com.zhonglai.luhui.device.domain.IotAlert" resultMap="AlertResult">
... ... @@ -29,6 +30,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<where>
<if test="alertName != null and alertName != ''"> and alert_name like concat('%', #{alertName}, '%')</if>
<if test="alertLevel != null "> and alert_level = #{alertLevel}</if>
<if test="alertType != null "> and alert_type = #{alertType}</if>
<if test="status != null "> and status = #{status}</if>
<if test="productId != null "> and product_id = #{productId}</if>
<if test="productName != null and productName != ''"> and product_name like concat('%', #{productName}, '%')</if>
... ... @@ -45,6 +47,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="alertName != null and alertName != ''">alert_name,</if>
<if test="alertLevel != null">alert_level,</if>
<if test="alertType != null">alert_type,</if>
<if test="status != null">status,</if>
<if test="productId != null">product_id,</if>
<if test="productName != null and productName != ''">product_name,</if>
... ... @@ -59,6 +62,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="alertName != null and alertName != ''">#{alertName},</if>
<if test="alertLevel != null">#{alertLevel},</if>
<if test="alertType != null">#{alertType},</if>
<if test="status != null">#{status},</if>
<if test="productId != null">#{productId},</if>
<if test="productName != null and productName != ''">#{productName},</if>
... ... @@ -77,6 +81,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
<trim prefix="SET" suffixOverrides=",">
<if test="alertName != null and alertName != ''">alert_name = #{alertName},</if>
<if test="alertLevel != null">alert_level = #{alertLevel},</if>
<if test="alertType != null">alert_type = #{alertType},</if>
<if test="status != null">status = #{status},</if>
<if test="productId != null">product_id = #{productId},</if>
<if test="productName != null and productName != ''">product_name = #{productName},</if>
... ...
... ... @@ -8,15 +8,21 @@ import com.ruoyi.common.core.domain.MessageCode;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.exception.RequestTimeoutException;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
@Service
public class RocketMqService {
private final Logger log = LoggerFactory.getLogger(this.getClass());
@Value("${rocketmq.producer.send-topic}")
private String sendTopic; //客户端操作时间
@Value("${rocketmq.producer.send-tags}")
... ... @@ -56,4 +62,8 @@ public class RocketMqService {
return new Message(MessageCode.DEFAULT_FAIL_CODE);
}
public void syncSend(String topic, Object message)
{
rocketMQTemplate.syncSend(topic, MessageBuilder.withPayload(message).build(), 3000, 1);
}
}
... ...
... ... @@ -14,11 +14,11 @@ import org.springframework.context.annotation.ComponentScan;
"com.zhonglai.luhui.config",
"com.zhonglai.luhui.datasource",
"com.zhonglai.luhui.dao",
"com.zhonglai.luhui.security",
"com.zhonglai.luhui.sys",
"com.zhonglai.luhui.device",
"com.zhonglai.luhui.redis.configure",
"com.zhonglai.luhui.redis.service",
"com.zhonglai.luhui.security",
"com.zhonglai.luhui.rocketmq",
"com.zhonglai.luhui.firewall",
"com.zhonglai.luhui.admin",
... ...
... ... @@ -127,6 +127,47 @@ public class ControlDeviceConreoller extends BaseController {
return control(deviceCommand);
}
@ApiOperation("添加订阅")
@ApiImplicitParams({
@ApiImplicitParam(value = "监听服务器的ip",name = "ip"),
@ApiImplicitParam(value = "产品集合",name = "product_ids"),
})
@PreAuthorize("@ss.hasPermi('iot:controlDevice:addSubscribe')")
@Log(title = "添加订阅", businessType = BusinessType.CAHE)
@PostMapping("/addSubscribe")
public AjaxResult addSubscribe(String product_ids,String ip) {
DeviceCommand deviceCommand = new DeviceCommand();
deviceCommand.setCommandType(CommandType.addSubscribe);
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("product_ids",product_ids);
jsonObject.addProperty("ip",ip);
deviceCommand.setData(jsonObject);
return control(deviceCommand);
}
@ApiOperation(value = "通知",notes = "body参数描述:\r\n" +
"{\n" +
" \"1\":{\n" +
" \"id1\":\"value1\",\n" +
" \"id2\":\"value2\",\n" +
" \"id3\":\"value3\"\n" +
" }\n" +
"}")
@ApiImplicitParams({
@ApiImplicitParam(value = "网关id",name = "deviceId"),
})
@PreAuthorize("@ss.hasPermi('iot:controlDevice:notice')")
@Log(title = "通知", businessType = BusinessType.CAHE)
@PostMapping("/notice/{deviceId}")
public AjaxResult notice(@PathVariable String deviceId, HttpServletRequest request) throws IOException {
byte[] bodyBytes = StreamUtils.copyToByteArray(request.getInputStream());
String body = new String(bodyBytes, request.getCharacterEncoding());
DeviceCommand deviceCommand = new DeviceCommand();
deviceCommand.setDeviceId(deviceId);
deviceCommand.setCommandType(CommandType.notice);
deviceCommand.setData(GsonConstructor.get().fromJson(body,JsonObject.class));
return control(deviceCommand);
}
private AjaxResult control( DeviceCommand deviceCommand)
{
... ...
... ... @@ -7,8 +7,7 @@ import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.zhonglai.luhui.admin.dto.AlarmActionConfig;
import com.zhonglai.luhui.admin.dto.AlarmTriggersConfig;
import com.zhonglai.luhui.admin.dto.*;
import com.zhonglai.luhui.action.BaseController;
import com.zhonglai.luhui.device.domain.IotAlert;
import com.zhonglai.luhui.device.service.IIotAlertService;
... ... @@ -20,7 +19,9 @@ import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
/**
... ... @@ -88,10 +89,10 @@ public class IotAlertController extends BaseController
{
return AjaxResult.error("触发器参数必填");
}
if (checkActions(alert))
{
return AjaxResult.error("执行动作参数必填");
}
// if (checkActions(alert))
// {
// return AjaxResult.error("执行动作参数必填");
// }
return toAjax(alertService.insertAlert(alert));
}
... ... @@ -108,10 +109,10 @@ public class IotAlertController extends BaseController
{
return AjaxResult.error("触发器参数必填");
}
if (checkActions(alert))
{
return AjaxResult.error("执行动作参数必填");
}
// if (checkActions(alert))
// {
// return AjaxResult.error("执行动作参数必填");
// }
return toAjax(alertService.updateAlert(alert));
}
... ... @@ -136,12 +137,35 @@ public class IotAlertController extends BaseController
String triggers = Optional.ofNullable(alert).orElse(new IotAlert()).getTriggers();
if(StringUtils.isNotEmpty(triggers))
{
AlarmTriggersConfig alarmTriggersConfig = JSONObject.parseObject(triggers, AlarmTriggersConfig.class);
return BeanUtil.hasNullField(alarmTriggersConfig,"cron");
switch (alert.getAlertType())
{
case 1:
AttributeTriggers attributeTriggers = JSONObject.parseObject(triggers, AttributeTriggers.class);
return BeanUtil.hasNullField(attributeTriggers);
case 2:
TriggerTriggers triggerTriggers = JSONObject.parseObject(triggers, TriggerTriggers.class);
return BeanUtil.hasNullField(triggerTriggers);
case 3:
TimerTriggers timerTriggers = JSONObject.parseObject(triggers, TimerTriggers.class);
return BeanUtil.hasNullField(timerTriggers,"terminalids");
}
}
return false;
}
public static void main(String[] args) {
String triggers = "{\"model_name\":\"alarm\",\"valueMapName\":{{\"1\":\"传感器检测失败故障\"},{\"3\",\"超低氧告警\"}}}";
AttributeTriggers attributeTriggers = new AttributeTriggers();
attributeTriggers.setModel_name("alarm");
Map<Object,String> valueMapName = new HashMap<>();
valueMapName.put("1","传感器检测失败故障");
valueMapName.put("3","超低氧告警");
attributeTriggers.setValueMapName(valueMapName);
System.out.println(triggers);
System.out.println(JSONObject.toJSON(attributeTriggers));
}
/**
* 检验执行动作
* @return
... ...
package com.zhonglai.luhui.admin.dto;
import java.util.Map;
/**
* 属性警触发配置
*/
public class AttributeTriggers {
private String model_name;
private Map<Object,String> valueMapName;
public String getModel_name() {
return model_name;
}
public void setModel_name(String model_name) {
this.model_name = model_name;
}
public Map<Object, String> getValueMapName() {
return valueMapName;
}
public void setValueMapName(Map<Object, String> valueMapName) {
this.valueMapName = valueMapName;
}
}
... ...
package com.zhonglai.luhui.admin.dto;
import java.util.List;
/**
* 定时告警触发配置
*/
public class TimerTriggers {
/**
* cron表达式
*/
private String cron;
/**
* 终端id集合,用英文逗号分割(可以为空)
*/
private String terminalids;
/**
* 触发条件
*/
private List<TriggerTriggers> triggersList;
public String getCron() {
return cron;
}
public void setCron(String cron) {
this.cron = cron;
}
public List<TriggerTriggers> getTriggersList() {
return triggersList;
}
public void setTriggersList(List<TriggerTriggers> triggersList) {
this.triggersList = triggersList;
}
public String getTerminalids() {
return terminalids;
}
public void setTerminalids(String terminalids) {
this.terminalids = terminalids;
}
}
... ...
package com.zhonglai.luhui.admin.dto;
/**
* 触发告警触发配置
*/
public class TriggerTriggers {
private String model_name; //要过滤的模型
private String equation; //等式
private Integer type; // 比较类型(1直接比较值,2和另一个读数模型比较,3和另一个参数模型比较)
private Object compare_object; //被比较的对象
private boolean isor; //与或条件
public boolean isIsor() {
return isor;
}
public void setIsor(boolean isor) {
this.isor = isor;
}
public String getModel_name() {
return model_name;
}
public void setModel_name(String model_name) {
this.model_name = model_name;
}
public String getEquation() {
return equation;
}
public void setEquation(String equation) {
this.equation = equation;
}
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
public Object getCompare_object() {
return compare_object;
}
public void setCompare_object(Object compare_object) {
this.compare_object = compare_object;
}
}
... ...
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.zhonglai.luhui</groupId>
<artifactId>lh-modules</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>lh-alarm-timer</artifactId>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>
\ No newline at end of file
... ...
... ... @@ -12,57 +12,31 @@
<artifactId>lh-alarm</artifactId>
<dependencies>
<!-- spring-boot-devtools -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional> <!-- 表示依赖不会传递 -->
</dependency>
<dependency>
<groupId>com.zendesk</groupId>
<artifactId>mysql-binlog-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</dependency>
<!-- Mysql驱动包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- 核心模块-->
<dependency>
<groupId>com.zhonglai.luhui</groupId>
<artifactId>ruoyi-framework</artifactId>
</dependency>
<!-- 文档 -->
<dependency >
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${swagger.version}</version>
<exclusions>
<exclusion>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
</exclusion>
<exclusion>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--https://mvnrepository.com/artifact/io.swagger/swagger-models-->
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
<version>${swagger-models.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger.version}</version>
</dependency>
<!--&lt;!&ndash; https://mvnrepository.com/artifact/com.github.xiaoymin/swagger-bootstrap-ui &ndash;&gt;-->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>swagger-bootstrap-ui</artifactId>
<version>${swagger-ui.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba.otter</groupId>
<artifactId>canal.client</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.otter</groupId>
<artifactId>canal.protocol</artifactId>
</dependency>
<dependency>
<groupId>com.zhonglai.luhui</groupId>
<artifactId>lh-service-dao</artifactId>
</dependency>
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
</dependency>
</dependencies>
<build>
... ...
package com.zhonglai.luhui.alarm;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.FilterType;
@ComponentScan(basePackages = {
"com.ruoyi.common",
"com.ruoyi.framework",
}
// excludeFilters = {@ComponentScan.Filter(type= FilterType.ASSIGNABLE_TYPE,classes = {LogAspect.class,
// RateLimiterAspect.class, LoginService.class, TokenService.class, FilterConfig.class, JwtAuthenticationTokenFilter.class,
// SysConfigServiceImpl.class, SysDictTypeServiceImpl.class, SysUserServiceImpl.class,SecurityConfig.class, LogoutSuccessHandlerImpl.class
// })}
)
@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class })
public class AlarmApplication {
public static void main(String[] args) {
SpringApplication.run(AlarmApplication.class,args);
System.out.println("启动成功");
}
}
package com.zhonglai.luhui.alarm;
import com.zhonglai.luhui.alarm.config.CachAlarmConfig;
import com.zhonglai.luhui.alarm.handle.CleanupTask;
import com.zhonglai.luhui.alarm.service.TimerAlarmService;
import com.zhonglai.luhui.alarm.service.TriggerAlarmService;
public class LhAlarmMain {
public static void main(String[] args) {
// 注册Shutdown Hook
Runtime.getRuntime().addShutdownHook(new CleanupTask());
CachAlarmConfig.loadConfig();
//启动触发告警服务
TriggerAlarmService.start();
//启动定时任务告警
TimerAlarmService.start();
}
}
... ...
package com.zhonglai.luhui.alarm.clas;
import com.zhonglai.luhui.alarm.config.CachAlarmConfig;
import com.zhonglai.luhui.alarm.dto.IotAlert;
import com.zhonglai.luhui.alarm.service.TimerAlarmService;
import java.io.Serializable;
public class IotAlertAlarm extends UpAlarmFactory<IotAlert> implements Serializable {
public IotAlertAlarm(IotAlert beforeupAlarmDb, IotAlert afterupAlarmDb) {
super(beforeupAlarmDb, afterupAlarmDb);
}
@Override
void deleteGenerateAlarm() {
CachAlarmConfig.delete(beforeupAlarmDb.getAlertId());
}
@Override
void insertGenerateAlarm() {
switch (afterupAlarmDb.getAlertType())
{
case 1:
CachAlarmConfig.addAttributeAlarmRoute(afterupAlarmDb);
break;
case 2:
CachAlarmConfig.addTriggerAlarmRoute(afterupAlarmDb);
break;
case 3:
TimerAlarmService.addTimerAlarm(afterupAlarmDb);
break;
}
}
@Override
void updateGenerateAlarm() {
switch (afterupAlarmDb.getAlertType())
{
case 1:
CachAlarmConfig.addAttributeAlarmRoute(afterupAlarmDb);
break;
case 2:
CachAlarmConfig.addTriggerAlarmRoute(afterupAlarmDb);
break;
case 3:
if (null != afterupAlarmDb.getStatus() && 2==afterupAlarmDb.getStatus())
{
deleteGenerateAlarm();
}else {
TimerAlarmService.addTimerAlarm(afterupAlarmDb);
}
break;
}
}
@Override
Object getNowValue(Object model_name, Integer type) {
return null;
}
}
... ...
package com.zhonglai.luhui.alarm.clas;
import com.alibaba.fastjson.JSONObject;
import com.zhonglai.luhui.alarm.config.CachAlarmConfig;
import com.zhonglai.luhui.alarm.dto.*;
import com.zhonglai.luhui.service.dao.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.Serializable;
/**
* 主机/网关对象 iot_device
*
* @author 钟来
* @date 2022-08-26
*/
public class IotDeviceAlarm extends UpAlarmFactory<IotDevice> implements Serializable
{
private final Logger logger = LoggerFactory.getLogger(this.getClass());
public IotDeviceAlarm(IotDevice beforeupAlarmDb, IotDevice afterupAlarmDb) {
super(beforeupAlarmDb,afterupAlarmDb);
}
@Override
public void deleteGenerateAlarm() {
logger.info("主机{}删除不需要告警",beforeupAlarmDb.getClient_id());
}
@Override
public void insertGenerateAlarm() {
logger.info("主机{}添加不需要告警",afterupAlarmDb.getClient_id());
}
@Override
public void updateGenerateAlarm() {
//如果是产品变更先更新产品
if (null != afterupAlarmDb.getProduct_id() && (beforeupAlarmDb.getProduct_id()-afterupAlarmDb.getProduct_id()) !=0)
{
CachAlarmConfig.putDeviceProduct(afterupAlarmDb.getClient_id(), afterupAlarmDb.getProduct_id());
}
//通过变更的数据获得对应的告警规则
valueUp(beforeupAlarmDb.getClient_id(),CachAlarmConfig.getDeviceProduct(beforeupAlarmDb.getClient_id()),beforeupAlarmDb.getThings_model_value(),afterupAlarmDb.getThings_model_value());
}
Object getNowValue(Object model_name,Integer type) {
if(null != afterupAlarmDb )
{
if(StringUtils.isNotEmpty(afterupAlarmDb.getThings_model_value()))
{
return getValueFromJSON(model_name+"",JSONObject.parseObject(afterupAlarmDb.getThings_model_value()));
}
}
return null;
}
}
... ...
package com.zhonglai.luhui.alarm.clas;
import com.alibaba.fastjson.JSONObject;
import com.zhonglai.luhui.alarm.config.CachAlarmConfig;
import com.zhonglai.luhui.alarm.dto.IotDevice;
import com.zhonglai.luhui.alarm.dto.IotTerminal;
import com.zhonglai.luhui.service.dao.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.Serializable;
/**
* 终端对象 iot_terminal
*
* @author 钟来
* @date 2022-08-26
*/
public class IotTerminalAlarm extends UpAlarmFactory<IotTerminal> implements Serializable
{
private final Logger logger = LoggerFactory.getLogger(this.getClass());
public IotTerminalAlarm(IotTerminal beforeupAlarmDb, IotTerminal afterupAlarmDb) {
super(beforeupAlarmDb,afterupAlarmDb);
}
@Override
public void deleteGenerateAlarm() {
logger.info("终端{}删除不需要告警",beforeupAlarmDb.getId());
}
@Override
public void insertGenerateAlarm() {
logger.info("终端{}添加不需要告警",afterupAlarmDb.getId());
}
@Override
public void updateGenerateAlarm() {
//通过变更的数据获得对应的告警规则
valueUp(beforeupAlarmDb.getId(), CachAlarmConfig.getDeviceProduct(beforeupAlarmDb.getId()),beforeupAlarmDb.getThings_model_value(),afterupAlarmDb.getThings_model_value());
}
@Override
Object getNowValue(Object model_name,Integer type) {
Object value = null;
if(null != afterupAlarmDb )
{
switch (type)
{
case 2:
if(StringUtils.isNotEmpty(afterupAlarmDb.getThings_model_value()))
{
value = getValueFromJSON(model_name+"", JSONObject.parseObject(afterupAlarmDb.getThings_model_value()));
}
break;
case 3:
if(StringUtils.isNotEmpty(afterupAlarmDb.getThings_model_config()))
{
value = getValueFromJSON(model_name+"", JSONObject.parseObject(afterupAlarmDb.getThings_model_config()));
}
break;
}
}
return value;
}
}
... ...
package com.zhonglai.luhui.alarm.clas;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.otter.canal.protocol.CanalEntry;
import com.zhonglai.luhui.alarm.config.CachAlarmConfig;
import com.zhonglai.luhui.alarm.dto.*;
import com.zhonglai.luhui.alarm.util.GenericComparator;
import com.zhonglai.luhui.service.dao.util.StringUtils;
import java.util.ArrayList;
import java.util.List;
/**
* 告警工厂
*/
public abstract class UpAlarmFactory<T> {
protected List<IotAlertLog> list = new ArrayList<>();
protected T beforeupAlarmDb;
protected T afterupAlarmDb;
abstract void deleteGenerateAlarm();
abstract void insertGenerateAlarm();
abstract void updateGenerateAlarm();
abstract Object getNowValue(Object model_name,Integer type);
public UpAlarmFactory(T beforeupAlarmDb, T afterupAlarmDb)
{
this.beforeupAlarmDb = beforeupAlarmDb;
this.afterupAlarmDb = afterupAlarmDb;
}
public static UpAlarmFactory instantiate(List<CanalEntry.Column> beforecolumns, List<CanalEntry.Column> aftercolumns, String dbName, String tableName)
{
switch (dbName+"."+tableName)
{
case "mqtt_broker.iot_device":
return new IotDeviceAlarm(IotDevice.instantiate(beforecolumns),IotDevice.instantiate(aftercolumns));
case "mqtt_broker.iot_terminal":
return new IotTerminalAlarm(IotTerminal.instantiate(beforecolumns),IotTerminal.instantiate(aftercolumns));
case "mqtt_broker.iot_alert":
return new IotAlertAlarm(IotAlert.instantiate(beforecolumns),IotAlert.instantiate(aftercolumns));
}
return null;
}
public void alarm(CanalEntry.EventType eventType)
{
switch (eventType)
{
case DELETE:
if(null != beforeupAlarmDb)
{
deleteGenerateAlarm();
}
break;
case INSERT:
if(null != afterupAlarmDb)
{
insertGenerateAlarm();
}
break;
default:
updateGenerateAlarm();
break;
}
}
protected void valueUp(String client_id,Integer product_id,String oldvalue,String newValue)
{
if(StringUtils.isNotEmpty(newValue))
{
JSONObject oldjson = null==oldvalue?new JSONObject():JSONObject.parseObject(oldvalue);
JSONObject newjson = JSONObject.parseObject(newValue);
if(null == product_id)
{
product_id = CachAlarmConfig.getDeviceProduct(client_id);
}
for (String key:newjson.keySet())
{
if(!newjson.get(key).equals(oldjson.get(key))) //新老不一致,触发告警
{
//属性告警
List<IotAlert> listAttribute = CachAlarmConfig.getAttributeIotAlert(product_id,key);
if (null != listAttribute && listAttribute.size() != 0)
{
alarmAttribute(client_id,listAttribute,oldjson.get(key));
}
//触发告警
List<IotAlert> listTrigger = CachAlarmConfig.getTriggerIotAlert(product_id,key);
if (null != listTrigger && listTrigger.size() != 0)
{
alarmTrigger(client_id,listTrigger,oldjson.get(key));
}
}
}
}
}
protected void alarmAttribute(String client_id,List<IotAlert> listAttribute,Object newValue)
{
for (IotAlert iotAlert:listAttribute)
{
AttributeTriggers attributeTriggers = JSONObject.parseObject(iotAlert.getTriggers(),AttributeTriggers.class);
String alrmname = attributeTriggers.getValueMapName().get(newValue);
if(StringUtils.isNotEmpty(alrmname))
{
IotAlertLog iotAlertLog = new IotAlertLog(iotAlert.getAlertId(),alrmname,iotAlert.getAlertLevel().intValue(),2,client_id,System.currentTimeMillis(),1,iotAlert.getCreateBy());
list.add(iotAlertLog);
}
}
}
protected void alarmTrigger(String client_id,List<IotAlert> listAttribute,Object newValue)
{
for (IotAlert iotAlert:listAttribute)
{
List<TriggerTriggers> attributeTriggersList = JSON.parseArray(iotAlert.getTriggers(),TriggerTriggers.class);
alarmTriggerTriggers(attributeTriggersList,newValue,iotAlert.getAlertId(),iotAlert.getAlertName(),iotAlert.getAlertLevel().intValue(),client_id,iotAlert.getCreateBy());
}
}
public void alarmTriggerTriggers( List<TriggerTriggers> attributeTriggersList,Object newValue,Long alert_id, String alert_name, Integer alert_level, String device_id,String userId)
{
if(null != attributeTriggersList && attributeTriggersList.size() != 0)
{
//所有条件都是与
boolean jieguo = true;
for (TriggerTriggers triggerTriggers:attributeTriggersList)
{
Object value = triggerTriggers.getCompare_object();
switch (triggerTriggers.getType())
{
case 1:
value = triggerTriggers.getCompare_object();
break;
case 2:
value = getNowValue(triggerTriggers.getCompare_object(),2);
break;
case 3:
value = getNowValue(triggerTriggers.getCompare_object(),3);
break;
}
if (triggerTriggers.isIsor())
{
jieguo = jieguo || GenericComparator.compare(newValue,value,triggerTriggers.getEquation());
}else {
jieguo = jieguo && GenericComparator.compare(newValue,value,triggerTriggers.getEquation());
}
}
if(jieguo)
{
IotAlertLog iotAlertLog = new IotAlertLog(alert_id,alert_name,alert_level,2,device_id,System.currentTimeMillis(),1,userId);
list.add(iotAlertLog);
}
}
}
protected Object getValueFromJSON(String key,JSONObject jsonObject)
{
if(null != jsonObject && jsonObject.containsKey(jsonObject))
{
return jsonObject.getJSONObject(key).get("value");
}
return null;
}
public List<IotAlertLog> getList() {
return list;
}
}
... ...
package com.zhonglai.luhui.alarm.config;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zhonglai.luhui.alarm.dao.DbOperateUtil;
import com.zhonglai.luhui.alarm.dto.AttributeTriggers;
import com.zhonglai.luhui.alarm.dto.IotAlert;
import com.zhonglai.luhui.alarm.dto.TimerTriggers;
import com.zhonglai.luhui.alarm.dto.TriggerTriggers;
import com.zhonglai.luhui.alarm.handle.TimerAlarmJob;
import com.zhonglai.luhui.alarm.service.TimerAlarmService;
import com.zhonglai.luhui.service.dao.util.StringUtils;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 缓存的告警配置
*/
public class CachAlarmConfig {
private static final Logger logger = LoggerFactory.getLogger(CachAlarmConfig.class);
/** 属性告警路由 */
private static Map<Integer, Map<String, String>> product_attribute_route = new HashMap<>();
/** 触发告警路由 */
private static Map<Integer, Map<String, String>> product_trigger_route = new HashMap<>();
/** 告警配置 */
private static Map<Long, IotAlert> alarmConfig = new HashMap<>();
/** 告警配置 */
private static Map<String, Integer> device_product = new HashMap<>();
public static void loadConfig()
{
//加载属性告警配置
loadAttributeAlarmConfig();
//加载触发告警配置
loadTriggerAlarmConfig();
//加载定时任务
loadTimerAlarmConfig();
//加载用户告警配置
loadUserAlarmConfig();
}
/**
* 加载属性告警配置
*/
private static void loadAttributeAlarmConfig()
{
List<IotAlert> list = DbOperateUtil.getIotAlertList(1);
if(null != list && list.size() != 0)
{
for (IotAlert iotAlert:list)
{
addAttributeAlarmRoute(iotAlert);
}
}
}
/**
* 加载触发告警配置
*/
private static void loadTriggerAlarmConfig()
{
List<IotAlert> list = DbOperateUtil.getIotAlertList(2);
if(null != list && list.size() != 0)
{
for (IotAlert iotAlert:list)
{
addTriggerAlarmRoute(iotAlert);
}
}
}
/**
* 加载定时任务
*/
private static void loadTimerAlarmConfig()
{
List<IotAlert> list = DbOperateUtil.getIotAlertList(3);
if(null != list && list.size() != 0)
{
for (IotAlert iotAlert:list)
{
TimerAlarmService.addTimerAlarm(iotAlert);
}
}
}
/**
* 加载用户告警配置
*/
private static void loadUserAlarmConfig()
{
List<IotAlert> list = DbOperateUtil.getUserIotAlertList(1);
if(null != list && list.size() != 0)
{
for (IotAlert iotAlert:list)
{
addAttributeAlarmRoute(iotAlert);
}
}
list = DbOperateUtil.getUserIotAlertList(2);
if(null != list && list.size() != 0)
{
for (IotAlert iotAlert:list)
{
addTriggerAlarmRoute(iotAlert);
}
}
list = DbOperateUtil.getUserIotAlertList(3);
if(null != list && list.size() != 0)
{
for (IotAlert iotAlert:list)
{
TimerAlarmService.addTimerAlarm(iotAlert);
}
}
}
/**
* 添加属性告警路由
* @param iotAlert
*/
public static void addAttributeAlarmRoute(IotAlert iotAlert)
{
Map<String, String> iotAlertMap = product_attribute_route.get(iotAlert.getProductId());
if(null == iotAlertMap)
{
iotAlertMap = new HashMap<>();
product_attribute_route.put(iotAlert.getProductId().intValue(),iotAlertMap);
}
String triggers = iotAlert.getTriggers();
if(StringUtils.isNotEmpty(triggers))
{
AttributeTriggers attributeTriggers = JSONObject.parseObject(triggers,AttributeTriggers.class);
//添加路由
putroute(iotAlertMap,attributeTriggers.getModel_name(),iotAlert.getAlertId());
//添加告警配置
putIotAlert(iotAlert);
}
}
/**
* 添加触发告警路由
* @param iotAlert
*/
public static void addTriggerAlarmRoute(IotAlert iotAlert)
{
Map<String, String> iotAlertMap = product_trigger_route.get(iotAlert.getProductId());
if(null == iotAlertMap)
{
iotAlertMap = new HashMap<>();
product_trigger_route.put(iotAlert.getProductId().intValue(),iotAlertMap);
}
String triggers = iotAlert.getTriggers();
if(StringUtils.isNotEmpty(triggers))
{
List<TriggerTriggers> attributeTriggersList = JSON.parseArray(triggers,TriggerTriggers.class);
if(null != attributeTriggersList && attributeTriggersList.size() !=0 )
{
for (TriggerTriggers triggerTriggers:attributeTriggersList)
{
//添加路由
putroute(iotAlertMap,triggerTriggers.getModel_name(),iotAlert.getAlertId());
if(triggerTriggers.getType()==2)
{
putroute(iotAlertMap,triggerTriggers.getCompare_object()+"",iotAlert.getAlertId());
}
//添加告警配置
putIotAlert(iotAlert);
}
}
}
}
private static void putroute(Map<String, String> iotAlertMap,String model_name,Long alertid)
{
String route = iotAlertMap.get(model_name);
if(null == route)
{
route = "|";
}
if (route.indexOf("|"+alertid+"|")<0) //如果关系不存在,就加上
{
route+=alertid+"|";
iotAlertMap.put(model_name,route);
}
}
/**
* 获取属性告警配置
* @param product_id
* @param modelKey
* @return
*/
public static List<IotAlert> getAttributeIotAlert(Integer product_id,String modelKey)
{
if(product_attribute_route.containsKey(product_id) && product_attribute_route.get(product_id).containsKey(modelKey))
{
String idsStr = product_attribute_route.get(product_id).get(modelKey);
if(StringUtils.isNotEmpty(idsStr))
{
idsStr = idsStr.substring(1,idsStr.length()-1);
String[] ids = idsStr.split("\\|");
List<IotAlert> list = new ArrayList<>();
for (String id:ids)
{
IotAlert iotAlert = alarmConfig.get(Long.parseLong(id));
list.add(iotAlert);
}
return list;
}
}
return null;
}
/**
* 获取触发告警配置
* @param product_id
* @param modelKey
* @return
*/
public static List<IotAlert> getTriggerIotAlert(Integer product_id,String modelKey)
{
if(product_trigger_route.containsKey(product_id) && product_trigger_route.get(product_id).containsKey(modelKey))
{
String idsStr = product_trigger_route.get(product_id).get(modelKey);
if(StringUtils.isNotEmpty(idsStr))
{
idsStr = idsStr.substring(1,idsStr.length()-1);
String[] ids = idsStr.split("\\|");
List<IotAlert> list = new ArrayList<>();
for (String id:ids)
{
IotAlert iotAlert = alarmConfig.get(Long.parseLong(id));
list.add(iotAlert);
}
return list;
}
}
return null;
}
public static Integer getDeviceProduct(String id)
{
String deviceId = id.split("_")[0];
Integer productId = device_product.get(deviceId);
if(null == productId)
{
try {
productId = DbOperateUtil.getProductId(deviceId);
if (null != productId)
{
device_product.put(deviceId,productId);
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
return productId;
}
public static void putDeviceProduct(String deviceId,Integer product_id)
{
device_product.put(deviceId,product_id);
}
public static void delete(Long id)
{
IotAlert iotAlert = alarmConfig.get(id);
if(null != iotAlert)
{
alarmConfig.remove(id);
switch (iotAlert.getAlertType())
{
case 1:
product_attribute_route.remove(iotAlert.getProductId());
break;
case 2:
product_trigger_route.remove(iotAlert.getProductId());
break;
case 3:
TimerAlarmService.removeTimerAlarm(iotAlert.getAlertId(),iotAlert.getProductId());
break;
}
}
}
public static void putIotAlert(IotAlert iotAlert)
{
alarmConfig.put(iotAlert.getAlertId(),iotAlert);
}
}
... ...
package com.zhonglai.luhui.alarm.dao;
import com.zhonglai.luhui.alarm.dto.IotAlert;
import com.zhonglai.luhui.alarm.dto.IotAlertLog;
import com.zhonglai.luhui.alarm.dto.IotTerminal;
import com.zhonglai.luhui.service.dao.BaseDao;
import com.zhonglai.luhui.service.dao.util.StringUtils;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import java.sql.SQLException;
import java.util.List;
public class DbOperateUtil {
private static BaseDao baseDao = new BaseDao();
public static List<IotAlert> getIotAlertList(Integer alertType)
{
IotAlert iotAlert = new IotAlert();
iotAlert.setStatus(1);
iotAlert.setAlertType(alertType);
List<IotAlert> list = baseDao.find(iotAlert);
return list;
}
public static List<IotAlert> getUserIotAlertList(Integer alertType)
{
return baseDao.findBysql("SELECT * FROM `iot_alert_user` WHERE `status`=1 AND alert_type=?",IotAlert.class,alertType);
}
public static Integer getProductId(String client_id) throws SQLException {
return baseDao.query().query("SELECT product_id FROM `iot_device` WHERE client_id=?",new ScalarHandler<Integer>(),client_id);
}
public static int insertIotAlertLogList(List<IotAlertLog> list)
{
return baseDao.insertList(list,null);
}
public static List<IotTerminal> getTimerAlarmIotTerminal(Long productId,String terminalids)
{
if(StringUtils.isNotEmpty(terminalids))
{
return baseDao.findBysql("SELECT * FROM `iot_terminal` WHERE product_id=? AND id IN(?)",IotTerminal.class,productId,terminalids.split(","));
}
return baseDao.findBysql("SELECT * FROM `iot_terminal` WHERE product_id=?",IotTerminal.class,productId);
}
public static List<IotAlertLog> getIotAlertLogList(Integer status,Integer limit)
{
List<IotAlertLog> list = baseDao.findBysql("select * from iot_alert_log where `status`=? limit ?",IotAlertLog.class,status,limit);
return list;
}
public static int updateIotAlertLogStatus(List<Long> ids,Integer status)
{
return baseDao.updateBySql("update iot_alert_log set `status`=? where id in(?)",status,ids);
}
}
... ...
package com.zhonglai.luhui.alarm.dto;
import java.util.Map;
/**
* 属性警触发配置
*/
public class AttributeTriggers {
private String model_name;
private Map<Object,String> valueMapName;
public String getModel_name() {
return model_name;
}
public void setModel_name(String model_name) {
this.model_name = model_name;
}
public Map<Object, String> getValueMapName() {
return valueMapName;
}
public void setValueMapName(Map<Object, String> valueMapName) {
this.valueMapName = valueMapName;
}
}
... ...
package com.zhonglai.luhui.alarm.dto;
import com.alibaba.otter.canal.protocol.CanalEntry;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
public class IotAlert {
/** 告警ID */
private Long alertId;
/** 告警名称 */
private String alertName;
/** 告警级别(1=提醒通知,2=轻微问题,3=严重警告) */
private Long alertLevel;
/** 告警类型(1属性告警,2触发告警,3定时告警) */
private Integer alertType;
/** 产品ID */
private Long productId;
/** 产品名称 */
private String productName;
/** 触发器 */
private String triggers;
/** 执行动作 */
private String actions;
/** 告警状态 (1-启动,2-停止)**/
private Integer status;
private String createBy;
public String getCreateBy() {
return createBy;
}
public void setCreateBy(String createBy) {
this.createBy = createBy;
}
public Long getAlertId() {
return alertId;
}
public void setAlertId(Long alertId) {
this.alertId = alertId;
}
public String getAlertName() {
return alertName;
}
public void setAlertName(String alertName) {
this.alertName = alertName;
}
public Long getAlertLevel() {
return alertLevel;
}
public void setAlertLevel(Long alertLevel) {
this.alertLevel = alertLevel;
}
public Integer getAlertType() {
return alertType;
}
public void setAlertType(Integer alertType) {
this.alertType = alertType;
}
public Long getProductId() {
return productId;
}
public void setProductId(Long productId) {
this.productId = productId;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getTriggers() {
return triggers;
}
public void setTriggers(String triggers) {
this.triggers = triggers;
}
public String getActions() {
return actions;
}
public void setActions(String actions) {
this.actions = actions;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public static IotAlert instantiate(List<CanalEntry.Column> columns) {
if (null == columns || columns.size() ==0)
{
return null;
}
IotAlert iotAlert = new IotAlert();
for (CanalEntry.Column column : columns)
{
try {
Method method = iotAlert.getClass().getMethod("set"+getName(column.getName()));
method.invoke(iotAlert, column.getValue());
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
}
}
if(null == iotAlert.getAlertId())
{
return null;
}
return iotAlert;
}
/**
* [简要描述]:首字母大写
*
* @author com.zhonglai
* @param str
* @return
*/
public static String getName(String str) {
char ch = str.toCharArray()[0];
ch = (char) ((ch - 97) + 'A');
str = ch + str.substring(1);
return str;
}
}
... ...
package com.zhonglai.luhui.alarm.dto;
import com.zhonglai.luhui.service.dao.util.StringUtils;
/**
* 设备告警对象 iot_alert_log
*
* @author kerwincui
* @date 2022-01-13
*/
public class IotAlertLog
{
private Long alert_log_id; // bigint NOT NULL AUTO_INCREMENT COMMENT '主键',
private Long alert_id; // bigint DEFAULT NULL COMMENT '告警ID',
private String alert_name; // varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '告警名称',
private Integer alert_level; // int NOT NULL COMMENT '告警级别(1=轻微问题,2=提醒通知,3=严重警告)',
private Integer status; // int NOT NULL COMMENT '处理状态(1=不需要处理,2=未处理,3=已处理)',
private String device_id; // varchar(150) COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '设备ID',
private Long create_time; // datetime DEFAULT NULL COMMENT '创建时间',
private Integer type; // tinyint DEFAULT NULL COMMENT '类型(1=告警,2=场景联动)',
private Integer user_id; //关联的用户id(0为系统生成)
public IotAlertLog() {
}
public IotAlertLog(Long alert_id, String alert_name, Integer alert_level, Integer status, String device_id, Long create_time, Integer type,String user_id) {
this.alert_id = alert_id;
this.alert_name = alert_name;
this.alert_level = alert_level;
this.status = status;
this.device_id = device_id;
this.create_time = create_time;
this.type = type;
if(StringUtils.isNotEmpty(user_id))
{
this.user_id = Integer.parseInt(user_id);
}
}
public Integer getUser_id() {
return user_id;
}
public void setUser_id(Integer user_id) {
this.user_id = user_id;
}
public Long getAlert_log_id() {
return alert_log_id;
}
public void setAlert_log_id(Long alert_log_id) {
this.alert_log_id = alert_log_id;
}
public Long getAlert_id() {
return alert_id;
}
public void setAlert_id(Long alert_id) {
this.alert_id = alert_id;
}
public String getAlert_name() {
return alert_name;
}
public void setAlert_name(String alert_name) {
this.alert_name = alert_name;
}
public Integer getAlert_level() {
return alert_level;
}
public void setAlert_level(Integer alert_level) {
this.alert_level = alert_level;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getDevice_id() {
return device_id;
}
public void setDevice_id(String device_id) {
this.device_id = device_id;
}
public Long getCreate_time() {
return create_time;
}
public void setCreate_time(Long create_time) {
this.create_time = create_time;
}
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
}
... ...
package com.zhonglai.luhui.alarm.dto;
import com.alibaba.otter.canal.protocol.CanalEntry;
import com.zhonglai.luhui.alarm.clas.UpAlarmFactory;
import java.util.List;
public class IotDevice {
/** 主键 */
private String client_id;
/** 设备摘要,格式[{"name":"device"},{"chip":"esp8266"}] */
private String summary;
/** 物模型值 */
private String things_model_value;
private Integer product_id;
public Integer getProduct_id() {
return product_id;
}
public void setProduct_id(Integer product_id) {
this.product_id = product_id;
}
public String getClient_id() {
return client_id;
}
public void setClient_id(String client_id) {
this.client_id = client_id;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
public String getThings_model_value() {
return things_model_value;
}
public void setThings_model_value(String things_model_value) {
this.things_model_value = things_model_value;
}
public static IotDevice instantiate(List<CanalEntry.Column> columns) {
if (null == columns || columns.size() ==0)
{
return null;
}
IotDevice iotDevice = new IotDevice();
for (CanalEntry.Column column : columns)
{
switch (column.getName())
{
case "client_id":
iotDevice.setClient_id(column.getValue());
break;
case "summary":
iotDevice.setSummary( column.getValue());
break;
case "things_model_value":
iotDevice.setThings_model_value ( column.getValue());
break;
case "product_id":
iotDevice.setProduct_id ( null!=column.getValue()&&!"".equals(column.getValue())?Integer.parseInt(column.getValue()):null);
break;
}
}
if(null == iotDevice.getSummary() || null == iotDevice.getThings_model_value() || null == iotDevice.getClient_id())
{
return null;
}
return iotDevice;
}
}
... ...