Commit 8d027b10 by 胡懿

物联网模块

parent 01cd2faf
...@@ -10,4 +10,6 @@ public class ErrorInfo { ...@@ -10,4 +10,6 @@ public class ErrorInfo {
public static ErrorCode USER_DES_RULE_NOT_EXISTS = new ErrorCode(5, "人员脱敏规则不存在"); public static ErrorCode USER_DES_RULE_NOT_EXISTS = new ErrorCode(5, "人员脱敏规则不存在");
public static ErrorCode DES_CORPORATION_NOT_EXISTS = new ErrorCode(6, "法人脱敏不存在"); public static ErrorCode DES_CORPORATION_NOT_EXISTS = new ErrorCode(6, "法人脱敏不存在");
public static ErrorCode IMPORTANT_FILE_NOT_EXISTS = new ErrorCode(7, "重要文件不存在"); public static ErrorCode IMPORTANT_FILE_NOT_EXISTS = new ErrorCode(7, "重要文件不存在");
public static ErrorCode CONNET_RULE_NOT_EXISTS = new ErrorCode(8, "设备连接规则不存在");
public static ErrorCode CONNET_RULE_INFO_NOT_EXISTS = new ErrorCode(9, "设备规则配置细则不存在");
} }
package cn.gintone.config; package cn.gintone.config;
import cn.gintone.dto.DeviceLogInfo;
import cn.gintone.dto.WebLogInfo; import cn.gintone.dto.WebLogInfo;
import cn.gintone.entity.DeviceConnetRuleInfoDO;
import cn.gintone.iotdbUtils.MyIotDbUtils; import cn.gintone.iotdbUtils.MyIotDbUtils;
import cn.gintone.service.DeviceConnetRuleInfoService;
import cn.gintone.service.VisitInfoService; import cn.gintone.service.VisitInfoService;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel; import com.rabbitmq.client.Channel;
...@@ -25,6 +28,8 @@ public class MyConsumer { ...@@ -25,6 +28,8 @@ public class MyConsumer {
@Autowired @Autowired
private VisitInfoService visitInfoService; private VisitInfoService visitInfoService;
@Autowired
private DeviceConnetRuleInfoService deviceConnetRuleInfoService;
/** /**
* 监听队列---当队列中有消息,则监听器工作,处理接受到的消息 * 监听队列---当队列中有消息,则监听器工作,处理接受到的消息
...@@ -40,8 +45,6 @@ public class MyConsumer { ...@@ -40,8 +45,6 @@ public class MyConsumer {
byte[] body = message.getBody(); byte[] body = message.getBody();
String receivedRoutingKey = message.getMessageProperties().getReceivedRoutingKey(); String receivedRoutingKey = message.getMessageProperties().getReceivedRoutingKey();
if (receivedRoutingKey.contains("weblog")) { if (receivedRoutingKey.contains("weblog")) {
System.out.println(iotDbConfig);
System.out.println(channel);
String jsonStr = new String(body); String jsonStr = new String(body);
WebLogInfo webLogInfo = null; WebLogInfo webLogInfo = null;
try { try {
...@@ -53,6 +56,12 @@ public class MyConsumer { ...@@ -53,6 +56,12 @@ public class MyConsumer {
}finally { }finally {
return; return;
} }
} else if (receivedRoutingKey.contains("devicelog")) {
String jsonStr = new String(body);
DeviceLogInfo deviceLogInfo = null;
deviceLogInfo = JSON.parseObject(JSON.parse(jsonStr).toString(), DeviceLogInfo.class);
MyIotDbUtils.inserOneDeviceLogInfo(iotDbConfig, deviceLogInfo);
deviceConnetRuleInfoService.checkDeviceLogInfo(deviceLogInfo);
} }
......
package cn.gintone.controller;
import cn.gintone.controller.vo.DeviceConnetRulePageReqVO;
import cn.gintone.controller.vo.DeviceConnetRuleRespVO;
import cn.gintone.controller.vo.DeviceConnetRuleSaveReqVO;
import cn.gintone.entity.DeviceConnetRuleDO;
import cn.gintone.service.DeviceConnetRuleService;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;
import javax.validation.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.List;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.*;
@Tag(name = "管理后台 - 设备连接规则")
@RestController
@RequestMapping("/admin-api/device/connet-rule")
@Validated
public class DeviceConnetRuleController {
@Resource
private DeviceConnetRuleService connetRuleService;
@PostMapping("/create")
@Operation(summary = "创建设备连接规则")
@PreAuthorize("@ss.hasPermission('device:connet-rule:create')")
public CommonResult<Long> createConnetRule(@Valid @RequestBody DeviceConnetRuleSaveReqVO createReqVO) {
return success(connetRuleService.createConnetRule(createReqVO));
}
@PutMapping("/update")
@Operation(summary = "更新设备连接规则")
@PreAuthorize("@ss.hasPermission('device:connet-rule:update')")
public CommonResult<Boolean> updateConnetRule(@Valid @RequestBody DeviceConnetRuleSaveReqVO updateReqVO) {
connetRuleService.updateConnetRule(updateReqVO);
return success(true);
}
@DeleteMapping("/delete")
@Operation(summary = "删除设备连接规则")
@Parameter(name = "id", description = "编号", required = true)
@PreAuthorize("@ss.hasPermission('device:connet-rule:delete')")
public CommonResult<Boolean> deleteConnetRule(@RequestParam("id") Long id) {
connetRuleService.deleteConnetRule(id);
return success(true);
}
@GetMapping("/get")
@Operation(summary = "获得设备连接规则")
@Parameter(name = "id", description = "编号", required = true, example = "1024")
@PreAuthorize("@ss.hasPermission('device:connet-rule:query')")
public CommonResult<DeviceConnetRuleRespVO> getConnetRule(@RequestParam("id") Long id) {
DeviceConnetRuleDO connetRule = connetRuleService.getConnetRule(id);
return success(BeanUtils.toBean(connetRule, DeviceConnetRuleRespVO.class));
}
@GetMapping("/page")
@Operation(summary = "获得设备连接规则分页")
@PreAuthorize("@ss.hasPermission('device:connet-rule:query')")
public CommonResult<PageResult<DeviceConnetRuleRespVO>> getConnetRulePage(@Valid DeviceConnetRulePageReqVO pageReqVO) {
PageResult<DeviceConnetRuleDO> pageResult = connetRuleService.getConnetRulePage(pageReqVO);
return success(BeanUtils.toBean(pageResult, DeviceConnetRuleRespVO.class));
}
@GetMapping("/export-excel")
@Operation(summary = "导出设备连接规则 Excel")
@PreAuthorize("@ss.hasPermission('device:connet-rule:export')")
@ApiAccessLog(operateType = EXPORT)
public void exportConnetRuleExcel(@Valid DeviceConnetRulePageReqVO pageReqVO,
HttpServletResponse response) throws IOException {
pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
List<DeviceConnetRuleDO> list = connetRuleService.getConnetRulePage(pageReqVO).getList();
// 导出 Excel
ExcelUtils.write(response, "设备连接规则.xls", "数据", DeviceConnetRuleRespVO.class,
BeanUtils.toBean(list, DeviceConnetRuleRespVO.class));
}
}
\ No newline at end of file
package cn.gintone.controller;
import cn.gintone.controller.vo.*;
import cn.gintone.dto.DeviceType;
import cn.gintone.entity.DeviceConnetRuleInfoDO;
import cn.gintone.entity.VisitInfoDO;
import cn.gintone.service.DeviceConnetRuleInfoService;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;
import javax.validation.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.List;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.*;
@Tag(name = "管理后台 - 设备规则配置细则")
@RestController
@RequestMapping("/admin-api/device/connet-rule-info")
@Validated
public class DeviceConnetRuleInfoController {
@Resource
private DeviceConnetRuleInfoService connetRuleInfoService;
@PostMapping("/create")
@Operation(summary = "创建设备规则配置细则")
// @PreAuthorize("@ss.hasPermission('device:connet-rule-info:create')")
public CommonResult<Long> createConnetRuleInfo(@Valid @RequestBody DeviceConnetRuleInfoSaveReqVO createReqVO) {
return success(connetRuleInfoService.createConnetRuleInfo(createReqVO));
}
@PutMapping("/update")
@Operation(summary = "更新设备规则配置细则")
// @PreAuthorize("@ss.hasPermission('device:connet-rule-info:update')")
public CommonResult<Boolean> updateConnetRuleInfo(@Valid @RequestBody DeviceConnetRuleInfoSaveReqVO updateReqVO) {
connetRuleInfoService.updateConnetRuleInfo(updateReqVO);
return success(true);
}
@DeleteMapping("/delete")
@Operation(summary = "删除设备规则配置细则")
@Parameter(name = "id", description = "编号", required = true)
// @PreAuthorize("@ss.hasPermission('device:connet-rule-info:delete')")
public CommonResult<Boolean> deleteConnetRuleInfo(@RequestParam("id") Long id) {
connetRuleInfoService.deleteConnetRuleInfo(id);
return success(true);
}
@GetMapping("/get")
@Operation(summary = "获得设备规则配置细则")
@Parameter(name = "id", description = "编号", required = true, example = "1024")
// @PreAuthorize("@ss.hasPermission('device:connet-rule-info:query')")
public CommonResult<DeviceConnetRuleInfoRespVO> getConnetRuleInfo(@RequestParam("id") Long id) {
DeviceConnetRuleInfoDO connetRuleInfo = connetRuleInfoService.getConnetRuleInfo(id);
return success(BeanUtils.toBean(connetRuleInfo, DeviceConnetRuleInfoRespVO.class));
}
@GetMapping("/page")
@Operation(summary = "获得设备规则配置细则分页")
// @PreAuthorize("@ss.hasPermission('device:connet-rule-info:query')")
public CommonResult<PageResult<DeviceConnetRuleInfoRespVO>> getConnetRuleInfoPage(@Valid DeviceConnetRuleInfoPageReqVO pageReqVO) {
PageResult<DeviceConnetRuleInfoDO> pageResult = connetRuleInfoService.getConnetRuleInfoPage(pageReqVO);
return success(BeanUtils.toBean(pageResult, DeviceConnetRuleInfoRespVO.class));
}
@GetMapping("/getList")
@Operation(summary = "获得访问规则配置")
public CommonResult<List<DeviceConnetRuleInfoDO>> getList(DeviceConnetRuleInfoPageReqVO pageReqVO) {
List<DeviceConnetRuleInfoDO> list = connetRuleInfoService.getList(pageReqVO);
return success(list);
}
@GetMapping("/export-excel")
@Operation(summary = "导出设备规则配置细则 Excel")
// @PreAuthorize("@ss.hasPermission('device:connet-rule-info:export')")
@ApiAccessLog(operateType = EXPORT)
public void exportConnetRuleInfoExcel(@Valid DeviceConnetRuleInfoPageReqVO pageReqVO,
HttpServletResponse response) throws IOException {
pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
List<DeviceConnetRuleInfoDO> list = connetRuleInfoService.getConnetRuleInfoPage(pageReqVO).getList();
// 导出 Excel
ExcelUtils.write(response, "设备规则配置细则.xls", "数据", DeviceConnetRuleInfoRespVO.class,
BeanUtils.toBean(list, DeviceConnetRuleInfoRespVO.class));
}
@GetMapping("/getDeviceType")
@Operation(summary = "获取设备信息")
public CommonResult<List<DeviceType>> getDeviceType() {
List<DeviceType> deviceTypeList = connetRuleInfoService.getDeviceType();
return success(deviceTypeList);
}
@PostMapping("/saveAll")
@Operation(summary = "创建设备访问细则")
public CommonResult<Boolean> saveAll(@Valid @RequestBody List<DeviceConnetRuleInfoRespVO> deviceConnetRuleInfoRespVOList) {
return success(connetRuleInfoService.saveAll(deviceConnetRuleInfoRespVOList));
}
@DeleteMapping("/deleteByRuleId")
@Operation(summary = "根据RuleId删除访问规则配置")
@Parameter(name = "id", description = "编号", required = true)
public CommonResult<Boolean> deleteByRuleId(@RequestParam("ruleId") Long ruleId) {
connetRuleInfoService.deleteByRuleId(ruleId);
return success(true);
}
@PutMapping("/updateAll")
@Operation(summary = "更新访问规则配置")
public CommonResult<Boolean> updateAll(@Valid @RequestBody List<DeviceConnetRuleInfoRespVO> deviceConnetRuleInfoRespVOList) {
return success(connetRuleInfoService.updateAll(deviceConnetRuleInfoRespVOList));
}
}
\ No newline at end of file
package cn.gintone.controller;
import cn.gintone.config.IotDbConfig;
import cn.gintone.dto.*;
import cn.gintone.iotdbUtils.MyDateUtils;
import cn.gintone.iotdbUtils.MyIotDbUtils;
import cn.iocoder.yudao.framework.common.exception.ErrorCode;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import com.alibaba.fastjson.JSON;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Date;
import java.util.List;
@RestController
@RequestMapping("/admin-api/gintone/deviceLogInfo")
public class DeviceLogInfoController {
@Autowired
private RabbitTemplate rabbitTemplate;
@Autowired
private IotDbConfig iotDbConfig;
@PostMapping("/saveDeviceLogInfo")
@Operation(summary = "外部性请求保存日志")
public CommonResult<String> saveDeviceLogInfo(@RequestBody DeviceLogInfo deviceLogInfo) {
if (null == deviceLogInfo.getAccessed()) {
deviceLogInfo.setAccessed(MyDateUtils.longToString(new Date().getTime()));
}
String deviceLogInfoStr = JSON.toJSONString(deviceLogInfo);
rabbitTemplate.convertAndSend("my_boot_topic_exchange", "devicelog.save", deviceLogInfoStr);
return CommonResult.success("保存成功");
}
@PostMapping("/saveDeviceLogInfoList")
@Operation(summary = "外部性请求保存日志")
public CommonResult<String> saveDeviceLogInfoList(@RequestBody List<DeviceLogInfo> deviceLogInfoList) {
if (null != deviceLogInfoList && deviceLogInfoList.size() > 0) {
for (DeviceLogInfo deviceLogInfo : deviceLogInfoList) {
if (null == deviceLogInfo.getAccessed()) {
deviceLogInfo.setAccessed(MyDateUtils.longToString(new Date().getTime()));
}
String deviceLogInfoStr = JSON.toJSONString(deviceLogInfo);
rabbitTemplate.convertAndSend("my_boot_topic_exchange", "devicelog.save", deviceLogInfoStr);
}
return CommonResult.success("保存成功");
} else {
return CommonResult.error(new ErrorCode(205, "上报设备日志不能为空"));
}
}
@PostMapping("/initIllIotDBTable")
@Operation(summary = "初始设备访问时间序列")
public CommonResult<String> initIllIotDBTable() {
MyIotDbUtils.createDeviceLogInfoTimeseries(iotDbConfig);
MyIotDbUtils.createDeviceIllLogInfoTimeseries(iotDbConfig);
return CommonResult.success("初始化成功");
}
@GetMapping("/countDeviceIllLogInfo")
@Operation(summary = "统计非法日志条数接口")
public CommonResult<Long> countDeviceIllLogInfo(DeviceIllLogInfo deviceIllLogInfo) {
long pageCount = MyIotDbUtils.countDeviceLogInfo_ill(iotDbConfig, deviceIllLogInfo);
return CommonResult.success(pageCount);
}
@GetMapping("/deviceIllLogInfoList")
@Operation(summary = "查询非法日志记录")
public CommonResult<List<DeviceIllLogInfo>> deviceIllLogInfoList(DeviceIllLogInfo deviceIllLogInfo) {
List<DeviceIllLogInfo> deviceIllLogInfoList = MyIotDbUtils.selectDeviceLogInfo_ill(iotDbConfig, deviceIllLogInfo);
return CommonResult.success(deviceIllLogInfoList);
}
@GetMapping("/countDeviceLogInfo")
@Operation(summary = "统计设备访问日志条数接口")
public CommonResult<Long> countDeviceLogInfo(DeviceLogInfo deviceLogInfo) {
long pageCount = MyIotDbUtils.countDeviceLogInfo(iotDbConfig, deviceLogInfo);
return CommonResult.success(pageCount);
}
@GetMapping("/deviceLogInfoList")
@Operation(summary = "查询设备访问日志记录")
public CommonResult<List<DeviceLogInfo>> deviceLogInfoList(DeviceLogInfo deviceLogInfo) {
List<DeviceLogInfo> deviceLogInfoList = MyIotDbUtils.selectDeviceLogInfo(iotDbConfig, deviceLogInfo);
return CommonResult.success(deviceLogInfoList);
}
}
package cn.gintone.controller.vo;
import lombok.*;
import java.util.*;
import io.swagger.v3.oas.annotations.media.Schema;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import org.springframework.format.annotation.DateTimeFormat;
import java.time.LocalDateTime;
import static cn.iocoder.yudao.framework.common.util.date.DateUtils.FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND;
@Schema(description = "管理后台 - 设备规则配置细则分页 Request VO")
@Data
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
public class DeviceConnetRuleInfoPageReqVO extends PageParam {
@Schema(description = "规则外键", example = "11033")
private Long deviceRuleId;
@Schema(description = "设备名称", example = "李四")
private String deviceName;
@Schema(description = "设备id", example = "10642")
private String deviceId;
@Schema(description = "角色", example = "9412")
private String roleId;
@Schema(description = "角色名称", example = "张三")
private String roleName;
@Schema(description = "用户id", example = "31481")
private String userId;
@Schema(description = "用户名称", example = "芋艿")
private String userName;
@Schema(description = "创建时间")
@DateTimeFormat(pattern = FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND)
private LocalDateTime[] createTime;
}
\ No newline at end of file
package cn.gintone.controller.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.*;
import java.util.*;
import org.springframework.format.annotation.DateTimeFormat;
import java.time.LocalDateTime;
import com.alibaba.excel.annotation.*;
@Schema(description = "管理后台 - 设备规则配置细则 Response VO")
@Data
@ExcelIgnoreUnannotated
public class DeviceConnetRuleInfoRespVO {
@Schema(description = "id", requiredMode = Schema.RequiredMode.REQUIRED, example = "18505")
@ExcelProperty("id")
private Long id;
@Schema(description = "规则外键", requiredMode = Schema.RequiredMode.REQUIRED, example = "11033")
@ExcelProperty("规则外键")
private Long deviceRuleId;
@Schema(description = "设备名称", example = "李四")
@ExcelProperty("设备名称")
private String deviceName;
@Schema(description = "设备id", example = "10642")
@ExcelProperty("设备id")
private String deviceId;
@Schema(description = "角色", example = "9412")
@ExcelProperty("角色")
private String roleId;
@Schema(description = "角色名称", example = "张三")
@ExcelProperty("角色名称")
private String roleName;
@Schema(description = "用户id", example = "31481")
@ExcelProperty("用户id")
private String userId;
@Schema(description = "用户名称", example = "芋艿")
@ExcelProperty("用户名称")
private String userName;
@Schema(description = "创建时间", requiredMode = Schema.RequiredMode.REQUIRED)
@ExcelProperty("创建时间")
private LocalDateTime createTime;
}
\ No newline at end of file
package cn.gintone.controller.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.*;
import java.util.*;
import javax.validation.constraints.*;
@Schema(description = "管理后台 - 设备规则配置细则新增/修改 Request VO")
@Data
public class DeviceConnetRuleInfoSaveReqVO {
@Schema(description = "id", requiredMode = Schema.RequiredMode.REQUIRED, example = "18505")
private Long id;
@Schema(description = "规则外键", requiredMode = Schema.RequiredMode.REQUIRED, example = "11033")
@NotNull(message = "规则外键不能为空")
private Long deviceRuleId;
@Schema(description = "设备名称", example = "李四")
private String deviceName;
@Schema(description = "设备id", example = "10642")
private String deviceId;
@Schema(description = "角色", example = "9412")
private String roleId;
@Schema(description = "角色名称", example = "张三")
private String roleName;
@Schema(description = "用户id", example = "31481")
private String userId;
@Schema(description = "用户名称", example = "芋艿")
private String userName;
}
\ No newline at end of file
package cn.gintone.controller.vo;
import lombok.*;
import java.util.*;
import io.swagger.v3.oas.annotations.media.Schema;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import org.springframework.format.annotation.DateTimeFormat;
import java.time.LocalDateTime;
import static cn.iocoder.yudao.framework.common.util.date.DateUtils.FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND;
@Schema(description = "管理后台 - 设备连接规则分页 Request VO")
@Data
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
public class DeviceConnetRulePageReqVO extends PageParam {
@Schema(description = "规则名称", example = "张三")
private String name;
@Schema(description = "创建时间")
@DateTimeFormat(pattern = FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND)
private LocalDateTime[] createTime;
}
\ No newline at end of file
package cn.gintone.controller.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.*;
import java.util.*;
import org.springframework.format.annotation.DateTimeFormat;
import java.time.LocalDateTime;
import com.alibaba.excel.annotation.*;
@Schema(description = "管理后台 - 设备连接规则 Response VO")
@Data
@ExcelIgnoreUnannotated
public class DeviceConnetRuleRespVO {
@Schema(description = "id", requiredMode = Schema.RequiredMode.REQUIRED, example = "12777")
@ExcelProperty("id")
private Long id;
@Schema(description = "规则名称", requiredMode = Schema.RequiredMode.REQUIRED, example = "张三")
@ExcelProperty("规则名称")
private String name;
@Schema(description = "创建时间", requiredMode = Schema.RequiredMode.REQUIRED)
@ExcelProperty("创建时间")
private LocalDateTime createTime;
}
\ No newline at end of file
package cn.gintone.controller.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.*;
import java.util.*;
import javax.validation.constraints.*;
@Schema(description = "管理后台 - 设备连接规则新增/修改 Request VO")
@Data
public class DeviceConnetRuleSaveReqVO {
@Schema(description = "id", requiredMode = Schema.RequiredMode.REQUIRED, example = "12777")
private Long id;
@Schema(description = "规则名称", requiredMode = Schema.RequiredMode.REQUIRED, example = "张三")
@NotEmpty(message = "规则名称不能为空")
private String name;
}
\ No newline at end of file
package cn.gintone.dal;
import cn.gintone.controller.vo.DeviceConnetRuleInfoPageReqVO;
import cn.gintone.entity.DeviceConnetRuleInfoDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.mybatis.core.mapper.BaseMapperX;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
/**
* 设备规则配置细则 Mapper
*
* @author 胡懿
*/
@Mapper
public interface DeviceConnetRuleInfoMapper extends BaseMapperX<DeviceConnetRuleInfoDO> {
default PageResult<DeviceConnetRuleInfoDO> selectPage(DeviceConnetRuleInfoPageReqVO reqVO) {
return selectPage(reqVO, new LambdaQueryWrapperX<DeviceConnetRuleInfoDO>()
.eqIfPresent(DeviceConnetRuleInfoDO::getDeviceRuleId, reqVO.getDeviceRuleId())
.likeIfPresent(DeviceConnetRuleInfoDO::getDeviceName, reqVO.getDeviceName())
.eqIfPresent(DeviceConnetRuleInfoDO::getDeviceId, reqVO.getDeviceId())
.eqIfPresent(DeviceConnetRuleInfoDO::getRoleId, reqVO.getRoleId())
.likeIfPresent(DeviceConnetRuleInfoDO::getRoleName, reqVO.getRoleName())
.eqIfPresent(DeviceConnetRuleInfoDO::getUserId, reqVO.getUserId())
.likeIfPresent(DeviceConnetRuleInfoDO::getUserName, reqVO.getUserName())
.betweenIfPresent(DeviceConnetRuleInfoDO::getCreateTime, reqVO.getCreateTime())
.orderByDesc(DeviceConnetRuleInfoDO::getId));
}
default List<DeviceConnetRuleInfoDO> selectList(DeviceConnetRuleInfoPageReqVO reqVO) {
List<DeviceConnetRuleInfoDO> deviceConnetRuleInfoDOS = selectList(new LambdaQueryWrapperX<DeviceConnetRuleInfoDO>()
.eqIfPresent(DeviceConnetRuleInfoDO::getDeviceRuleId, reqVO.getDeviceRuleId())
.likeIfPresent(DeviceConnetRuleInfoDO::getDeviceName, reqVO.getDeviceName())
.eqIfPresent(DeviceConnetRuleInfoDO::getDeviceId, reqVO.getDeviceId())
.eqIfPresent(DeviceConnetRuleInfoDO::getRoleId, reqVO.getRoleId())
.likeIfPresent(DeviceConnetRuleInfoDO::getRoleName, reqVO.getRoleName())
.eqIfPresent(DeviceConnetRuleInfoDO::getUserId, reqVO.getUserId())
.likeIfPresent(DeviceConnetRuleInfoDO::getUserName, reqVO.getUserName())
.betweenIfPresent(DeviceConnetRuleInfoDO::getCreateTime, reqVO.getCreateTime())
.orderByDesc(DeviceConnetRuleInfoDO::getId));
return deviceConnetRuleInfoDOS;
}
}
\ No newline at end of file
package cn.gintone.dal;
import cn.gintone.controller.vo.DeviceConnetRulePageReqVO;
import cn.gintone.entity.DeviceConnetRuleDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.mybatis.core.mapper.BaseMapperX;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import org.apache.ibatis.annotations.Mapper;
/**
* 设备连接规则 Mapper
*
* @author 胡懿
*/
@Mapper
public interface DeviceConnetRuleMapper extends BaseMapperX<DeviceConnetRuleDO> {
default PageResult<DeviceConnetRuleDO> selectPage(DeviceConnetRulePageReqVO reqVO) {
return selectPage(reqVO, new LambdaQueryWrapperX<DeviceConnetRuleDO>()
.likeIfPresent(DeviceConnetRuleDO::getName, reqVO.getName())
.betweenIfPresent(DeviceConnetRuleDO::getCreateTime, reqVO.getCreateTime())
.orderByDesc(DeviceConnetRuleDO::getId));
}
}
\ No newline at end of file
package cn.gintone.dto;
public class DeviceIllLogInfo {
private Long timesta;
private String timestaStr;
private String roleId;
private String roleName;
private String userId; // 用户id
private String username; // 用户名
private String deviceId; // 设备id
private String deviceName; // 设备名称
private String deviceTypeId; // 设备类型id
private String deviceTypeName; // 设备类型名称
private String accessed; // 访问时间
private String illType; // 日志类型()
private String clientIp; // 访问端ip
private String remark; // 备注
private Long beginTime;
private Long endTime;
private Integer pageSize;
private Integer pageNum;
public Long getTimesta() {
return timesta;
}
public void setTimesta(Long timesta) {
this.timesta = timesta;
}
public String getTimestaStr() {
return timestaStr;
}
public void setTimestaStr(String timestaStr) {
this.timestaStr = timestaStr;
}
public String getRoleId() {
return roleId;
}
public void setRoleId(String roleId) {
this.roleId = roleId;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getDeviceId() {
return deviceId;
}
public void setDeviceId(String deviceId) {
this.deviceId = deviceId;
}
public String getDeviceName() {
return deviceName;
}
public void setDeviceName(String deviceName) {
this.deviceName = deviceName;
}
public String getDeviceTypeId() {
return deviceTypeId;
}
public void setDeviceTypeId(String deviceTypeId) {
this.deviceTypeId = deviceTypeId;
}
public String getDeviceTypeName() {
return deviceTypeName;
}
public void setDeviceTypeName(String deviceTypeName) {
this.deviceTypeName = deviceTypeName;
}
public String getAccessed() {
return accessed;
}
public void setAccessed(String accessed) {
this.accessed = accessed;
}
public String getIllType() {
return illType;
}
public void setIllType(String illType) {
this.illType = illType;
}
public String getClientIp() {
return clientIp;
}
public void setClientIp(String clientIp) {
this.clientIp = clientIp;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public Long getBeginTime() {
return beginTime;
}
public void setBeginTime(Long beginTime) {
this.beginTime = beginTime;
}
public Long getEndTime() {
return endTime;
}
public void setEndTime(Long endTime) {
this.endTime = endTime;
}
public Integer getPageSize() {
return pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
public Integer getPageNum() {
return pageNum;
}
public void setPageNum(Integer pageNum) {
this.pageNum = pageNum;
}
@Override
public String toString() {
return "DeviceIllLogInfo{" +
"timesta=" + timesta +
", timestaStr='" + timestaStr + '\'' +
", roleId='" + roleId + '\'' +
", roleName='" + roleName + '\'' +
", userId='" + userId + '\'' +
", username='" + username + '\'' +
", deviceId='" + deviceId + '\'' +
", deviceName='" + deviceName + '\'' +
", deviceTypeId='" + deviceTypeId + '\'' +
", deviceTypeName='" + deviceTypeName + '\'' +
", accessed='" + accessed + '\'' +
", illType='" + illType + '\'' +
", clientIp='" + clientIp + '\'' +
", remark='" + remark + '\'' +
", beginTime=" + beginTime +
", endTime=" + endTime +
", pageSize=" + pageSize +
", pageNum=" + pageNum +
'}';
}
}
package cn.gintone.dto;
public class DeviceInfo {
private Long id;
private String name;
private String mac; // 设备物理地址
private String ip; // 设备ip
private String port; // 端口
private Long parentId;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMac() {
return mac;
}
public void setMac(String mac) {
this.mac = mac;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public String getPort() {
return port;
}
public void setPort(String port) {
this.port = port;
}
public Long getParentId() {
return parentId;
}
public void setParentId(Long parentId) {
this.parentId = parentId;
}
@Override
public String toString() {
return "DeviceInfo{" +
"id=" + id +
", name='" + name + '\'' +
", mac='" + mac + '\'' +
", ip='" + ip + '\'' +
", port='" + port + '\'' +
", parentId=" + parentId +
'}';
}
}
package cn.gintone.dto;
public class DeviceLogInfo {
private Long timesta;
private String timestaStr;
private String roleId;
private String roleName;
private String userId; // 用户id
private String username; // 用户名
private String deviceId; // 设备id
private String deviceName; // 设备名称
private String deviceTypeId; // 设备类型id
private String deviceTypeName; // 设备类型名称
private String accessed; // 访问时间
private String type; // 日志类型(info, warning, error)
private String clientIp; // 访问端ip
private String remark; // 备注
// 查询使用
private Long beginTime;
private Long endTime;
private Integer pageSize;
private Integer pageNum;
public Long getTimesta() {
return timesta;
}
public void setTimesta(Long timesta) {
this.timesta = timesta;
}
public String getTimestaStr() {
return timestaStr;
}
public void setTimestaStr(String timestaStr) {
this.timestaStr = timestaStr;
}
public String getRoleId() {
return roleId;
}
public void setRoleId(String roleId) {
this.roleId = roleId;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getDeviceId() {
return deviceId;
}
public void setDeviceId(String deviceId) {
this.deviceId = deviceId;
}
public String getDeviceName() {
return deviceName;
}
public void setDeviceName(String deviceName) {
this.deviceName = deviceName;
}
public String getDeviceTypeId() {
return deviceTypeId;
}
public void setDeviceTypeId(String deviceTypeId) {
this.deviceTypeId = deviceTypeId;
}
public String getDeviceTypeName() {
return deviceTypeName;
}
public void setDeviceTypeName(String deviceTypeName) {
this.deviceTypeName = deviceTypeName;
}
public String getAccessed() {
return accessed;
}
public void setAccessed(String accessed) {
this.accessed = accessed;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getClientIp() {
return clientIp;
}
public void setClientIp(String clientIp) {
this.clientIp = clientIp;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public Long getBeginTime() {
return beginTime;
}
public void setBeginTime(Long beginTime) {
this.beginTime = beginTime;
}
public Long getEndTime() {
return endTime;
}
public void setEndTime(Long endTime) {
this.endTime = endTime;
}
public Integer getPageSize() {
return pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
public Integer getPageNum() {
return pageNum;
}
public void setPageNum(Integer pageNum) {
this.pageNum = pageNum;
}
@Override
public String toString() {
return "DeviceLogInfo{" +
"timesta=" + timesta +
", timestaStr='" + timestaStr + '\'' +
", roleId='" + roleId + '\'' +
", roleName='" + roleName + '\'' +
", userId='" + userId + '\'' +
", username='" + username + '\'' +
", deviceId='" + deviceId + '\'' +
", deviceName='" + deviceName + '\'' +
", deviceTypeId='" + deviceTypeId + '\'' +
", deviceTypeName='" + deviceTypeName + '\'' +
", accessed='" + accessed + '\'' +
", type='" + type + '\'' +
", clientIp='" + clientIp + '\'' +
", remark='" + remark + '\'' +
", beginTime=" + beginTime +
", endTime=" + endTime +
", pageSize=" + pageSize +
", pageNum=" + pageNum +
'}';
}
}
package cn.gintone.dto;
import java.util.List;
public class DeviceType {
private Long id;
private String name;
private List<DeviceInfo> deviceInfoList;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<DeviceInfo> getDeviceInfoList() {
return deviceInfoList;
}
public void setDeviceInfoList(List<DeviceInfo> deviceInfoList) {
this.deviceInfoList = deviceInfoList;
}
@Override
public String toString() {
return "DeviceType{" +
"id=" + id +
", name='" + name + '\'' +
", deviceInfoList=" + deviceInfoList +
'}';
}
}
package cn.gintone.entity;
import lombok.*;
import java.util.*;
import java.time.LocalDateTime;
import java.time.LocalDateTime;
import com.baomidou.mybatisplus.annotation.*;
import cn.iocoder.yudao.framework.mybatis.core.dataobject.BaseDO;
/**
* 设备连接规则 DO
*
* @author 胡懿
*/
@TableName("t_device_connet_rule")
@KeySequence("t_device_connet_rule_seq") // 用于 Oracle、PostgreSQL、Kingbase、DB2、H2 数据库的主键自增。如果是 MySQL 等数据库,可不写。
@Data
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class DeviceConnetRuleDO extends BaseDO {
/**
* id
*/
@TableId
private Long id;
/**
* 规则名称
*/
private String name;
}
\ No newline at end of file
package cn.gintone.entity;
import lombok.*;
import java.util.*;
import java.time.LocalDateTime;
import java.time.LocalDateTime;
import com.baomidou.mybatisplus.annotation.*;
import cn.iocoder.yudao.framework.mybatis.core.dataobject.BaseDO;
/**
* 设备规则配置细则 DO
*
* @author 胡懿
*/
@TableName("t_device_connet_rule_info")
@KeySequence("t_device_connet_rule_info_seq") // 用于 Oracle、PostgreSQL、Kingbase、DB2、H2 数据库的主键自增。如果是 MySQL 等数据库,可不写。
@Data
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class DeviceConnetRuleInfoDO extends BaseDO {
/**
* id
*/
@TableId
private Long id;
/**
* 规则外键
*/
private Long deviceRuleId;
/**
* 设备名称
*/
private String deviceName;
/**
* 设备id
*/
private String deviceId;
/**
* 角色
*/
private String roleId;
/**
* 角色名称
*/
private String roleName;
/**
* 用户id
*/
private String userId;
/**
* 用户名称
*/
private String userName;
}
\ No newline at end of file
package cn.gintone.service;
import cn.gintone.controller.vo.DeviceConnetRuleInfoPageReqVO;
import cn.gintone.controller.vo.DeviceConnetRuleInfoRespVO;
import cn.gintone.controller.vo.DeviceConnetRuleInfoSaveReqVO;
import cn.gintone.dto.DeviceLogInfo;
import cn.gintone.dto.DeviceType;
import cn.gintone.entity.DeviceConnetRuleInfoDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import javax.validation.*;
import java.util.List;
/**
* 设备规则配置细则 Service 接口
*
* @author 胡懿
*/
public interface DeviceConnetRuleInfoService {
/**
* 创建设备规则配置细则
*
* @param createReqVO 创建信息
* @return 编号
*/
Long createConnetRuleInfo(@Valid DeviceConnetRuleInfoSaveReqVO createReqVO);
/**
* 更新设备规则配置细则
*
* @param updateReqVO 更新信息
*/
void updateConnetRuleInfo(@Valid DeviceConnetRuleInfoSaveReqVO updateReqVO);
/**
* 删除设备规则配置细则
*
* @param id 编号
*/
void deleteConnetRuleInfo(Long id);
/**
* 获得设备规则配置细则
*
* @param id 编号
* @return 设备规则配置细则
*/
DeviceConnetRuleInfoDO getConnetRuleInfo(Long id);
/**
* 获得设备规则配置细则分页
*
* @param pageReqVO 分页查询
* @return 设备规则配置细则分页
*/
PageResult<DeviceConnetRuleInfoDO> getConnetRuleInfoPage(DeviceConnetRuleInfoPageReqVO pageReqVO);
/**
* 获取设备上级信息,并且携带设备信息返回
* @return
*/
List<DeviceType> getDeviceType();
/**
* 批量添加
* @param deviceConnetRuleInfoRespVOList
* @return
*/
Boolean saveAll(List<DeviceConnetRuleInfoRespVO> deviceConnetRuleInfoRespVOList);
void deleteByRuleId(Long ruleId);
Boolean updateAll(List<DeviceConnetRuleInfoRespVO> deviceConnetRuleInfoRespVOList);
void checkDeviceLogInfo(DeviceLogInfo deviceLogInfo);
List<DeviceConnetRuleInfoDO> getList(DeviceConnetRuleInfoPageReqVO pageReqVO);
}
\ No newline at end of file
package cn.gintone.service;
import cn.gintone.controller.vo.DeviceConnetRulePageReqVO;
import cn.gintone.controller.vo.DeviceConnetRuleSaveReqVO;
import cn.gintone.entity.DeviceConnetRuleDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import javax.validation.*;
/**
* 设备连接规则 Service 接口
*
* @author 胡懿
*/
public interface DeviceConnetRuleService {
/**
* 创建设备连接规则
*
* @param createReqVO 创建信息
* @return 编号
*/
Long createConnetRule(@Valid DeviceConnetRuleSaveReqVO createReqVO);
/**
* 更新设备连接规则
*
* @param updateReqVO 更新信息
*/
void updateConnetRule(@Valid DeviceConnetRuleSaveReqVO updateReqVO);
/**
* 删除设备连接规则
*
* @param id 编号
*/
void deleteConnetRule(Long id);
/**
* 获得设备连接规则
*
* @param id 编号
* @return 设备连接规则
*/
DeviceConnetRuleDO getConnetRule(Long id);
/**
* 获得设备连接规则分页
*
* @param pageReqVO 分页查询
* @return 设备连接规则分页
*/
PageResult<DeviceConnetRuleDO> getConnetRulePage(DeviceConnetRulePageReqVO pageReqVO);
}
\ No newline at end of file
package cn.gintone.service;
import cn.gintone.ErrorInfo;
import cn.gintone.controller.vo.DeviceConnetRulePageReqVO;
import cn.gintone.controller.vo.DeviceConnetRuleSaveReqVO;
import cn.gintone.dal.DeviceConnetRuleInfoMapper;
import cn.gintone.dal.DeviceConnetRuleMapper;
import cn.gintone.entity.DeviceConnetRuleDO;
import cn.gintone.entity.DeviceConnetRuleInfoDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
/**
* 设备连接规则 Service 实现类
*
* @author 胡懿
*/
@Service
@Validated
public class DeviceConnetRuleServiceImpl implements DeviceConnetRuleService {
@Resource
private DeviceConnetRuleMapper connetRuleMapper;
@Resource
private DeviceConnetRuleInfoMapper connetRuleInfoMapper;
@Override
public Long createConnetRule(DeviceConnetRuleSaveReqVO createReqVO) {
// 插入
DeviceConnetRuleDO connetRule = BeanUtils.toBean(createReqVO, DeviceConnetRuleDO.class);
connetRuleMapper.insert(connetRule);
// 返回
return connetRule.getId();
}
@Override
public void updateConnetRule(DeviceConnetRuleSaveReqVO updateReqVO) {
// 校验存在
validateConnetRuleExists(updateReqVO.getId());
// 更新
DeviceConnetRuleDO updateObj = BeanUtils.toBean(updateReqVO, DeviceConnetRuleDO.class);
connetRuleMapper.updateById(updateObj);
}
@Override
public void deleteConnetRule(Long id) {
// 校验存在
validateConnetRuleExists(id);
// 删除
connetRuleMapper.deleteById(id);
connetRuleInfoMapper.deleteById(new QueryWrapper<DeviceConnetRuleInfoDO>().lambda().eq(DeviceConnetRuleInfoDO::getDeviceRuleId, id));
}
private void validateConnetRuleExists(Long id) {
if (connetRuleMapper.selectById(id) == null) {
throw exception(ErrorInfo.CONNET_RULE_NOT_EXISTS);
}
}
@Override
public DeviceConnetRuleDO getConnetRule(Long id) {
return connetRuleMapper.selectById(id);
}
@Override
public PageResult<DeviceConnetRuleDO> getConnetRulePage(DeviceConnetRulePageReqVO pageReqVO) {
return connetRuleMapper.selectPage(pageReqVO);
}
}
\ No newline at end of file
...@@ -138,7 +138,7 @@ public class VisitInfoServiceImpl implements VisitInfoService { ...@@ -138,7 +138,7 @@ public class VisitInfoServiceImpl implements VisitInfoService {
if (null == userId || "".equals(userId)) { if (null == userId || "".equals(userId)) {
WebIllLogInfo webIllLogInfo = new WebIllLogInfo(); WebIllLogInfo webIllLogInfo = new WebIllLogInfo();
webIllLogInfo.setUserId(webLogInfo.getUserId()); webIllLogInfo.setUserId(webLogInfo.getUserId());
webIllLogInfo.setUserId(webLogInfo.getUsername()); webIllLogInfo.setUsername(webLogInfo.getUsername());
webIllLogInfo.setSysAbbre(webLogInfo.getSysAbbre()); webIllLogInfo.setSysAbbre(webLogInfo.getSysAbbre());
webIllLogInfo.setUrl(webLogInfo.getUrl()); webIllLogInfo.setUrl(webLogInfo.getUrl());
webIllLogInfo.setAccessed(webLogInfo.getAccessed()); webIllLogInfo.setAccessed(webLogInfo.getAccessed());
...@@ -169,7 +169,7 @@ public class VisitInfoServiceImpl implements VisitInfoService { ...@@ -169,7 +169,7 @@ public class VisitInfoServiceImpl implements VisitInfoService {
// 查询用户规则,如果配置了用户规则,则按照用户规则走 // 查询用户规则,如果配置了用户规则,则按照用户规则走
List<VisitInfoDO> visitInfoDOS = visitInfoMapper.selectList(new LambdaQueryWrapper<VisitInfoDO>() List<VisitInfoDO> visitInfoDOS = visitInfoMapper.selectList(new LambdaQueryWrapper<VisitInfoDO>()
.like(VisitInfoDO::getUrl, webLogInfo.getUrl()) .like(VisitInfoDO::getUserId, webLogInfo.getUserId())
); );
if (null != visitInfoDOS && visitInfoDOS.size() > 0) { if (null != visitInfoDOS && visitInfoDOS.size() > 0) {
isLegal = false; isLegal = false;
...@@ -185,7 +185,7 @@ public class VisitInfoServiceImpl implements VisitInfoService { ...@@ -185,7 +185,7 @@ public class VisitInfoServiceImpl implements VisitInfoService {
if (!isLegal) { if (!isLegal) {
WebIllLogInfo webIllLogInfo = new WebIllLogInfo(); WebIllLogInfo webIllLogInfo = new WebIllLogInfo();
webIllLogInfo.setUserId(webLogInfo.getUserId()); webIllLogInfo.setUserId(webLogInfo.getUserId());
webIllLogInfo.setUserId(webLogInfo.getUsername()); webIllLogInfo.setUsername(webLogInfo.getUsername());
webIllLogInfo.setSysAbbre(webLogInfo.getSysAbbre()); webIllLogInfo.setSysAbbre(webLogInfo.getSysAbbre());
webIllLogInfo.setUrl(webLogInfo.getUrl()); webIllLogInfo.setUrl(webLogInfo.getUrl());
webIllLogInfo.setAccessed(webLogInfo.getAccessed()); webIllLogInfo.setAccessed(webLogInfo.getAccessed());
......
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.gintone.dal.DeviceConnetRuleInfoMapper">
<!--
一般情况下,尽可能使用 Mapper 进行 CRUD 增删改查即可。
无法满足的场景,例如说多表关联查询,才使用 XML 编写 SQL。
代码生成器暂时只生成 Mapper XML 文件本身,更多推荐 MybatisX 快速开发插件来生成查询。
文档可见:https://www.iocoder.cn/MyBatis/x-plugins/
-->
</mapper>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.gintone.dal.DeviceConnetRuleMapper">
<!--
一般情况下,尽可能使用 Mapper 进行 CRUD 增删改查即可。
无法满足的场景,例如说多表关联查询,才使用 XML 编写 SQL。
代码生成器暂时只生成 Mapper XML 文件本身,更多推荐 MybatisX 快速开发插件来生成查询。
文档可见:https://www.iocoder.cn/MyBatis/x-plugins/
-->
</mapper>
\ No newline at end of file
...@@ -52,6 +52,8 @@ public class TokenAuthenticationFilter extends OncePerRequestFilter { ...@@ -52,6 +52,8 @@ public class TokenAuthenticationFilter extends OncePerRequestFilter {
pdToken = request.getParameter("pdToken"); pdToken = request.getParameter("pdToken");
if (StrUtil.isBlank(pdToken)) { if (StrUtil.isBlank(pdToken)) {
CommonResult<?> result = new CommonResult<>(); CommonResult<?> result = new CommonResult<>();
result.setCode(403);
result.setMsg("未登录");
ServletUtils.writeJSON(response, result); ServletUtils.writeJSON(response, result);
return; return;
} }
......
...@@ -19,8 +19,8 @@ public class BannerApplicationRunner implements ApplicationRunner { ...@@ -19,8 +19,8 @@ public class BannerApplicationRunner implements ApplicationRunner {
@Override @Override
public void run(ApplicationArguments args) { public void run(ApplicationArguments args) {
ThreadUtil.execute(() -> { ThreadUtil.execute(() -> {
ThreadUtil.sleep(1, TimeUnit.SECONDS); // 延迟 1 秒,保证输出到结尾 // ThreadUtil.sleep(1, TimeUnit.SECONDS); // 延迟 1 秒,保证输出到结尾
log.info("\n----------------------------------------------------------\n\t" + /*log.info("\n----------------------------------------------------------\n\t" +
"项目启动成功!\n\t" + "项目启动成功!\n\t" +
"接口文档: \t{} \n\t" + "接口文档: \t{} \n\t" +
"开发文档: \t{} \n\t" + "开发文档: \t{} \n\t" +
...@@ -28,10 +28,10 @@ public class BannerApplicationRunner implements ApplicationRunner { ...@@ -28,10 +28,10 @@ public class BannerApplicationRunner implements ApplicationRunner {
"----------------------------------------------------------", "----------------------------------------------------------",
"https://doc.iocoder.cn/api-doc/", "https://doc.iocoder.cn/api-doc/",
"https://doc.iocoder.cn", "https://doc.iocoder.cn",
"https://t.zsxq.com/02Yf6M7Qn"); "https://t.zsxq.com/02Yf6M7Qn");*/
// 数据报表 // 数据报表
if (isNotPresent("cn.iocoder.yudao.module.report.framework.security.config.SecurityConfiguration")) { /*if (isNotPresent("cn.iocoder.yudao.module.report.framework.security.config.SecurityConfiguration")) {
System.out.println("[报表模块 yudao-module-report - 已禁用][参考 https://doc.iocoder.cn/report/ 开启]"); System.out.println("[报表模块 yudao-module-report - 已禁用][参考 https://doc.iocoder.cn/report/ 开启]");
} }
// 工作流 // 工作流
...@@ -65,7 +65,7 @@ public class BannerApplicationRunner implements ApplicationRunner { ...@@ -65,7 +65,7 @@ public class BannerApplicationRunner implements ApplicationRunner {
// IoT 物联网 // IoT 物联网
if (isNotPresent("cn.iocoder.yudao.module.iot.framework.web.config.IotWebConfiguration")) { if (isNotPresent("cn.iocoder.yudao.module.iot.framework.web.config.IotWebConfiguration")) {
System.out.println("[IoT 物联网 yudao-module-iot - 已禁用][参考 https://doc.iocoder.cn/iot/build/ 开启]"); System.out.println("[IoT 物联网 yudao-module-iot - 已禁用][参考 https://doc.iocoder.cn/iot/build/ 开启]");
} }*/
}); });
} }
......
...@@ -107,6 +107,18 @@ ...@@ -107,6 +107,18 @@
<groupId>com.xingyuv</groupId> <groupId>com.xingyuv</groupId>
<artifactId>spring-boot-starter-captcha-plus</artifactId> <!-- 验证码,一般用于登录使用 --> <artifactId>spring-boot-starter-captcha-plus</artifactId> <!-- 验证码,一般用于登录使用 -->
</dependency> </dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- HTTPClient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
</dependencies> </dependencies>
</project> </project>
...@@ -7,7 +7,12 @@ import cn.iocoder.yudao.framework.common.enums.UserTypeEnum; ...@@ -7,7 +7,12 @@ import cn.iocoder.yudao.framework.common.enums.UserTypeEnum;
import cn.iocoder.yudao.framework.common.pojo.CommonResult; import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.security.config.SecurityProperties; import cn.iocoder.yudao.framework.security.config.SecurityProperties;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils; import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.system.controller.admin.auth.myVo.LoginRequestVo;
import cn.iocoder.yudao.module.system.controller.admin.auth.myVo.LoginUserInfo;
import cn.iocoder.yudao.module.system.controller.admin.auth.myVo.PtResult;
import cn.iocoder.yudao.module.system.controller.admin.auth.vo.*; import cn.iocoder.yudao.module.system.controller.admin.auth.vo.*;
import cn.iocoder.yudao.module.system.controller.admin.conf.PtUrlConf;
import cn.iocoder.yudao.module.system.controller.admin.myUtils.MyHttpUtils;
import cn.iocoder.yudao.module.system.convert.auth.AuthConvert; import cn.iocoder.yudao.module.system.convert.auth.AuthConvert;
import cn.iocoder.yudao.module.system.dal.dataobject.permission.MenuDO; import cn.iocoder.yudao.module.system.dal.dataobject.permission.MenuDO;
import cn.iocoder.yudao.module.system.dal.dataobject.permission.RoleDO; import cn.iocoder.yudao.module.system.dal.dataobject.permission.RoleDO;
...@@ -19,11 +24,14 @@ import cn.iocoder.yudao.module.system.service.permission.PermissionService; ...@@ -19,11 +24,14 @@ import cn.iocoder.yudao.module.system.service.permission.PermissionService;
import cn.iocoder.yudao.module.system.service.permission.RoleService; import cn.iocoder.yudao.module.system.service.permission.RoleService;
import cn.iocoder.yudao.module.system.service.social.SocialClientService; import cn.iocoder.yudao.module.system.service.social.SocialClientService;
import cn.iocoder.yudao.module.system.service.user.AdminUserService; import cn.iocoder.yudao.module.system.service.user.AdminUserService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters; import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated; import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
...@@ -31,9 +39,7 @@ import javax.annotation.Resource; ...@@ -31,9 +39,7 @@ import javax.annotation.Resource;
import javax.annotation.security.PermitAll; import javax.annotation.security.PermitAll;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid; import javax.validation.Valid;
import java.util.Collections; import java.util.*;
import java.util.List;
import java.util.Set;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success; import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertSet; import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertSet;
...@@ -46,6 +52,9 @@ import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUti ...@@ -46,6 +52,9 @@ import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUti
@Slf4j @Slf4j
public class AuthController { public class AuthController {
@Autowired
private PtUrlConf ptUrlConf;
@Resource @Resource
private AdminAuthService authService; private AdminAuthService authService;
@Resource @Resource
...@@ -180,4 +189,133 @@ public class AuthController { ...@@ -180,4 +189,133 @@ public class AuthController {
return success(authService.socialLogin(reqVO)); return success(authService.socialLogin(reqVO));
} }
@PostMapping("/ptLogin")
@PermitAll
@Operation(summary = "使用账号密码登录平台")
public PtResult<LoginUserInfo> ptLogin(HttpServletRequest request,LoginRequestVo reqVO) {
String appkey = request.getHeader("appkey");
if (null == appkey || "".equals(appkey)) {
return new PtResult<>("400", "请求头appkey缺失", null, null, null, null);
}
// JSON格式POST请求
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
headers.put("appkey", appkey);
String jsonBody = JSON.toJSONString(reqVO);
String rStr = MyHttpUtils.postJson(ptUrlConf.getLoginUrl(), headers, jsonBody);
PtResult<LoginUserInfo> result = JSON.parseObject(rStr, new TypeReference<PtResult<LoginUserInfo>>() {});
return result;
}
@GetMapping("/getUserInfoByToken")
@PermitAll
@Operation(summary = "接⼊单点登录后,⽤token换取⽤户信息")
public PtResult<LoginUserInfo> getUserInfoByToken(HttpServletRequest request) {
String appkey = request.getHeader("appkey");
String authorization = request.getHeader("Authorization");
if (null == appkey || "".equals(appkey) || null == authorization || "".equals(authorization)) {
return new PtResult<>("400", "请求头appkey或Authorization缺失", null, null, null, null);
}
// 带参数和请求头
Map<String, String> headers = new HashMap<>();
headers.put("appkey", appkey);
headers.put("Authorization", authorization);
String rStr = MyHttpUtils.get(ptUrlConf.getGetUserByToken(), headers, null);
PtResult<LoginUserInfo> result = JSON.parseObject(rStr, new TypeReference<PtResult<LoginUserInfo>>() {});
return result;
}
@GetMapping("/getUserInfoByCode")
@PermitAll
@Operation(summary = "接⼊单点登录后,⽤code换取⽤户信息")
public PtResult<LoginUserInfo> getUserInfoByCode(HttpServletRequest request, @RequestParam String code, @RequestParam String redirect_uri) {
String appkey = request.getHeader("appkey");
if (null == appkey || "".equals(appkey)) {
return new PtResult<>("400", "请求头appkey缺失", null, null, null, null);
}
// 带参数和请求头
Map<String, String> headers = new HashMap<>();
headers.put("appkey", appkey);
Map<String, Object> params = new HashMap<>();
params.put("code", code);
params.put("redirect_uri", redirect_uri);
String rStr = MyHttpUtils.get(ptUrlConf.getGetUserByCode(), headers, params);
PtResult<LoginUserInfo> result = JSON.parseObject(rStr, new TypeReference<PtResult<LoginUserInfo>>() {});
return result;
}
@GetMapping("/logOffToken")
@PermitAll
@Operation(summary = "注销token")
public PtResult<LoginUserInfo> logOffToken(HttpServletRequest request) {
String appkey = request.getHeader("appkey");
String authorization = request.getHeader("Authorization");
if (null == appkey || "".equals(appkey) || null == authorization || "".equals(authorization)) {
return new PtResult<>("400", "请求头appkey或Authorization缺失", null, null, null, null);
}
// 带参数和请求头
Map<String, String> headers = new HashMap<>();
headers.put("appkey", appkey);
headers.put("Authorization", authorization);
String rStr = MyHttpUtils.get(ptUrlConf.getLogOffToken(), headers, null);
PtResult<LoginUserInfo> result = JSON.parseObject(rStr, new TypeReference<PtResult<LoginUserInfo>>() {});
return result;
}
@PostMapping("/refToken")
@PermitAll
@Operation(summary = "刷新token")
public PtResult<LoginUserInfo> refToken(HttpServletRequest request, String refreshToken) {
String appkey = request.getHeader("appkey");
if (null == appkey || "".equals(appkey)) {
return new PtResult<>("400", "请求头appkey缺失", null, null, null, null);
}
// JSON格式POST请求
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
headers.put("appkey", appkey);
Map<String, Object> params = new HashMap<>();
params.put("refreshToken", refreshToken);
String jsonBody = JSON.toJSONString(params);
String rStr = MyHttpUtils.postJson(ptUrlConf.getRefTokenUrl(), headers, jsonBody);
PtResult<LoginUserInfo> result = JSON.parseObject(rStr, new TypeReference<PtResult<LoginUserInfo>>() {});
return result;
}
@GetMapping("/logOffTokenAndJump")
@PermitAll
@Operation(summary = "注销token并跳转指定页面")
public PtResult<LoginUserInfo> logOffTokenAndJump(HttpServletRequest request, @RequestParam String redirectUri) {
String appkey = request.getHeader("appkey");
String authorization = request.getHeader("Authorization");
if (null == appkey || "".equals(appkey) || null == authorization || "".equals(authorization)) {
return new PtResult<>("400", "请求头appkey或Authorization缺失", null, null, null, null);
}
// 带参数和请求头
Map<String, String> headers = new HashMap<>();
headers.put("appkey", appkey);
headers.put("Authorization", authorization);
String rStr = MyHttpUtils.get(ptUrlConf.getLogOffTokenAndJump() + redirectUri, headers, null);
PtResult<LoginUserInfo> result = JSON.parseObject(rStr, new TypeReference<PtResult<LoginUserInfo>>() {});
return result;
}
} }
package cn.iocoder.yudao.module.system.controller.admin.auth.myVo;
import java.util.Arrays;
public class DataAuth {
private String[] subjectIds;
private String[] regionIds;
public String[] getSubjectIds() {
return subjectIds;
}
public void setSubjectIds(String[] subjectIds) {
this.subjectIds = subjectIds;
}
public String[] getRegionIds() {
return regionIds;
}
public void setRegionIds(String[] regionIds) {
this.regionIds = regionIds;
}
@Override
public String toString() {
return "DataAuth{" +
"subjectIds=" + Arrays.toString(subjectIds) +
", regionIds=" + Arrays.toString(regionIds) +
'}';
}
}
package cn.iocoder.yudao.module.system.controller.admin.auth.myVo;
public class LoginRequestVo {
private String username;
private String password;
private String phoneNum;
private String vCode;
private int platform;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPhoneNum() {
return phoneNum;
}
public void setPhoneNum(String phoneNum) {
this.phoneNum = phoneNum;
}
public String getvCode() {
return vCode;
}
public void setvCode(String vCode) {
this.vCode = vCode;
}
public int getPlatform() {
return platform;
}
public void setPlatform(int platform) {
this.platform = platform;
}
@Override
public String toString() {
return "LoginRequestVo{" +
"username='" + username + '\'' +
", password='" + password + '\'' +
", phoneNum='" + phoneNum + '\'' +
", vCode='" + vCode + '\'' +
", platform=" + platform +
'}';
}
}
package cn.iocoder.yudao.module.system.controller.admin.auth.myVo;
public class LoginUserInfo {
private String orgName;
private String userPhoto;
private String loginId;
private String roleId;
private DataAuth dataAuth;
private String phoneNum;
private String userName;
private String accessToken;
private String userId;
private String orgId;
private Integer expiresIn;
private String orgType;
private String userState;
private String clientIp;
private String roleName;
private String imei;
private String refreshToken;
public String getOrgName() {
return orgName;
}
public void setOrgName(String orgName) {
this.orgName = orgName;
}
public String getUserPhoto() {
return userPhoto;
}
public void setUserPhoto(String userPhoto) {
this.userPhoto = userPhoto;
}
public String getLoginId() {
return loginId;
}
public void setLoginId(String loginId) {
this.loginId = loginId;
}
public String getRoleId() {
return roleId;
}
public void setRoleId(String roleId) {
this.roleId = roleId;
}
public DataAuth getDataAuth() {
return dataAuth;
}
public void setDataAuth(DataAuth dataAuth) {
this.dataAuth = dataAuth;
}
public String getPhoneNum() {
return phoneNum;
}
public void setPhoneNum(String phoneNum) {
this.phoneNum = phoneNum;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getOrgId() {
return orgId;
}
public void setOrgId(String orgId) {
this.orgId = orgId;
}
public Integer getExpiresIn() {
return expiresIn;
}
public void setExpiresIn(Integer expiresIn) {
this.expiresIn = expiresIn;
}
public String getOrgType() {
return orgType;
}
public void setOrgType(String orgType) {
this.orgType = orgType;
}
public String getUserState() {
return userState;
}
public void setUserState(String userState) {
this.userState = userState;
}
public String getClientIp() {
return clientIp;
}
public void setClientIp(String clientIp) {
this.clientIp = clientIp;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public String getImei() {
return imei;
}
public void setImei(String imei) {
this.imei = imei;
}
public String getRefreshToken() {
return refreshToken;
}
public void setRefreshToken(String refreshToken) {
this.refreshToken = refreshToken;
}
@Override
public String toString() {
return "LoginUserInfo{" +
"orgName='" + orgName + '\'' +
", userPhoto='" + userPhoto + '\'' +
", loginId='" + loginId + '\'' +
", roleId='" + roleId + '\'' +
", dataAuth=" + dataAuth +
", phoneNum='" + phoneNum + '\'' +
", userName='" + userName + '\'' +
", accessToken='" + accessToken + '\'' +
", userId='" + userId + '\'' +
", orgId='" + orgId + '\'' +
", expiresIn=" + expiresIn +
", orgType='" + orgType + '\'' +
", userState='" + userState + '\'' +
", clientIp='" + clientIp + '\'' +
", roleName='" + roleName + '\'' +
", imei='" + imei + '\'' +
", refreshToken='" + refreshToken + '\'' +
'}';
}
}
package cn.iocoder.yudao.module.system.controller.admin.auth.myVo;
public class PtResult<T> {
private String msg;
private String eventId;
private String flag;
private String code;
private T data;
private String errorStack;
public PtResult() {
}
public PtResult(String code, String msg, T data, String eventId, String flag, String errorStack) {
this.msg = msg;
this.eventId = eventId;
this.flag = flag;
this.code = code;
this.data = data;
this.errorStack = errorStack;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getEventId() {
return eventId;
}
public void setEventId(String eventId) {
this.eventId = eventId;
}
public String getFlag() {
return flag;
}
public void setFlag(String flag) {
this.flag = flag;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public String getErrorStack() {
return errorStack;
}
public void setErrorStack(String errorStack) {
this.errorStack = errorStack;
}
@Override
public String toString() {
return "PtResult{" +
"msg='" + msg + '\'' +
", eventId='" + eventId + '\'' +
", flag='" + flag + '\'' +
", code='" + code + '\'' +
", data=" + data +
", errorStack='" + errorStack + '\'' +
'}';
}
}
package cn.iocoder.yudao.module.system.controller.admin.conf;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "ptauth")
public class PtUrlConf {
private String loginUrl;
private String getUserByCode;
private String getUserByToken;
private String logOffToken;
private String refTokenUrl;
private String logOffTokenAndJump;
public String getLoginUrl() {
return loginUrl;
}
public void setLoginUrl(String loginUrl) {
this.loginUrl = loginUrl;
}
public String getGetUserByCode() {
return getUserByCode;
}
public void setGetUserByCode(String getUserByCode) {
this.getUserByCode = getUserByCode;
}
public String getGetUserByToken() {
return getUserByToken;
}
public void setGetUserByToken(String getUserByToken) {
this.getUserByToken = getUserByToken;
}
public String getLogOffToken() {
return logOffToken;
}
public void setLogOffToken(String logOffToken) {
this.logOffToken = logOffToken;
}
public String getRefTokenUrl() {
return refTokenUrl;
}
public void setRefTokenUrl(String refTokenUrl) {
this.refTokenUrl = refTokenUrl;
}
public String getLogOffTokenAndJump() {
return logOffTokenAndJump;
}
public void setLogOffTokenAndJump(String logOffTokenAndJump) {
this.logOffTokenAndJump = logOffTokenAndJump;
}
}
package cn.iocoder.yudao.module.system.controller.admin.myUtils;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.http.*;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import javax.net.ssl.SSLContext;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.Map;
/**
* HTTP请求工具类
* 支持HTTP/HTTPS协议自动判断
* 支持GET/POST/PUT/DELETE请求方法
*/
public class MyHttpUtils {
private static RestTemplate restTemplate;
static {
// 初始化RestTemplate,支持HTTPS
restTemplate = createRestTemplate();
}
/**
* 创建支持HTTPS的RestTemplate
*/
private static RestTemplate createRestTemplate() {
try {
// 信任所有证书
TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;
SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
.loadTrustMaterial(null, acceptingTrustStrategy)
.build();
SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
CloseableHttpClient httpClient = HttpClients.custom()
.setSSLSocketFactory(csf)
.build();
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);
// 设置连接和读取超时时间(单位:毫秒)
requestFactory.setConnectTimeout(5000);
requestFactory.setReadTimeout(10000);
return new RestTemplate(requestFactory);
} catch (KeyStoreException | NoSuchAlgorithmException | KeyManagementException e) {
throw new RuntimeException("创建RestTemplate失败", e);
}
}
/**
* 发送GET请求
* @param url 请求地址
* @param headers 请求头
* @param params 请求参数
* @return 响应结果
*/
public static String get(String url, Map<String, String> headers, Map<String, Object> params) {
HttpHeaders httpHeaders = new HttpHeaders();
if (headers != null) {
headers.forEach(httpHeaders::add);
}
HttpEntity<String> requestEntity = new HttpEntity<>(null, httpHeaders);
// 处理URL参数
String fullUrl = buildUrlWithParams(url, params);
ResponseEntity<String> response = restTemplate.exchange(
fullUrl, HttpMethod.GET, requestEntity, String.class);
return response.getBody();
}
/**
* 发送POST请求(JSON格式)
* @param url 请求地址
* @param headers 请求头
* @param body 请求体(JSON字符串)
* @return 响应结果
*/
public static String postJson(String url, Map<String, String> headers, String body) {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
if (headers != null) {
headers.forEach(httpHeaders::add);
}
HttpEntity<String> requestEntity = new HttpEntity<>(body, httpHeaders);
ResponseEntity<String> response = restTemplate.exchange(
url, HttpMethod.POST, requestEntity, String.class);
return response.getBody();
}
/**
* 发送POST请求(表单格式)
* @param url 请求地址
* @param headers 请求头
* @param formData 表单数据
* @return 响应结果
*/
public static String postForm(String url, Map<String, String> headers, Map<String, String> formData) {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
if (headers != null) {
headers.forEach(httpHeaders::add);
}
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
if (formData != null) {
formData.forEach(map::add);
}
HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(map, httpHeaders);
ResponseEntity<String> response = restTemplate.exchange(
url, HttpMethod.POST, requestEntity, String.class);
return response.getBody();
}
/**
* 发送PUT请求(JSON格式)
* @param url 请求地址
* @param headers 请求头
* @param body 请求体(JSON字符串)
* @return 响应结果
*/
public static String putJson(String url, Map<String, String> headers, String body) {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
if (headers != null) {
headers.forEach(httpHeaders::add);
}
HttpEntity<String> requestEntity = new HttpEntity<>(body, httpHeaders);
ResponseEntity<String> response = restTemplate.exchange(
url, HttpMethod.PUT, requestEntity, String.class);
return response.getBody();
}
/**
* 发送DELETE请求
* @param url 请求地址
* @param headers 请求头
* @param params 请求参数
* @return 响应结果
*/
public static String delete(String url, Map<String, String> headers, Map<String, Object> params) {
HttpHeaders httpHeaders = new HttpHeaders();
if (headers != null) {
headers.forEach(httpHeaders::add);
}
HttpEntity<String> requestEntity = new HttpEntity<>(null, httpHeaders);
// 处理URL参数
String fullUrl = buildUrlWithParams(url, params);
ResponseEntity<String> response = restTemplate.exchange(
fullUrl, HttpMethod.DELETE, requestEntity, String.class);
return response.getBody();
}
/**
* 构建带参数的URL
* @param url 原始URL
* @param params 参数Map
* @return 带参数的URL
*/
private static String buildUrlWithParams(String url, Map<String, Object> params) {
if (params == null || params.isEmpty()) {
return url;
}
StringBuilder sb = new StringBuilder(url);
if (!url.contains("?")) {
sb.append("?");
} else {
sb.append("&");
}
params.forEach((key, value) -> sb.append(key).append("=").append(value).append("&"));
// 删除最后一个多余的&
return sb.substring(0, sb.length() - 1);
}
}
...@@ -371,4 +371,12 @@ iotdb: ...@@ -371,4 +371,12 @@ iotdb:
password: root password: root
aes: aes:
Key: sx+htIs=6a2t8qt% Key: sx+htIs=6a2t8qt%
\ No newline at end of file
ptauth:
loginUrl: http://3h.sritcloud.com:8000/oauth/N1001
getUserByToken: http://127.0.0.1:7006/oauth/N100101
getUserByCode: http://3h.sritcloud.com:8000/oauth/N100102
logOffToken: http://3h.sritcloud.com:8000/oauth/N1007
refTokenUrl: http://3h.sritcloud.com:8000/oauth/N1010
logOffTokenAndJump: http://3h.sritcloud.com:8000/oauth/oauth/logout?redirect_uri=
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment