增加监控接口,调整Maven依赖

This commit is contained in:
zy 2025-11-18 18:15:17 +08:00
parent 0f18d0f33d
commit 90eefb2977
22 changed files with 501 additions and 64 deletions

View File

@ -44,6 +44,16 @@
<dependency> <dependency>
<groupId>org.jeecgframework.boot</groupId> <groupId>org.jeecgframework.boot</groupId>
<artifactId>jeecg-boot-common</artifactId> <artifactId>jeecg-boot-common</artifactId>
<exclusions>
<exclusion>
<groupId>cn.hutool</groupId>
<artifactId>hutool-core</artifactId>
</exclusion>
<exclusion>
<groupId>cn.hutool</groupId>
<artifactId>hutool-crypto</artifactId>
</exclusion>
</exclusions>
</dependency> </dependency>
<!--集成springmvc框架并实现自动配置 --> <!--集成springmvc框架并实现自动配置 -->
<dependency> <dependency>
@ -258,6 +268,12 @@
<artifactId>easy-captcha</artifactId> <artifactId>easy-captcha</artifactId>
<version>1.6.2</version> <version>1.6.2</version>
</dependency> </dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>${hutool.version}</version>
</dependency>
</dependencies> </dependencies>
</project> </project>

View File

@ -19,6 +19,16 @@
<dependency> <dependency>
<groupId>org.jeecgframework.boot</groupId> <groupId>org.jeecgframework.boot</groupId>
<artifactId>jeecg-boot-starter-cloud</artifactId> <artifactId>jeecg-boot-starter-cloud</artifactId>
<exclusions>
<exclusion>
<groupId>cn.hutool</groupId>
<artifactId>hutool-core</artifactId>
</exclusion>
<exclusion>
<groupId>cn.hutool</groupId>
<artifactId>hutool-crypto</artifactId>
</exclusion>
</exclusions>
</dependency> </dependency>
<!-- jeecg-system-biz依赖 --> <!-- jeecg-system-biz依赖 -->

View File

@ -46,7 +46,7 @@
<ojdbc6.version>11.2.0.3</ojdbc6.version> <ojdbc6.version>11.2.0.3</ojdbc6.version>
<sqljdbc4.version>4.0</sqljdbc4.version> <sqljdbc4.version>4.0</sqljdbc4.version>
<mysql-connector-java.version>8.0.27</mysql-connector-java.version> <mysql-connector-java.version>8.0.27</mysql-connector-java.version>
<hutool.version>5.3.8</hutool.version> <hutool.version>5.8.22</hutool.version>
<!-- 持久层 --> <!-- 持久层 -->
<mybatis-plus.version>3.5.1</mybatis-plus.version> <mybatis-plus.version>3.5.1</mybatis-plus.version>

View File

@ -10,6 +10,7 @@ import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result; import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.IotConstants;
import org.jeecg.common.constant.PollutionConstants; import org.jeecg.common.constant.PollutionConstants;
import org.jeecg.common.entity.*; import org.jeecg.common.entity.*;
import org.jeecg.common.constant.enums.PollutionEnum; import org.jeecg.common.constant.enums.PollutionEnum;
@ -18,6 +19,7 @@ import org.jeecg.common.util.oConvertUtils;
import org.jeecg.common.vo.*; import org.jeecg.common.vo.*;
import org.jeecg.modules.appmana.service.*; import org.jeecg.modules.appmana.service.*;
import org.jeecg.modules.appmana.utils.Iotutils; import org.jeecg.modules.appmana.utils.Iotutils;
import org.jeecg.modules.appmana.utils.YSUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.RedisTemplate;
@ -99,6 +101,12 @@ public class BigScreenController {
@Value(value = "${ysy.secret}") @Value(value = "${ysy.secret}")
private String secret; private String secret;
@Autowired
private Iotutils iotutils;
@Autowired
private ISurvConfigService survConfigService;
@ApiOperation("获取萤石云token") @ApiOperation("获取萤石云token")
@PostMapping(value = "/getYsToken") @PostMapping(value = "/getYsToken")
@ -890,7 +898,7 @@ public class BigScreenController {
//移除非摄像头设备 //移除非摄像头设备
survStationInfo.getDeviceList().retainAll(remainList); survStationInfo.getDeviceList().retainAll(remainList);
//补充在线状态 //补充在线状态
survStationInfo.setDeviceList(Iotutils.addOnlineStatus(survStationInfo.getDeviceList())); survStationInfo.setDeviceList(iotutils.addOnlineStatus(survStationInfo.getDeviceList()));
} }
survStationInfo.setLatestData(returnArrs); survStationInfo.setLatestData(returnArrs);
survStationInfo.setLatestSoilData(returnSoilArrs); survStationInfo.setLatestSoilData(returnSoilArrs);
@ -1038,7 +1046,7 @@ public class BigScreenController {
ent.setIotReverseUrl(deploy.getDeviceReverseIotUrl()); ent.setIotReverseUrl(deploy.getDeviceReverseIotUrl());
ent.setMapIcon(deploy.getMapIcon()); ent.setMapIcon(deploy.getMapIcon());
ent.setIds(deploy.getId()); ent.setIds(deploy.getId());
ent.setIsOnline(Iotutils.addOnlineStatus(deploy).getIsOnline()); ent.setIsOnline(iotutils.addOnlineStatus(deploy).getIsOnline());
returnList.add(ent); returnList.add(ent);
} }
} }
@ -1053,13 +1061,15 @@ public class BigScreenController {
@ApiOperation("获取首页站点侧数据") @ApiOperation("获取首页站点侧数据")
public Result stationInfoWithCamera(@RequestParam(value = "stationCode",required = false)String stationCode){ public Result stationInfoWithCamera(@RequestParam(value = "stationCode",required = false)String stationCode){
//萤石云token //萤石云token
String token = getYsToken(); //萤石云token
SurvConfig survConfig = survConfigService.getOneByTypeWithTenant("0", IotConstants.ysyAcess);
String token = new YSUtils().getYsToken(survConfig);
List<SurvStationInfo> stationList = survStationInfoService.getAllStationAndDevice(stationCode,PollutionConstants.CAMERA,token); List<SurvStationInfo> stationList = survStationInfoService.getAllStationAndDevice(stationCode,PollutionConstants.CAMERA,token);
//补充在线状态 //补充在线状态
if(!stationList.isEmpty()){ if(!stationList.isEmpty()){
for (SurvStationInfo survStationInfo : stationList) { for (SurvStationInfo survStationInfo : stationList) {
if(survStationInfo.getDeviceList()!=null && !survStationInfo.getDeviceList().isEmpty()){ if(survStationInfo.getDeviceList()!=null && !survStationInfo.getDeviceList().isEmpty()){
List<SurvDeviceDeploy> deploys = Iotutils.addOnlineStatus(survStationInfo.getDeviceList()); List<SurvDeviceDeploy> deploys = iotutils.addOnlineStatus(survStationInfo.getDeviceList());
survStationInfo.setDeviceList(deploys); survStationInfo.setDeviceList(deploys);
} }
} }

View File

@ -1,12 +1,12 @@
package org.jeecg.modules.appmana.controller; package org.jeecg.modules.appmana.controller;
import java.util.Arrays; import java.util.*;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import cn.hutool.json.JSONUtil;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result; import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator; import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.entity.SurvConfig; import org.jeecg.common.entity.SurvConfig;
@ -59,19 +59,9 @@ public class SurvConfigController extends JeecgController<SurvConfig, ISurvConfi
@RequestParam(name="pageNo", defaultValue="1") Integer pageNo, @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
@RequestParam(name="pageSize", defaultValue="10") Integer pageSize, @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
HttpServletRequest req) { HttpServletRequest req) {
QueryWrapper<SurvConfig> queryWrapper = QueryGenerator.initQueryWrapper(survConfig, req.getParameterMap()); // QueryWrapper<SurvConfig> queryWrapper = QueryGenerator.initQueryWrapper(survConfig, req.getParameterMap());
Page<SurvConfig> page = new Page<SurvConfig>(pageNo, pageSize); Page<SurvConfig> page = new Page<SurvConfig>(pageNo, pageSize);
IPage<SurvConfig> pageList = survConfigService.page(page, queryWrapper); IPage<SurvConfig> pageList = survConfigService.pages(page, survConfig);
//补充字典
if(!pageList.getRecords().isEmpty()){
List<String> types = pageList.getRecords().stream().map(SurvConfig::getConfigType).collect(Collectors.toList());
List<DictVo> maps = survConfigService.getDictByCode("apply_config_type");
// maps.stream().collect(Collectors.toMap())
for (SurvConfig record : pageList.getRecords()) {
}
}
return Result.OK(pageList); return Result.OK(pageList);
} }
@ -89,6 +79,9 @@ public class SurvConfigController extends JeecgController<SurvConfig, ISurvConfi
String username = JwtUtil.getUserNameByToken(request); String username = JwtUtil.getUserNameByToken(request);
survConfig.setCreatedBy(username); survConfig.setCreatedBy(username);
survConfig.setCreateTime(new Date()); survConfig.setCreateTime(new Date());
if (StringUtils.isNotBlank(survConfig.getConfigJsonStr())) {
survConfig.setConfigJson(JSONUtil.parseObj(survConfig.getConfigJsonStr()));
}
survConfigService.save(survConfig); survConfigService.save(survConfig);
return Result.OK("添加成功!"); return Result.OK("添加成功!");
} }
@ -109,6 +102,9 @@ public class SurvConfigController extends JeecgController<SurvConfig, ISurvConfi
survConfig.setUpdatedTime(null); survConfig.setUpdatedTime(null);
String username = JwtUtil.getUserNameByToken(request); String username = JwtUtil.getUserNameByToken(request);
survConfig.setUpdatedBy(username); survConfig.setUpdatedBy(username);
if (StringUtils.isNotBlank(survConfig.getConfigJsonStr())) {
survConfig.setConfigJson(JSONUtil.parseObj(survConfig.getConfigJsonStr()));
}
survConfigService.updateById(survConfig); survConfigService.updateById(survConfig);
return Result.OK("编辑成功!"); return Result.OK("编辑成功!");
} }

View File

@ -7,6 +7,7 @@ import java.util.List;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import cn.hutool.core.lang.Assert;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport; import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
@ -14,8 +15,11 @@ import com.google.gson.JsonObject;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result; import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant; import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.constant.IotConstants;
import org.jeecg.common.constant.PollutionConstants; import org.jeecg.common.constant.PollutionConstants;
import org.jeecg.common.entity.*; import org.jeecg.common.entity.*;
import org.jeecg.common.iot.common.DTOCamControl;
import org.jeecg.common.iot.common.IotDeviceCtlResult;
import org.jeecg.common.system.query.QueryGenerator; import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.util.JwtUtil; import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.vo.DeviceCmdVo; import org.jeecg.common.vo.DeviceCmdVo;
@ -27,6 +31,8 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.system.base.controller.JeecgController; import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.modules.appmana.utils.Iotutils;
import org.jeecg.modules.appmana.utils.YSUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.ModelAndView;
@ -63,6 +69,14 @@ public class SurvDeviceDeployController extends JeecgController<SurvDeviceDeploy
@Autowired @Autowired
private ISurvDeviceDeployService deviceDeployService; private ISurvDeviceDeployService deviceDeployService;
@Autowired
private ISurvConfigService survConfigService;
@Autowired
private ISurvStationInfoService survStationInfoService;
@Autowired
private Iotutils iotutils;
/** /**
* 分页列表查询 * 分页列表查询
* *
@ -287,4 +301,48 @@ public class SurvDeviceDeployController extends JeecgController<SurvDeviceDeploy
return Result.error("初始化失败,请联系管理员!"); return Result.error("初始化失败,请联系管理员!");
} }
} }
@PostMapping("/cameraStart")
@ApiOperation("21.摄像头控制开始")
@ApiOperationSupport(order = 21)
public Result cameraStart(@RequestBody DTOCamControl dtoCamControl) {
SurvDeviceDeploy deploy = survDeviceDeployService.getById(dtoCamControl.getCameraId());
Assert.notNull(deploy, "无效的摄像头");
IotDeviceCtlResult iotDeviceCtlResult = new YSUtils().controlCamra(deploy, deploy.getDeployCode(), dtoCamControl.getDirection());
Boolean result = iotDeviceCtlResult.isSuccess();
return result ? Result.ok(iotDeviceCtlResult.getMessage()) : Result.error(iotDeviceCtlResult.getMessage());
}
@PostMapping("/cameraStop")
@ApiOperation("22.摄像头控制结束")
@ApiOperationSupport(order = 22)
public Result cameraStop(@RequestBody DTOCamControl dtoCamControl) {
SurvDeviceDeploy deploy = survDeviceDeployService.getById(dtoCamControl.getCameraId());
Assert.notNull(deploy, "无效的摄像头");
IotDeviceCtlResult iotDeviceCtlResult = new YSUtils().endControlCamra(deploy, deploy.getDeployCode(), dtoCamControl.getDirection());
Boolean result = iotDeviceCtlResult.isSuccess();
return result ? Result.ok(iotDeviceCtlResult.getMessage()) : Result.error(iotDeviceCtlResult.getMessage());
}
@PostMapping("/stationInfoWithCamera")
@ApiOperation("获取首页站点侧数据")
public Result stationInfoWithCamera(@RequestParam(value = "stationCode",required = false)String stationCode){
//萤石云token
SurvConfig survConfig = survConfigService.getOneByTypeWithTenant("0", IotConstants.ysyAcess);
String token = new YSUtils().getYsToken(survConfig);
List<SurvStationInfo> stationList = survStationInfoService.getAllStationAndDevice(stationCode,PollutionConstants.CAMERA,token);
//补充在线状态
if(!stationList.isEmpty()){
for (SurvStationInfo survStationInfo : stationList) {
if(survStationInfo.getDeviceList()!=null && !survStationInfo.getDeviceList().isEmpty()){
List<SurvDeviceDeploy> deploys = iotutils.addOnlineStatus(survStationInfo.getDeviceList());
survStationInfo.setDeviceList(deploys);
}
}
}
return Result.ok(stationList);
}
} }

View File

@ -1,5 +1,7 @@
package org.jeecg.modules.appmana.mapper; package org.jeecg.modules.appmana.mapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Param;
import org.jeecg.common.entity.SurvConfig; import org.jeecg.common.entity.SurvConfig;
import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper;
@ -22,4 +24,6 @@ public interface SurvConfigMapper extends BaseMapper<SurvConfig> {
SurvConfig getOneByTypeWithTenant(@Param("tenantId") String tenantId, @Param("type") String type); SurvConfig getOneByTypeWithTenant(@Param("tenantId") String tenantId, @Param("type") String type);
List<DictVo> getDictByCode(String applyConfigType); List<DictVo> getDictByCode(String applyConfigType);
IPage<SurvConfig> getPages(Page<SurvConfig> page, @Param("query") SurvConfig survConfig);
} }

View File

@ -2,6 +2,32 @@
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.jeecg.modules.appmana.mapper.SurvConfigMapper"> <mapper namespace="org.jeecg.modules.appmana.mapper.SurvConfigMapper">
<resultMap type="org.jeecg.common.entity.SurvConfig" id="SurvConfigMap">
<result property="id" column="ID" jdbcType="VARCHAR"/>
<result property="configName" column="CONFIG_NAME" jdbcType="VARCHAR"/>
<result property="configKey" column="CONFIG_KEY" jdbcType="VARCHAR"/>
<result property="configValue" column="CONFIG_VALUE" jdbcType="VARCHAR"/>
<result property="configValueSe" column="CONFIG_VALUE_SE" jdbcType="VARCHAR"/>
<result property="configValueSe2" column="CONFIG_VALUE_SE2" jdbcType="VARCHAR"/>
<result property="configValueSe3" column="CONFIG_VALUE_SE3" jdbcType="VARCHAR"/>
<result property="configValueSe4" column="CONFIG_VALUE_SE4" jdbcType="VARCHAR"/>
<result property="configJson" column="CONFIG_JSON" jdbcType="VARCHAR" typeHandler="org.jeecg.common.mybatis.typehandler.JsonTypeHandler"/>
<result property="configType" column="CONFIG_TYPE" jdbcType="VARCHAR"/>
<result property="configRemark" column="CONFIG_REMARK" jdbcType="VARCHAR"/>
<result property="tenantId" column="TENANT_ID" jdbcType="VARCHAR"/>
<result property="reVision" column="RE_VISION" jdbcType="INTEGER"/>
<result property="createdBy" column="CREATED_BY" jdbcType="VARCHAR"/>
<result property="createTime" column="CREATE_TIME" jdbcType="TIMESTAMP"/>
<result property="updatedBy" column="UPDATED_BY" jdbcType="VARCHAR"/>
<result property="isDel" column="IS_DEL" jdbcType="INTEGER"/>
<result property="updatedTime" column="UPDATED_TIME" jdbcType="TIMESTAMP"/>
</resultMap>
<sql id="baseSql">
ID,CONFIG_NAME,CONFIG_KEY,CONFIG_VALUE,CONFIG_VALUE_SE,CONFIG_VALUE_SE2,CONFIG_VALUE_SE3,CONFIG_VALUE_SE4,CONFIG_JSON,CONFIG_TYPE,CONFIG_REMARK,TENANT_ID,RE_VISION,CREATED_BY,CREATE_TIME,UPDATED_BY,IS_DEL,UPDATED_TIME
</sql>
<select id="getValueByKey" resultType="java.lang.String"> <select id="getValueByKey" resultType="java.lang.String">
select CONFIG_VALUE from surv_config where CONFIG_KEY = #{key} select CONFIG_VALUE from surv_config where CONFIG_KEY = #{key}
</select> </select>
@ -19,4 +45,25 @@
and s.status = 1 and s.status = 1
order by s.sort_order asc, s.create_time DESC; order by s.sort_order asc, s.create_time DESC;
</select> </select>
<select id="getPages" resultMap="SurvConfigMap">
select
<include refid="baseSql"/>
from surv_config
<where>
<if test="query.configName != null and query.configName != ''">
and CONFIG_NAME LIKE CONCAT('%',#{query.configName},'%')
</if>
<if test="query.configKey != null and query.configKey != ''">
and CONFIG_KEY = #{query.configKey}
</if>
<if test="query.configType != null and query.configType != ''">
and CONFIG_TYPE = #{query.configType}
</if>
<if test="query.tenantId != null and query.tenantId != ''">
and TENANT_ID = #{query.tenantId}
</if>
</where>
order by CREATE_TIME desc
</select>
</mapper> </mapper>

View File

@ -43,7 +43,7 @@
</sql> </sql>
<select id="getDeviceList" resultType="org.jeecg.common.entity.SurvDeviceDeploy"> <select id="getDeviceList" resultType="org.jeecg.common.entity.SurvDeviceDeploy">
select ID,DEPLOY_TYPE,DEPLOY_CODE,DEPLOY_PIC,DEVICE_URL,DEVICE_CODE,DEPLOY_DES,SORT_NO,#{ysToken} as ysToken from surv_device_deploy where STATION_CODE = #{STATION_CODE} select ID,DEPLOY_TYPE,DEPLOY_CODE,DEPLOY_PIC,DEVICE_URL,DEVICE_CODE,DEPLOY_DES,SORT_NO,DEVICE_IOT_URL,DEVICE_REVERSE_IOT_URL,MAP_ICON,DEVICE_LONGLAT,DEPLOY_SECONDARY_TYPE,#{ysToken} as ysToken from surv_device_deploy where STATION_CODE = #{STATION_CODE}
<if test="deviceType != null and deviceType != ''"> <if test="deviceType != null and deviceType != ''">
AND DEPLOY_TYPE = #{deviceType} AND DEPLOY_TYPE = #{deviceType}
</if> </if>

View File

@ -1,5 +1,7 @@
package org.jeecg.modules.appmana.service; package org.jeecg.modules.appmana.service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.jeecg.common.constant.IotConstants; import org.jeecg.common.constant.IotConstants;
import org.jeecg.common.entity.SurvConfig; import org.jeecg.common.entity.SurvConfig;
import com.baomidou.mybatisplus.extension.service.IService; import com.baomidou.mybatisplus.extension.service.IService;
@ -28,4 +30,6 @@ public interface ISurvConfigService extends IService<SurvConfig> {
long getOfflineConfig(String tenantId,String deployType); long getOfflineConfig(String tenantId,String deployType);
List<DictVo> getDictByCode(String applyConfigType); List<DictVo> getDictByCode(String applyConfigType);
IPage<SurvConfig> pages(Page<SurvConfig> page, SurvConfig survConfig);
} }

View File

@ -3,6 +3,7 @@ package org.jeecg.modules.appmana.service.impl;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils; import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.constant.PollutionConstants; import org.jeecg.common.constant.PollutionConstants;
import org.jeecg.common.constant.enums.PollutionEnum; import org.jeecg.common.constant.enums.PollutionEnum;
import org.jeecg.common.entity.*; import org.jeecg.common.entity.*;
@ -32,7 +33,8 @@ public class CommonServiceImpl {
private ISurvHisdataOrientwaterService hisdataOrientwaterService; private ISurvHisdataOrientwaterService hisdataOrientwaterService;
@Autowired @Autowired
private ISurvHisdataLivestockwaterService hisdataLivestockwaterService; private ISurvHisdataLivestockwaterService hisdataLivestockwaterService;
@Autowired
private SurvConfigServiceImpl configService;
/** /**
* 获取监测设备的数据 * 获取监测设备的数据
@ -131,4 +133,17 @@ public class CommonServiceImpl {
voHisResult.setDataList(dataList); voHisResult.setDataList(dataList);
return voHisResult; return voHisResult;
} }
public SurvConfig getSurvConfig(String configId,String tenantId,String configType) {
SurvConfig survConfig = null;
if(StringUtils.isNotBlank(configId)){
survConfig = configService.getConfigById(configId);
}else{
if(StringUtils.isNotBlank(configType) && StringUtils.isNotBlank(tenantId)){
survConfig = configService.getOneByTypeWithTenant(tenantId, configType);
}
}
return survConfig;
}
} }

View File

@ -1,5 +1,8 @@
package org.jeecg.modules.appmana.service.impl; package org.jeecg.modules.appmana.service.impl;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.constant.IotConstants; import org.jeecg.common.constant.IotConstants;
import org.jeecg.common.constant.PollutionConstants; import org.jeecg.common.constant.PollutionConstants;
@ -15,6 +18,8 @@ import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.Collections; import java.util.Collections;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/** /**
* @Description: 业务参数配置表 * @Description: 业务参数配置表
@ -94,4 +99,22 @@ public class SurvConfigServiceImpl extends ServiceImpl<SurvConfigMapper, SurvCon
public List<DictVo> getDictByCode(String applyConfigType) { public List<DictVo> getDictByCode(String applyConfigType) {
return baseMapper.getDictByCode(applyConfigType); return baseMapper.getDictByCode(applyConfigType);
} }
@Override
public IPage<SurvConfig> pages(Page<SurvConfig> page, SurvConfig survConfig) {
IPage<SurvConfig> pageList = baseMapper.getPages(page,survConfig);
//补充字典
if(!pageList.getRecords().isEmpty()){
List<DictVo> maps = getDictByCode("apply_config_type");
Map<String,DictVo> dictMap = maps.stream().collect(Collectors.toMap(DictVo::getValue, element -> element));
for (SurvConfig record : pageList.getRecords()) {
DictVo dictVo = dictMap.get(record.getConfigType());
record.setConfigTypeName(dictVo!=null?dictVo.getText():record.getConfigType());
if (record.getConfigJson() != null) {
record.setConfigJsonStr(JSONUtil.toJsonStr(record.getConfigJson()));
}
}
}
return pageList;
}
} }

View File

@ -3,17 +3,22 @@ package org.jeecg.modules.appmana.utils;
import org.jeecg.common.entity.SurvDeviceDeploy; import org.jeecg.common.entity.SurvDeviceDeploy;
import org.jeecg.common.util.SpringContextUtils; import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.modules.appmana.service.ISurvConfigService; import org.jeecg.modules.appmana.service.ISurvConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
@Component
public class Iotutils { public class Iotutils {
private static ISurvConfigService survConfigService = SpringContextUtils.getBean(ISurvConfigService.class);
public static Integer checkIsOnline(String tenantId, String protocolCode, Date lastSyncTime, String deployType) { @Autowired
private ISurvConfigService survConfigService ;
public Integer checkIsOnline(String tenantId, String protocolCode, Date lastSyncTime, String deployType) {
long limitTime = survConfigService.getOfflineConfig(tenantId,deployType); long limitTime = survConfigService.getOfflineConfig(tenantId,deployType);
if (lastSyncTime != null) { if (lastSyncTime != null) {
@ -23,7 +28,7 @@ public class Iotutils {
} }
} }
private static int timeCompare(long standardTime, long checkTime) { private int timeCompare(long standardTime, long checkTime) {
Date nowDate = new Date(); Date nowDate = new Date();
long diffInMillies = Math.abs(nowDate.getTime() - checkTime); long diffInMillies = Math.abs(nowDate.getTime() - checkTime);
long diffInMinutes = TimeUnit.MINUTES.convert(diffInMillies, TimeUnit.MILLISECONDS); long diffInMinutes = TimeUnit.MINUTES.convert(diffInMillies, TimeUnit.MILLISECONDS);
@ -34,12 +39,12 @@ public class Iotutils {
} }
} }
public static Integer getDeviceOnlineStatus(SurvDeviceDeploy deploy) { public Integer getDeviceOnlineStatus(SurvDeviceDeploy deploy) {
return checkIsOnline(deploy.getTenantId(),deploy.getProtocolCode(),deploy.getLastsyncTime(),deploy.getDeployType()); return checkIsOnline(deploy.getTenantId(),deploy.getProtocolCode(),deploy.getLastsyncTime(),deploy.getDeployType());
} }
public static List<SurvDeviceDeploy> addOnlineStatus(List<SurvDeviceDeploy> deploys){ public List<SurvDeviceDeploy> addOnlineStatus(List<SurvDeviceDeploy> deploys){
List<SurvDeviceDeploy> deps = new ArrayList<>(); List<SurvDeviceDeploy> deps = new ArrayList<>();
if(deploys!=null && !deploys.isEmpty()){ if(deploys!=null && !deploys.isEmpty()){
for (SurvDeviceDeploy deploy : deploys) { for (SurvDeviceDeploy deploy : deploys) {
@ -50,7 +55,7 @@ public class Iotutils {
return deps; return deps;
} }
public static SurvDeviceDeploy addOnlineStatus(SurvDeviceDeploy deploy){ public SurvDeviceDeploy addOnlineStatus(SurvDeviceDeploy deploy){
if(deploy!=null){ if(deploy!=null){
deploy.setIsOnline(getDeviceOnlineStatus(deploy)); deploy.setIsOnline(getDeviceOnlineStatus(deploy));
} }

View File

@ -0,0 +1,207 @@
package org.jeecg.modules.appmana.utils;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.constant.IotConstants;
import org.jeecg.common.entity.SurvConfig;
import org.jeecg.common.entity.SurvDeviceDeploy;
import org.jeecg.common.iot.common.IotDeviceCtlResult;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.appmana.service.impl.CommonServiceImpl;
import org.jeecg.modules.appmana.service.impl.SurvConfigServiceImpl;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Date;
@Slf4j
public class YSUtils {
// @Autowired
// private RedisTemplate redisTemplate;
private static RedisUtil redisUtil = SpringContextUtils.getBean(RedisUtil.class);
private String ys_key = "ys_token:token:";
private String ys_expire = "ys_token:expire:";
/**
* @Author zy
* @Date 2023/07/06 16:21:17
* @Description: 此注解相当于设置访问URL
*/
public String getYsToken(String appkey, String secret) {
String url = "https://open.ys7.com/api/lapp/token/get";
String curRedisKey = ys_key + appkey;
String curRedisExpireKey = ys_expire + appkey;
//检查缓存中是否有token
if (redisUtil.hasKey(curRedisKey)) {
String ysToken = oConvertUtils.getString(redisUtil.get(curRedisKey));
String ysExpire = oConvertUtils.getString(redisUtil.get(curRedisExpireKey));
if (StringUtils.isNotBlank(ysToken) && StringUtils.isNotBlank(ysExpire)) {
Date d = new Date();
Long curStamp = LocalDateTime.now().toInstant(ZoneOffset.ofHours(8)).toEpochMilli();
Integer isExpire = curStamp.compareTo(Long.valueOf(ysExpire));
if (isExpire < 0) {//未过期
return ysToken;
}
}
}
//缓存中没有token的逻辑
log.error("{}:缓存失效重新获取萤石 Token", appkey);
MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<String, Object>();
paramMap.add("appKey", appkey);
paramMap.add("appSecret", secret);
JSONObject resposeJson = postRequest(url, paramMap);
String resCode = resposeJson.getString("code");
if ("200".equals(resCode)) {//正常获取到token返回并刷新缓存
String newToken = resposeJson.getJSONObject("data").getString("accessToken");
String newExpireTime = resposeJson.getJSONObject("data").getString("expireTime");
redisUtil.set(curRedisKey, newToken);
redisUtil.set(curRedisExpireKey, newExpireTime);
return newToken;
} else {
throw new RuntimeException("token获取失败" + resposeJson.getString("msg"));
}
}
public JSONObject postRequest(String url, MultiValueMap requestMap) {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
MediaType type = MediaType.parseMediaType("application/x-www-form-urlencoded");
headers.setContentType(type);
headers.add("Accept", MediaType.APPLICATION_JSON.toString());
HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(requestMap, headers);
ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(url, httpEntity, JSONObject.class);
JSONObject body2 = responseEntity.getBody(); //响应体
HttpStatus statusCode = responseEntity.getStatusCode(); //状态码
HttpHeaders headers1 = responseEntity.getHeaders();//获取到头信息
return body2;
}
public IotDeviceCtlResult controlCamra(SurvDeviceDeploy deploy, String deployCode, String direction) {
IotDeviceCtlResult iotDeviceCtlResult = new IotDeviceCtlResult();
String url = "https://open.ys7.com/api/lapp/device/ptz/start";
MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<String, Object>();
String[] ss = deployCode.split("_");
if (!(ss.length == 2)) {
log.warn("摄像头部署编号设置错误");
iotDeviceCtlResult.setSuccess(false);
iotDeviceCtlResult.setMessage("摄像头部署编号设置错误");
return iotDeviceCtlResult;
}
// addToken(deploy.getTenantId(), paramMap);
addToken(deploy, paramMap);
paramMap.add("deviceSerial", ss[0]);
paramMap.add("channelNo", ss[1]);
paramMap.add("direction", direction);
paramMap.add("speed", "1");
JSONObject resposeJson = postRequest(url, paramMap);
String resCode = resposeJson.getString("code");
log.warn("萤石云开始摄像头控制回执:" + resposeJson);
if ("200".equals(resCode)) {//正常获取到token返回并刷新缓存
JSONObject dataJson = resposeJson.getJSONObject("data");
iotDeviceCtlResult.setSuccess(true);
iotDeviceCtlResult.setMessage("操作成功");
return iotDeviceCtlResult;
} else {
iotDeviceCtlResult.setSuccess(false);
iotDeviceCtlResult.setMessage(resposeJson.getString("msg"));
return iotDeviceCtlResult;
}
}
public IotDeviceCtlResult endControlCamra(SurvDeviceDeploy deploy, String deployCode, String direction) {
IotDeviceCtlResult iotDeviceCtlResult = new IotDeviceCtlResult();
String url = "https://open.ys7.com/api/lapp/device/ptz/stop";
MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<String, Object>();
String[] ss = deployCode.split("_");
if (!(ss.length == 2)) {
log.warn("摄像头部署编号设置错误");
iotDeviceCtlResult.setSuccess(false);
iotDeviceCtlResult.setMessage("摄像头部署编号设置错误");
return iotDeviceCtlResult;
}
// addToken(deploy.getTenantId(), paramMap);
addToken(deploy, paramMap);
paramMap.add("deviceSerial", ss[0]);
paramMap.add("channelNo", ss[1]);
paramMap.add("direction", direction);
JSONObject resposeJson = postRequest(url, paramMap);
log.warn("萤石云停止摄像头控制回执:" + resposeJson);
String resCode = resposeJson.getString("code");
if ("200".equals(resCode)) {//正常获取到token返回并刷新缓存
JSONObject dataJson = resposeJson.getJSONObject("data");
iotDeviceCtlResult.setSuccess(true);
iotDeviceCtlResult.setMessage("操作成功");
return iotDeviceCtlResult;
} else {
iotDeviceCtlResult.setSuccess(false);
iotDeviceCtlResult.setMessage(resposeJson.getString("msg"));
return iotDeviceCtlResult;
}
}
private void addToken(SurvDeviceDeploy deploy, MultiValueMap<String, Object> paramMap) {
CommonServiceImpl iotCommonP2Service = SpringContextUtils.getBean(CommonServiceImpl.class);
SurvConfig fSurvConfig = iotCommonP2Service.getSurvConfig(deploy.getSurvConfigId(),deploy.getTenantId(), IotConstants.ysyAcess);
String token = "";
if (fSurvConfig != null) {
token = getYsToken(fSurvConfig.getConfigKey(), fSurvConfig.getConfigValue());
}
paramMap.add("accessToken", token);
}
private void addToken(String tenantId, MultiValueMap<String, Object> paramMap) {
SurvConfigServiceImpl fSurvConfigService = SpringContextUtils.getBean(SurvConfigServiceImpl.class);
SurvConfig fSurvConfig = fSurvConfigService.getOneByTypeWithTenant(tenantId, IotConstants.ysyAcess);
String token = "";
if (fSurvConfig != null) {
token = getYsToken(fSurvConfig.getConfigKey(), fSurvConfig.getConfigValue());
}
paramMap.add("accessToken", token);
}
/**
* 传入survConfigid获取萤石云token
* @param configId
* @return
*/
public String getYsToken(String configId){
CommonServiceImpl iotCommonP2Service = SpringContextUtils.getBean(CommonServiceImpl.class);
SurvConfig fSurvConfig = iotCommonP2Service.getSurvConfig(configId,null,IotConstants.ysyAcess);
String token = "";
if (fSurvConfig != null) {
token = getYsToken(fSurvConfig.getConfigKey(), fSurvConfig.getConfigValue());
}
return token;
}
/**
* 传入survConfigid获取萤石云token
* @param configId
* @return
*/
public String getYsToken(SurvConfig survConfig){
String token = getYsToken(survConfig.getConfigKey(), survConfig.getConfigValue());
return token;
}
}

View File

@ -41,6 +41,8 @@ public class SurvDeviceDeployController {
private ISurvDeviceDeployService survDeviceDeployService; private ISurvDeviceDeployService survDeviceDeployService;
@Autowired @Autowired
private ISurvStationInfoService stationInfoService; private ISurvStationInfoService stationInfoService;
@Autowired
private Iotutils iotutils;
/** /**
@ -62,7 +64,7 @@ public class SurvDeviceDeployController {
List<SurvDeviceDeploy> deploys = new ArrayList<>(); List<SurvDeviceDeploy> deploys = new ArrayList<>();
for (SurvDeviceDeploy deviceDeploy : survList) { for (SurvDeviceDeploy deviceDeploy : survList) {
deviceDeploy.setStationName(mp.get(deviceDeploy.getStationCode())); deviceDeploy.setStationName(mp.get(deviceDeploy.getStationCode()));
deviceDeploy = Iotutils.addOnlineStatus(deviceDeploy); deviceDeploy = iotutils.addOnlineStatus(deviceDeploy);
deploys.add(deviceDeploy); deploys.add(deviceDeploy);
} }
return R.ok(deploys); return R.ok(deploys);

View File

@ -84,6 +84,9 @@ public class SurvStationInfoController {
@Autowired @Autowired
private ISurvDisplayInfoService survDisplayInfoService; private ISurvDisplayInfoService survDisplayInfoService;
@Autowired
private Iotutils iotutils;
/** /**
* 分页列表查询 * 分页列表查询
* *
@ -153,7 +156,7 @@ public class SurvStationInfoController {
record.setSurvDataCount(finalDataCounts); record.setSurvDataCount(finalDataCounts);
//补充设备在线状态 //补充设备在线状态
if(record.getDeviceList()!=null && !record.getDeviceList().isEmpty()){ if(record.getDeviceList()!=null && !record.getDeviceList().isEmpty()){
List<SurvDeviceDeploy> deploys = Iotutils.addOnlineStatus(record.getDeviceList()); List<SurvDeviceDeploy> deploys = iotutils.addOnlineStatus(record.getDeviceList());
record.setDeviceList(deploys); record.setDeviceList(deploys);
} }
} }
@ -230,7 +233,7 @@ public class SurvStationInfoController {
jsonObject.put("survItemList",allSurv); jsonObject.put("survItemList",allSurv);
//监控摄像头 //监控摄像头
List<SurvDeviceDeploy> camList = survDeviceDeployService.list(Wrappers.<SurvDeviceDeploy>lambdaQuery().eq(SurvDeviceDeploy::getStationCode,stationCode).eq(SurvDeviceDeploy::getDeployType,PollutionConstants.CAMERA).orderByAsc(SurvDeviceDeploy::getSortNo)); List<SurvDeviceDeploy> camList = survDeviceDeployService.list(Wrappers.<SurvDeviceDeploy>lambdaQuery().eq(SurvDeviceDeploy::getStationCode,stationCode).eq(SurvDeviceDeploy::getDeployType,PollutionConstants.CAMERA).orderByAsc(SurvDeviceDeploy::getSortNo));
List<SurvDeviceDeploy> adds = Iotutils.addOnlineStatus(camList); List<SurvDeviceDeploy> adds = iotutils.addOnlineStatus(camList);
jsonObject.put("survCamera",adds); jsonObject.put("survCamera",adds);
JSONArray jsonArray = new JSONArray(); JSONArray jsonArray = new JSONArray();
@ -400,7 +403,7 @@ public class SurvStationInfoController {
List<SurvStationInfo> stationList = survStationInfoService.listALlStation(); List<SurvStationInfo> stationList = survStationInfoService.listALlStation();
for (SurvStationInfo survStationInfo : stationList) { for (SurvStationInfo survStationInfo : stationList) {
List<SurvDeviceDeploy> pageList = survDeviceDeployService.getDeviceByStationNoCam(survStationInfo.getStationCode(),null); List<SurvDeviceDeploy> pageList = survDeviceDeployService.getDeviceByStationNoCam(survStationInfo.getStationCode(),null);
List<SurvDeviceDeploy> adds = Iotutils.addOnlineStatus(pageList); List<SurvDeviceDeploy> adds = iotutils.addOnlineStatus(pageList);
joa.add(adds); joa.add(adds);
count++; count++;
} }
@ -480,7 +483,7 @@ public class SurvStationInfoController {
ent.setIotReverseUrl(deploy.getDeviceReverseIotUrl()); ent.setIotReverseUrl(deploy.getDeviceReverseIotUrl());
ent.setMapIcon(deploy.getMapIcon()); ent.setMapIcon(deploy.getMapIcon());
ent.setIds(deploy.getId()); ent.setIds(deploy.getId());
ent.setIsOnline(Iotutils.addOnlineStatus(deploy).getIsOnline()); ent.setIsOnline(iotutils.addOnlineStatus(deploy).getIsOnline());
returnList.add(ent); returnList.add(ent);
} }
} }

View File

@ -13,9 +13,9 @@ import java.util.concurrent.TimeUnit;
@Component @Component
public class Iotutils { public class Iotutils {
@Autowired @Autowired
private static ISurvConfigService survConfigService; private ISurvConfigService survConfigService;
public static Integer checkIsOnline(String tenantId, String protocolCode, Date lastSyncTime, String deployType) { public Integer checkIsOnline(String tenantId, String protocolCode, Date lastSyncTime, String deployType) {
long limitTime = survConfigService.getOfflineConfig(tenantId,deployType); long limitTime = survConfigService.getOfflineConfig(tenantId,deployType);
if (lastSyncTime != null) { if (lastSyncTime != null) {
@ -36,12 +36,12 @@ public class Iotutils {
} }
} }
public static Integer getDeviceOnlineStatus(SurvDeviceDeploy deploy) { public Integer getDeviceOnlineStatus(SurvDeviceDeploy deploy) {
return checkIsOnline(deploy.getTenantId(),deploy.getProtocolCode(),deploy.getLastsyncTime(),deploy.getDeployType()); return checkIsOnline(deploy.getTenantId(),deploy.getProtocolCode(),deploy.getLastsyncTime(),deploy.getDeployType());
} }
public static List<SurvDeviceDeploy> addOnlineStatus(List<SurvDeviceDeploy> deploys){ public List<SurvDeviceDeploy> addOnlineStatus(List<SurvDeviceDeploy> deploys){
List<SurvDeviceDeploy> deps = new ArrayList<>(); List<SurvDeviceDeploy> deps = new ArrayList<>();
if(deploys!=null && !deploys.isEmpty()){ if(deploys!=null && !deploys.isEmpty()){
for (SurvDeviceDeploy deploy : deploys) { for (SurvDeviceDeploy deploy : deploys) {
@ -52,7 +52,7 @@ public class Iotutils {
return deps; return deps;
} }
public static SurvDeviceDeploy addOnlineStatus(SurvDeviceDeploy deploy){ public SurvDeviceDeploy addOnlineStatus(SurvDeviceDeploy deploy){
if(deploy!=null){ if(deploy!=null){
deploy.setIsOnline(getDeviceOnlineStatus(deploy)); deploy.setIsOnline(getDeviceOnlineStatus(deploy));
} }

View File

@ -13,7 +13,7 @@
<properties> <properties>
<ttl.version>2.11.4</ttl.version> <ttl.version>2.11.4</ttl.version>
<huTool.version>5.7.3</huTool.version> <huTool.version>5.8.22</huTool.version>
<mysql-connector-java.version>8.0.27</mysql-connector-java.version> <mysql-connector-java.version>8.0.27</mysql-connector-java.version>
<weixin.version>4.5.1.B</weixin.version> <weixin.version>4.5.1.B</weixin.version>
<knife4j-spring-boot-starter.version>3.0.3</knife4j-spring-boot-starter.version> <knife4j-spring-boot-starter.version>3.0.3</knife4j-spring-boot-starter.version>

View File

@ -120,4 +120,7 @@ public class SurvConfig implements Serializable {
@TableField(exist = false) @TableField(exist = false)
private String configTypeName; private String configTypeName;
@TableField(exist = false)
private String configJsonStr;
} }

View File

@ -0,0 +1,14 @@
package org.jeecg.common.iot.common;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
@Data
public class DTOCamControl {
@ApiModelProperty("设备部署编号")
private String cameraId;
@ApiModelProperty("设备朝向")
private String direction;
@ApiModelProperty("授权密钥,除大屏外勿传")
private String auths;
}

View File

@ -0,0 +1,15 @@
package org.jeecg.common.iot.common;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* 物联网设备操作结果
*/
@Data
public class IotDeviceCtlResult {
@ApiModelProperty("是否成功")
private boolean success;
@ApiModelProperty("返回信息")
private String message;
}

View File

@ -1,5 +1,6 @@
package org.jeecg.common.mybatis.typehandler; package org.jeecg.common.mybatis.typehandler;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject; import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil; import cn.hutool.json.JSONUtil;
import org.apache.ibatis.type.BaseTypeHandler; import org.apache.ibatis.type.BaseTypeHandler;
@ -13,38 +14,42 @@ import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
/** /**
* 存储到数据库, 将JSON对象转换成字符串; * 存储到数据库, 将JSON对象转换成字符串;
* 从数据库获取数据, 将字符串转为JSON对象. * 从数据库获取数据, 将字符串转为JSON对象.
*/ */
@MappedTypes({JSONObject.class}) @MappedTypes({JSONObject.class})
@MappedJdbcTypes({JdbcType.VARCHAR}) @MappedJdbcTypes({JdbcType.VARCHAR})
public class JsonTypeHandler extends BaseTypeHandler<JSONObject> { public class JsonTypeHandler extends BaseTypeHandler<JSONObject> {
@Override private static final String EMPTY_OBJECT = "{}";
public void setNonNullParameter(PreparedStatement ps, int i, JSONObject parameter,
JdbcType jdbcType) throws SQLException {
ps.setString(i, JSONUtil.toJsonStr(parameter)); @Override
} public void setNonNullParameter(PreparedStatement ps, int i, JSONObject parameter,
JdbcType jdbcType) throws SQLException {
ps.setString(i, JSONUtil.toJsonStr(parameter == null ? EMPTY_OBJECT : parameter));
}
@Override @Override
public JSONObject getNullableResult(ResultSet rs, String columnName) public JSONObject getNullableResult(ResultSet rs, String columnName)
throws SQLException { throws SQLException {
return to(rs.getString(columnName));
}
return JSONUtil.parseObj(rs.getString(columnName)).toBean(JSONObject.class); @Override
} public JSONObject getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
return to(rs.getString(columnIndex));
}
@Override @Override
public JSONObject getNullableResult(ResultSet rs, int columnIndex) throws SQLException { public JSONObject getNullableResult(CallableStatement cs, int columnIndex)
throws SQLException {
return JSONUtil.parseObj(rs.getString(columnIndex)).toBean(JSONObject.class); return to(cs.getString(columnIndex));
} }
@Override
public JSONObject getNullableResult(CallableStatement cs, int columnIndex)
throws SQLException {
return JSONUtil.parseObj(cs.getString(columnIndex)).toBean(JSONObject.class);
}
private JSONObject to(String s) {
if (StrUtil.isBlank(s)) {
s = EMPTY_OBJECT;
}
return JSONUtil.parseObj(s).toBean(JSONObject.class);
}
} }