初始提交

This commit is contained in:
2025-09-04 18:25:00 +08:00
commit 07ffe495a7
1939 changed files with 166154 additions and 0 deletions

View File

@ -0,0 +1,21 @@
package com.mosty.lzother;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.mosty.common.base.timeconsume.EnableTimeConsume;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.scheduling.annotation.EnableScheduling;
@EnableTimeConsume
@EnableFeignClients(basePackages = "com.mosty.base.feign.service")
@EnableDiscoveryClient
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
@EnableScheduling
public class MostyLzotherApplication {
public static void main(String[] args) {
SpringApplication.run(MostyLzotherApplication.class, args);
}
}

View File

@ -0,0 +1,27 @@
package com.mosty.lzother.config;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
@Configuration
public class FeignConfig implements RequestInterceptor {
@Override
public void apply(RequestTemplate requestTemplate) {
ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if (attr != null && attr.getRequest() != null) {
HttpServletRequest request = attr.getRequest();
if (StringUtils.isNotBlank(request.getHeader("Authorization"))) {
// 添加token
requestTemplate.header("Authorization", request.getHeader("Authorization"));
}
}
}
}

View File

@ -0,0 +1,25 @@
package com.mosty.lzother.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import java.util.List;
/**
* 全局配置
* @author kevin
* @date 2022/5/25 1:56 上午
* @since 1.0.0
*/
@Data
@Configuration
@ConfigurationProperties("exclude.path-patterns")
public class GlobalYmlConfig {
/**
* swagger 静态文件的放行列表
*/
private List<String> swagger;
}

View File

@ -0,0 +1,120 @@
package com.mosty.lzother.config;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import com.mosty.common.token.SysUserInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.*;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
/**
* 单体服务拦截器
* @author kevin
* @date 2022/3/21 11:17 PM
* @since 1.0.0
*/
@Configuration
@Slf4j
public class WebMvcConfig implements WebMvcConfigurer, InitializingBean {
private static final String DEFAULT_TIME_FORMAT = "HH:mm:ss";
private static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";
private static final String DEFAULT_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
@Value("${server.servlet.context-path:/}")
private String contextPath;
@Autowired
private GlobalYmlConfig globalYmlConfig;
@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
ObjectMapper objectMapper = converter.getObjectMapper();
// 生成JSON时,将所有Long转换成String
SimpleModule simpleModule = new SimpleModule();
//日期格式化
simpleModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)));
simpleModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)));
simpleModule.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)));
simpleModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)));
simpleModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)));
simpleModule.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)));
objectMapper.registerModule(simpleModule);
// 时间格式化
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.configure(JsonGenerator.Feature.WRITE_BIGDECIMAL_AS_PLAIN, true);
objectMapper.configure(JsonGenerator.Feature.IGNORE_UNKNOWN, true);
objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
// 设置格式化内容
converter.setObjectMapper(objectMapper);
converters.add(0, converter);
}
@Override
public void afterPropertiesSet() throws Exception {
log.info("当前服务的 contextPath={}", contextPath);
log.info("当前服务的 swaggerExcludePathPatterns={}", JSON.toJSONString(globalYmlConfig.getSwagger()));
}
@Override
public void addViewControllers(ViewControllerRegistry registry) {
}
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer.defaultContentType(MediaType.APPLICATION_JSON);
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(userInfoInterceptor()).addPathPatterns("/**")
.excludePathPatterns(globalYmlConfig.getSwagger());
log.info("初始化WebMvcConfig 监控拦截器SysUserInterceptor");
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
if (!registry.hasMappingForPattern("/template/**")) {
registry.addResourceHandler("/template/**").addResourceLocations("classpath:/template/");
}
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("docs.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
WebMvcConfigurer.super.addResourceHandlers(registry);
}
@Bean
public SysUserInterceptor userInfoInterceptor() {
log.info("初始化WebMvcConfig 拦截器SysUserInterceptor");
return new SysUserInterceptor();
}
}

View File

@ -0,0 +1,76 @@
package com.mosty.lzother.controller;
import com.alibaba.fastjson.JSONObject;
import com.mosty.base.utils.OkHttpUtils;
import com.mosty.common.base.domain.BaseController;
import com.mosty.common.base.domain.ResponseResult;
import com.mosty.common.redis.service.RedisService;
import com.mosty.common.token.JwtSysUser;
import com.mosty.lzother.service.VLz110TxjService;
import com.mosty.lzother.task.SyncJqTask;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@RestController
@AllArgsConstructor
@RequestMapping(value = "lzJq")
@Api(tags = {"泸州特巡警警情110对象接口"})
public class VLz110TxjController extends BaseController {
private final VLz110TxjService vLz110TxjService;
private final RedisService redisService;
@GetMapping(value = "/syncHndJq")
@ApiOperation("同步警情110数据")
public ResponseResult<Void> syncHndJq(String time) {
this.vLz110TxjService.syncHndJq(time);
return ResponseResult.success();
}
@GetMapping(value = "/syncJqCjd")
@ApiOperation("处警警情")
public ResponseResult<Void> syncJqCjd(String time) {
this.vLz110TxjService.syncJqCjd(time);
return ResponseResult.success();
}
@GetMapping(value = "/autoTime")
@ApiOperation("启动或者停止警情定时器")
public ResponseResult<Boolean> autoTime() {
SyncJqTask.start = !SyncJqTask.start;
return ResponseResult.success(SyncJqTask.start);
}
@GetMapping(value = "/autoTimeXzjq")
@ApiOperation("启动或者停止修正警情定时器")
public ResponseResult<Boolean> autoTimeXzjq() {
SyncJqTask.jqxz = !SyncJqTask.jqxz;
return ResponseResult.success(SyncJqTask.jqxz);
}
public static void main(String[] args) {
for (int i = 0; i < 10000; i++) {
int finalI = i;
Runnable runnable = () -> {
System.out.println(finalI);
};
new Thread(runnable).start();
}
}
}

View File

@ -0,0 +1,10 @@
package com.mosty.lzother.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.mosty.base.model.entity.xinzhi.Czxx;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface CzxxMapper extends BaseMapper<Czxx> {
}

View File

@ -0,0 +1,10 @@
package com.mosty.lzother.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.mosty.base.model.entity.lzother.FKDB;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface FkdbMapper extends BaseMapper<FKDB> {
}

View File

@ -0,0 +1,10 @@
package com.mosty.lzother.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.mosty.base.model.entity.xinzhi.Jjdb;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface JjdbMapper extends BaseMapper<Jjdb> {
}

View File

@ -0,0 +1,10 @@
package com.mosty.lzother.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.mosty.base.model.entity.rh.RhMyhtWarn;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface RhMyhtWarnMapper extends BaseMapper<RhMyhtWarn> {
}

View File

@ -0,0 +1,136 @@
package com.mosty.lzother.remote;
import com.alibaba.fastjson.JSON;
import com.mosty.base.feign.service.MostyBaseFeignService;
import com.mosty.base.model.dto.base.SysDeptDTO;
import com.mosty.base.model.dto.base.SysMessageInfoInsertDto;
import com.mosty.base.model.vo.base.DeptInfoVo;
import com.mosty.common.base.domain.ResponseResult;
import com.mosty.common.base.exception.BusinessException;
import com.mosty.common.core.business.entity.vo.SysUserDeptVO;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
/**
* 调用部门信息远程适配层
*
* @author kevin
* @date 2022/7/6 10:37 上午
* @since 1.0.0
*/
@Slf4j
@Service
@AllArgsConstructor
public class TbBaseAdaptRemoteService {
/**
* 部门信息
*/
private final MostyBaseFeignService mostyBaseFeignService;
/**
* 根据部门编码查询部门信息
*
* @param orgCode 部门编码
* @return 部门信息
*/
public SysDeptDTO getDeptByOrgCode(String orgCode) {
if (StringUtils.isBlank(orgCode)) {
return null;
}
ResponseResult<SysDeptDTO> responseResult = mostyBaseFeignService.getDeptByOrgCode(orgCode);
if (responseResult == null || !responseResult.isSuccess()) {
log.error("调用部门编码查询部门信息异常 responseResult = {}", JSON.toJSONString(responseResult));
return null;
}
return responseResult.getData();
}
/**
* 根据部门deptid获取所属分县局、所属地市州
*
* @param deptid 部门编码
*/
public DeptInfoVo getOrgByDeptId(String deptid) {
if (StringUtils.isBlank(deptid)) {
return null;
}
ResponseResult<DeptInfoVo> responseResult = mostyBaseFeignService.getOrgByDeptId(deptid);
if (responseResult == null || !responseResult.isSuccess()) {
log.error("调用部门id查询部门详情信息异常 responseResult = {}", JSON.toJSONString(responseResult));
return null;
}
return responseResult.getData();
}
/**
* 根据部门deptid获取所属分县局、所属地市州
*
* @param orgcode 部门编码
*/
public DeptInfoVo getOrgByOrgcode(String orgcode) {
if (StringUtils.isBlank(orgcode)) {
return null;
}
ResponseResult<DeptInfoVo> responseResult = mostyBaseFeignService.getOrgByOrgcode(orgcode);
if (responseResult == null || !responseResult.isSuccess()) {
log.error("调用部门code查询部门详情信息异常 responseResult = {}", JSON.toJSONString(responseResult));
throw new BusinessException("调用部门code查询部门详情信息异常");
}
return responseResult.getData();
}
/**
* 获取所有的用户数据
*/
public List<SysUserDeptVO> getUserAll(String deptId) {
ResponseResult<List<SysUserDeptVO>> responseResult = mostyBaseFeignService.getUserAll(deptId);
if (responseResult == null || !responseResult.isSuccess()) {
log.error("调用部门id查询部门详情信息异常 responseResult = {}", JSON.toJSONString(responseResult));
return new ArrayList<>();
}
return responseResult.getData();
}
/**
* 获取所有的部门信息集合
*/
public List<DeptInfoVo> getDeptAll() {
ResponseResult<List<DeptInfoVo>> responseResult = mostyBaseFeignService.getDeptAll();
if (responseResult == null || !responseResult.isSuccess()) {
log.error("调用部门id查询部门详情信息异常 responseResult = {}", JSON.toJSONString(responseResult));
return new ArrayList<>();
}
return responseResult.getData();
}
/**
* 给人员发送消息
*/
public Integer sendMsg(SysMessageInfoInsertDto dto) {
ResponseResult<Integer> responseResult = mostyBaseFeignService.sendMsg(dto);
if (responseResult == null || !responseResult.isSuccess()) {
log.error("给人员发送消息失败, responseResult = {}", JSON.toJSONString(responseResult));
return 0;
}
return responseResult.getData();
}
/**
* 获取人员的部门所属
*/
public DeptInfoVo getDeptInfoByUserId(String userId) {
ResponseResult<DeptInfoVo> responseResult = mostyBaseFeignService.getDeptInfoByUserId(userId);
if (responseResult == null || !responseResult.isSuccess()) {
log.error("获取人员的部门所属失败, responseResult = {}", JSON.toJSONString(responseResult));
return null;
}
return responseResult.getData();
}
}

View File

@ -0,0 +1,107 @@
package com.mosty.lzother.remote;
import com.alibaba.fastjson.JSON;
import com.mosty.base.feign.service.MostySjzxFeignService;
import com.mosty.base.model.entity.lzother.VLz110Txj;
import com.mosty.base.model.entity.lzother.ZhjmxfXfqwXfqyGzdw;
import com.mosty.base.model.entity.sjzx.TbJq;
import com.mosty.base.model.entity.sjzx.TbJqCjdb;
import com.mosty.base.model.entity.xinzhi.GxCjdb;
import com.mosty.base.model.entity.xinzhi.Jjdb;
import com.mosty.base.model.vo.sjzx.TbJqVo;
import com.mosty.base.model.vo.xinzhi.GxAlarmAllVo;
import com.mosty.common.base.domain.ResponseResult;
import com.mosty.common.base.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
/**
* @author dw
* @since 2022/10/31
* 外部调用事件中心接口
**/
@Service
@Slf4j
public class TbSjzxAdaptRemoteService {
@Resource
private MostySjzxFeignService mostySjzxFeignService;
// 同步仁寿警情信息
public void addRsJq(TbJq dto) {
ResponseResult<Void> responseResult = this.mostySjzxFeignService.addRsJq(dto);
if (responseResult == null || !responseResult.isSuccess()) {
log.error("同步仁寿警情信息异常 responseResult = {}", JSON.toJSONString(responseResult));
throw new BusinessException("同步仁寿警情信息异常");
}
}
// 获取警情的最新的一条信息
public TbJqVo getLastJq() {
ResponseResult<TbJqVo> responseResult = this.mostySjzxFeignService.getLastJq();
if (responseResult == null || !responseResult.isSuccess()) {
log.error("获取警情的最新的一条信息异常 responseResult = {}", JSON.toJSONString(responseResult));
throw new BusinessException("获取警情的最新的一条信息异常");
}
return responseResult.getData();
}
// 获取最新一条处警单的数据
public TbJqCjdb getLastJqCjdb() {
ResponseResult<TbJqCjdb> responseResult = this.mostySjzxFeignService.getLastJqCjdb();
if (responseResult == null || !responseResult.isSuccess()) {
log.error("获取最新一条处警单的数据 异常 responseResult = {}", JSON.toJSONString(responseResult));
throw new BusinessException("获取最新一条处警单的数据异常");
}
return responseResult.getData();
}
// 添加仁寿处警单数据
public void addRsCjdb(TbJqCjdb cjdb) {
ResponseResult<TbJqCjdb> responseResult = this.mostySjzxFeignService.addRsCjdb(cjdb);
if (responseResult == null || !responseResult.isSuccess()) {
log.error("添加仁寿处警单数据 异常 responseResult = {}", JSON.toJSONString(responseResult));
throw new BusinessException("添加仁寿处警单数据异常");
}
}
// 添加泸州110警情数据
public void addLzJq(VLz110Txj lz110) {
ResponseResult<Void> responseResult = this.mostySjzxFeignService.addLzJq(lz110);
if (responseResult == null || !responseResult.isSuccess()) {
log.error("添加泸州110警情数据 异常 responseResult = {}", JSON.toJSONString(responseResult));
throw new BusinessException("添加泸州110警情数据异常");
}
}
// 添加泸州海能达警情数据
public void addLzHndJq(Jjdb jjdb) {
ResponseResult<Void> responseResult = this.mostySjzxFeignService.addLzHndJq(jjdb);
if (responseResult == null || !responseResult.isSuccess()) {
log.error("添加泸州110警情数据 异常 responseResult = {}", JSON.toJSONString(responseResult));
throw new BusinessException("添加泸州110警情数据异常");
}
}
// 查询没得经纬度的接警单编号
public List<String> selectJjdbh() {
ResponseResult<List<String>> responseResult = this.mostySjzxFeignService.selectJjdbh();
if (responseResult == null || !responseResult.isSuccess()) {
log.error("查询没得经纬度的接警单编号 异常 responseResult = {}", JSON.toJSONString(responseResult));
throw new BusinessException("查询没得经纬度的接警单编号异常");
}
return responseResult.getData();
}
//修改经纬度
public void updateJqJwd(Jjdb jjdb) {
ResponseResult<Void> responseResult = this.mostySjzxFeignService.updateJqJwd(jjdb);
if (responseResult == null || !responseResult.isSuccess()) {
log.error("添加泸州110警情数据 异常 responseResult = {}", JSON.toJSONString(responseResult));
throw new BusinessException("添加泸州110警情数据异常");
}
}
}

View File

@ -0,0 +1,78 @@
package com.mosty.lzother.remote;
import com.alibaba.fastjson.JSON;
import com.mosty.base.feign.service.MostyYjzlFeignService;
import com.mosty.base.model.dto.yjzl.GetLastYjDto;
import com.mosty.base.model.entity.lzother.TAlarmYjZl;
import com.mosty.base.model.entity.lzother.TAlarmYjgj;
import com.mosty.base.model.entity.rh.RhMyhtWarn;
import com.mosty.base.model.entity.yjzl.TbYjxx;
import com.mosty.base.model.entity.yjzl.TbZlxx;
import com.mosty.base.model.vo.lzother.TAlarmYjZlVo;
import com.mosty.base.model.vo.trs.VwAlermYjzlVo;
import com.mosty.common.base.domain.ResponseResult;
import com.mosty.common.base.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
/**
* @author dw
* @since 2022/7/23
* 外部调用公安机关要素接口
**/
@Service
@Slf4j
public class TbYjzlAdaptRemoteService {
@Resource
private MostyYjzlFeignService mostyYjzlFeignService;
// 同步拓尔思预警指令(高新)
public void addTrsZl(VwAlermYjzlVo dto) {
ResponseResult<Void> responseResult = this.mostyYjzlFeignService.addTrsZl(dto);
if (responseResult == null || !responseResult.isSuccess()) {
log.error("同步拓尔思预警指令失败 responseResult = {}", JSON.toJSONString(responseResult));
throw new BusinessException("同步拓尔思预警指令失败");
}
}
// 获取trs最新的一条指令信息
public TbZlxx getLastZlxx() {
ResponseResult<TbZlxx> responseResult = this.mostyYjzlFeignService.getLastZlxx();
if (responseResult == null || !responseResult.isSuccess()) {
log.error("获取trs最新的一条指令信息失败 responseResult = {}", JSON.toJSONString(responseResult));
throw new BusinessException("获取trs最新的一条指令信息失败");
}
return responseResult.getData();
}
// 根据条件查询最新的预警信息
public TbYjxx getLastYj(GetLastYjDto dto) {
ResponseResult<TbYjxx> responseResult = this.mostyYjzlFeignService.getLastYj(dto);
if (responseResult == null || !responseResult.isSuccess()) {
log.error("根据条件查询最新的预警信息失败 responseResult = {}", JSON.toJSONString(responseResult));
throw new BusinessException("根据条件查询最新的预警信息失败");
}
return responseResult.getData();
}
// 添加泸州拓尔思预警信息
public void addYjxx(TAlarmYjgj item) {
ResponseResult<Void> responseResult = this.mostyYjzlFeignService.addYjxx(item);
if (responseResult == null || !responseResult.isSuccess()) {
log.error("添加泸州拓尔思预警信息失败 responseResult = {}", JSON.toJSONString(responseResult));
throw new BusinessException("添加泸州拓尔思预警信息失败");
}
}
// 添加融合预警信息失败
public void addRhyj(RhMyhtWarn rhMyhtWarn) {
ResponseResult<Void> responseResult = this.mostyYjzlFeignService.saveHryj(rhMyhtWarn);
if (responseResult == null || !responseResult.isSuccess()) {
log.error("添加融合预警信息失败 responseResult = {}", JSON.toJSONString(responseResult));
throw new BusinessException("添加融合预警信息失败");
}
}
}

View File

@ -0,0 +1,69 @@
package com.mosty.lzother.remote;
import com.alibaba.fastjson.JSON;
import com.mosty.base.feign.service.MostyYszxFeignService;
import com.mosty.base.model.dto.yszx.TbYsGajgByJwdDto;
import com.mosty.base.model.dto.yszx.TbYsSxtDto;
import com.mosty.base.model.entity.lzother.ZhjmxfXfqwXfqyGzdw;
import com.mosty.base.model.entity.sjzx.TbJqCjdb;
import com.mosty.base.model.vo.yszx.TbYsGajgVo;
import com.mosty.common.base.domain.ResponseResult;
import com.mosty.common.base.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
/**
* @author dw
* @since 2022/7/23
* 外部调用公安机关要素接口
**/
@Service
@Slf4j
public class TbYsZxAdaptRemoteService {
@Resource
private MostyYszxFeignService tbYszxFeignService;
// 返回要素表中不存在的感知源
public List<String> getInfoBySbbh(List<String> ids) {
ResponseResult<List<String>> responseResult = tbYszxFeignService.getInfoBySbbh(ids);
if (responseResult == null || !responseResult.isSuccess()) {
log.error("失败 responseResult = {}", JSON.toJSONString(responseResult));
return new ArrayList<>();
}
return responseResult.getData();
}
// 添加摄像头信息
public Integer addSxt(TbYsSxtDto dto) {
ResponseResult<Integer> responseResult = tbYszxFeignService.addSxt(dto);
if (responseResult == null || !responseResult.isSuccess()) {
log.error("添加摄像头信息失败 responseResult = {}", JSON.toJSONString(responseResult));
throw new BusinessException("添加摄像头信息失败");
}
return responseResult.getData();
}
// 根据经纬度查询所在辖区
public TbYsGajgVo getGajgByJwd(TbYsGajgByJwdDto dto) {
ResponseResult<TbYsGajgVo> responseResult = tbYszxFeignService.getGajgByJwd(dto);
if (responseResult == null || !responseResult.isSuccess()) {
log.error("查询所在辖区失败 responseResult = {}", JSON.toJSONString(responseResult));
throw new BusinessException("查询所在辖区失败");
}
return responseResult.getData();
}
// 添加泸州感知源信息
public void addLzGzy(ZhjmxfXfqwXfqyGzdw dto) {
ResponseResult<Void> responseResult = this.tbYszxFeignService.addLzGzy(dto);
if (responseResult == null || !responseResult.isSuccess()) {
log.error("添加泸州感知源信息 异常 responseResult = {}", JSON.toJSONString(responseResult));
throw new BusinessException("添加泸州感知源信息异常");
}
}
}

View File

@ -0,0 +1,22 @@
package com.mosty.lzother.service;
import com.mosty.base.model.entity.xinzhi.Czxx;
import io.swagger.annotations.ApiOperation;
import java.util.List;
public interface VLz110TxjService {
@ApiOperation("海能达警情")
void syncHndJq(String time);
@ApiOperation("海能达处警警情")
void syncJqCjd(String time);
@ApiOperation("融合预警")
void rhyj(String time);
@ApiOperation("修改经纬度")
void selectJjdbh();
}

View File

@ -0,0 +1,181 @@
package com.mosty.lzother.service.impl;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mosty.base.model.dto.yjzl.GetLastYjDto;
import com.mosty.base.model.entity.lzother.FKDB;
import com.mosty.base.model.entity.rh.RhMyhtWarn;
import com.mosty.base.model.entity.sjzx.TbJqCjdb;
import com.mosty.base.model.entity.xinzhi.Czxx;
import com.mosty.base.model.entity.xinzhi.Jjdb;
import com.mosty.base.model.entity.yjzl.TbYjxx;
import com.mosty.base.model.entity.yjzl.TbYjxxDypzYjjb;
import com.mosty.base.model.vo.base.DeptInfoVo;
import com.mosty.base.model.vo.sjzx.TbJqVo;
import com.mosty.base.utils.Constant;
import com.mosty.base.utils.DateUtils;
import com.mosty.base.utils.UUIDGenerator;
import com.mosty.common.redis.service.RedisService;
import com.mosty.lzother.mapper.CzxxMapper;
import com.mosty.lzother.mapper.FkdbMapper;
import com.mosty.lzother.mapper.JjdbMapper;
import com.mosty.lzother.mapper.RhMyhtWarnMapper;
import com.mosty.lzother.remote.TbBaseAdaptRemoteService;
import com.mosty.lzother.remote.TbSjzxAdaptRemoteService;
import com.mosty.lzother.remote.TbYjzlAdaptRemoteService;
import com.mosty.lzother.service.VLz110TxjService;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Set;
@Service
@AllArgsConstructor
public class VLz110TxjServiceImpl extends ServiceImpl<JjdbMapper, Jjdb>
implements VLz110TxjService {
private final TbSjzxAdaptRemoteService tbSjzxAdaptRemoteService;
private final TbBaseAdaptRemoteService tbBaseAdaptRemoteService;
private final TbYjzlAdaptRemoteService tbYjzlAdaptRemoteService;
private final FkdbMapper fkdbMapper;
private final RhMyhtWarnMapper rhMyhtWarnMapper;
private final CzxxMapper czxxMapper;
private final RedisService redisService;
@Override
public void syncJqCjd(String time) {
// 获取最后一条数据的时间
TbJqCjdb cjd = this.tbSjzxAdaptRemoteService.getLastJqCjdb();
if (StringUtils.isBlank(time) && ObjectUtils.isNotEmpty(cjd)) {
time = DateUtils.getQueryDateString(cjd.getRksj(), "02");
} else {
time = time + " 00:00:00";
}
List<FKDB> list = this.fkdbMapper.selectList(
new LambdaQueryWrapper<FKDB>()
.first("select * from ( ")
.last(" ) a where to_char(cjsj,'yyyy-MM-dd HH24:mi:ss') > '" + time + "' order by cjsj asc")
);
if (!CollectionUtils.isEmpty(list)) {
list.forEach(item -> {
TbJqCjdb cjdb = new TbJqCjdb();
BeanUtils.copyProperties(item, cjdb);
cjdb.setId(UUIDGenerator.getUUID());
cjdb.setCjdbh(item.getFkdbh());
cjdb.setJjdbh(item.getJjdbh());
cjdb.setTzdbh(item.getPjdbh());
cjdb.setCjdwbh(item.getFkdwdm());
cjdb.setCjyxm(item.getFkyxm());
cjdb.setCjybh(item.getFkybh());
cjdb.setScfksj(item.getFksj());
cjdb.setCjsj(item.getCjsj01());
cjdb.setDdxcsj(item.getDdxcsj());
cjdb.setCjwbsj(item.getXcclwbsj());
cjdb.setFknr(item.getCjczqk());
cjdb.setCjqk(item.getCjczqk());
cjdb.setCljglx(item.getJqcljgdm());
cjdb.setCljg(item.getJqcljgsm());
cjdb.setCdry(item.getCdrc());
cjdb.setCdcl(item.getCdcc());
cjdb.setXzqh(item.getXzqhdm());
cjdb.setRksj(item.getCjsj());
cjdb.setFkdwxzb(item.getFkdwxzb());
cjdb.setFkdwyzb(item.getFkdwyzb());
DeptInfoVo dept;
if (StringUtils.isNotBlank(item.getFkdwdm())) {
dept = this.tbBaseAdaptRemoteService.getOrgByOrgcode(item.getFkdwdm());
if (dept != null) {
cjdb.setCjdwmc(dept.getDeptname());
}
}
cjdb.setXzqh(item.getXzqhdm());
cjdb.setXtSjly("1");
cjdb.setCjwbsj(item.getXcclwbsj());
cjdb.setCljg(item.getJqclztdm());
// TODO 翻译类型
cjdb.setCljglx(item.getJqcljgdm());
this.tbSjzxAdaptRemoteService.addRsCjdb(cjdb);
});
}
}
@Override
public void syncHndJq(String time) {
TbJqVo jqVo = this.tbSjzxAdaptRemoteService.getLastJq();
if (StringUtils.isBlank(time) && ObjectUtils.isNotEmpty(jqVo)) {
time = DateUtils.getQueryDateString(jqVo.getBjsj(), "02");
} else {
time = time + " 00:00:00";
}
List<Jjdb> list = this.baseMapper.selectList(
new LambdaQueryWrapper<Jjdb>()
.last(" where LENGTH(jqlbdm) > 0 and LENGTH(bjnr) > 0 and LENGTH(gxdwdm) > 0 and to_char(\"bjsj\",'yyyy-MM-dd HH24:mi:ss') > '" + time + "' order by bjsj asc")
);
if (!CollectionUtils.isEmpty(list)) {
for (Jjdb jjdb : list) {
this.tbSjzxAdaptRemoteService.addLzHndJq(jjdb);
}
}
}
@Override
@DS("rh_yj")
public void rhyj(String time) {
if (StringUtils.isEmpty(time)) {
TbYjxx lastYj = this.tbYjzlAdaptRemoteService.getLastYj(new GetLastYjDto().setYjlyid("02"));
if (ObjectUtils.isNotEmpty(lastYj)) {
time = DateUtils.getQueryDateString(lastYj.getYjSj(), "02");
}
}
long gjsj = DateUtils.strToDate(StringUtils.isNoneBlank(time) ? time : DateUtils.getSystemDateTimeString(), "02").getTime() / 1000;
List<RhMyhtWarn> rhMyhtWarns = this.rhMyhtWarnMapper.selectList(new LambdaQueryWrapper<RhMyhtWarn>().gt(RhMyhtWarn::getCreateTime, gjsj));
if (!CollectionUtils.isEmpty(rhMyhtWarns)) {
rhMyhtWarns.forEach(this.tbYjzlAdaptRemoteService::addRhyj);
}
}
public void selectJjdbh() {
List<String> jjdbh = this.tbSjzxAdaptRemoteService.selectJjdbh();
if (!CollectionUtils.isEmpty(jjdbh)) {
jjdbh.forEach(v -> {
Jjdb jjdb = this.baseMapper.selectOne(
new LambdaQueryWrapper<Jjdb>()
.eq(Jjdb::getJjdbh, v)
.isNotNull(Jjdb::getFxdwwd)
.isNotNull(Jjdb::getFxdwjd)
);
if (ObjectUtils.isNotEmpty(jjdb)) {
this.tbSjzxAdaptRemoteService.updateJqJwd(jjdb);
}
});
}
//补全警情 查询今日接警单号
String time = DateUtils.getSystemDateTimeString();
time = DateUtils.getQueryDateString(DateUtils.getNextDate(DateUtils.strToDate(time, "02"), "H", -3), "02");
List<Jjdb> list = this.baseMapper.selectList(
new LambdaQueryWrapper<Jjdb>()
.last(" where LENGTH(jqlbdm) > 0 and LENGTH(bjnr) > 0 and LENGTH(gxdwdm) > 0 and to_char(\"bjsj\",'yyyy-MM-dd HH24:mi:ss') >= '" + time + "' order by bjsj asc")
);
//判断
if (!CollectionUtils.isEmpty(list)) {
for (Jjdb jjdb : list) {
if (!redisService.hasKey(Constant.JQ + jjdb.getJjdbh())) {
this.tbSjzxAdaptRemoteService.addLzHndJq(jjdb);
}
}
}
}
}

View File

@ -0,0 +1,46 @@
package com.mosty.lzother.task;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.mosty.lzother.service.VLz110TxjService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
/**
* @author dw
* @since 2022/12/15
* 同步特巡警110警情数据
**/
@Slf4j
@Component
@AllArgsConstructor
public class SyncJqTask {
private final VLz110TxjService vLz110TxjService;
public static boolean start = true;
public static boolean jqxz = true;
@Scheduled(cron = "0/30 * * * * *")
@Transactional
public void run() {
if (start) {
log.info("同步特巡警110警情数据");
this.vLz110TxjService.syncHndJq(null);
this.vLz110TxjService.syncJqCjd(null);
log.info("同步特巡警110警情数据--->结束");
}
}
//两分钟分钟分钟修正一次经纬度
@Scheduled(cron = "0 */20 * * * ?")
@Transactional
public void selectJjdbh() {
if (jqxz) {
log.info("修改经纬度");
this.vLz110TxjService.selectJjdbh();
log.info("修改经纬度--->结束");
}
}
}

View File

@ -0,0 +1,56 @@
package com.mosty.lzother.utils;
import com.google.common.collect.Maps;
import com.mosty.base.utils.Constant;
import com.mosty.common.core.util.HttpClientUtil;
import com.mosty.common.core.util.http.HttpUtils;
import okhttp3.*;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import javax.crypto.Cipher;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
public class ArthenaTest {
/**
* 注册到网关的调用方应用所属的公钥,用于加密需要加密的参数
*/
private static final String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCOA2uL+d+0/DC8laEG9xbsfYZd9eoSJephsUdrnF4zLV+btHVCu/9MMwN0KMomgL63VjDI/w8VwL7urDhW6jG8jmVcXJezU5VetfPpFIupNEYIgdOJ2V0nMJlbYPNXfTNHDx1V7hDb4gbCOxXIda8tJHWhTk0gMls84ElqK0+G2wIDAQAB";
private static final String rsaKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDbDiY4EyIXyS94pRMS18KP4wwCwnpncNYjj6y9WjdIxyz35Cs8UCKztPeeHZi7Pqovln/4ul3yzyU/A4RYEhwVLUr8bC8HHCHkINbI0aNLvS5uq3uZd7NbgjA/F1O0XvC0whVqCBLNM0HNtkUyGDGz9r1+X2DpaYyvCxD+Mt8BOQIDAQAB";
/**
* 注册到网关的调用方应用的key,作为唯一标识符
*/
private static final String athenaAppKey = "afbbc6936d0243aea4f421fbf2b6b75d";
/**
* 注册到网关的调用方应用的名字
*/
private static final String athenaAppName = "智慧派出所";
private static final String url = "/athena/forward/93AD36543A39D2505C70A56C66D6B9FCF195D02A717E51E34E29703D5C49ACC6";
private static final String ysToken = "bc837f91-76a7-4314-b4c0-db98d62b2931";
private static String encryptData(String str, String publicKeyText) throws Exception {
byte[] decoded = Base64.getDecoder().decode(publicKeyText);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(decoded);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey pk = keyFactory.generatePublic(keySpec);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, pk);
byte[] encryptedData = cipher.doFinal(str.getBytes());
return Base64.getEncoder().encodeToString(encryptedData);
}
}

View File

@ -0,0 +1,403 @@
package com.mosty.lzother.utils;
import com.alibaba.fastjson.JSON;
import okhttp3.*;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.net.URLEncoder;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
public class OkHttpUtils {
private static volatile OkHttpClient okHttpClient = null;
private static volatile Semaphore semaphore = null;
private Map<String, String> headerMap;
private Map<String, Object> paramMap;
private String url;
private Request.Builder request;
/**
* 初始化okHttpClient并且允许https访问
*/
private OkHttpUtils() {
if (okHttpClient == null) {
synchronized (OkHttpUtils.class) {
if (okHttpClient == null) {
TrustManager[] trustManagers = buildTrustManagers();
okHttpClient = new OkHttpClient.Builder().connectTimeout(15, TimeUnit.SECONDS).writeTimeout(20, TimeUnit.SECONDS).readTimeout(20, TimeUnit.SECONDS).sslSocketFactory(createSSLSocketFactory(trustManagers), (X509TrustManager) trustManagers[0]).hostnameVerifier((hostName, session) -> true).retryOnConnectionFailure(true).build();
addHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36");
}
}
}
}
/**
* 用于异步请求时,控制访问线程数,返回结果
*
* @return
*/
private static Semaphore getSemaphoreInstance() {
//只能1个线程同时访问
synchronized (OkHttpUtils.class) {
if (semaphore == null) {
semaphore = new Semaphore(0);
}
}
return semaphore;
}
/**
* 创建OkHttpUtils
*
* @return
*/
public static OkHttpUtils builder() {
return new OkHttpUtils();
}
/**
* 添加url
*
* @param url
* @return
*/
public OkHttpUtils url(String url) {
this.url = url;
return this;
}
/**
* 添加参数
*
* @param key 参数名
* @param value 参数值
* @return
*/
public OkHttpUtils addParam(String key, Object value) {
if (paramMap == null) {
paramMap = new LinkedHashMap<>(16);
}
paramMap.put(key, value);
return this;
}
/**
* 添加请求头
*
* @param key 参数名
* @param value 参数值
* @return
*/
public OkHttpUtils addHeader(String key, String value) {
if (headerMap == null) {
headerMap = new LinkedHashMap<>(16);
}
headerMap.put(key, value);
return this;
}
/**
* 初始化get方法
*
* @return
*/
public OkHttpUtils get() {
request = new Request.Builder().get();
StringBuilder urlBuilder = new StringBuilder(url);
if (paramMap != null) {
urlBuilder.append("?");
try {
for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
urlBuilder.append(URLEncoder.encode(entry.getKey(), "utf-8")).append("=").append(URLEncoder.encode(entry.getValue().toString(), "utf-8")).append("&");
}
} catch (Exception e) {
e.printStackTrace();
}
urlBuilder.deleteCharAt(urlBuilder.length() - 1);
}
request.url(urlBuilder.toString());
return this;
}
/**
* 初始化delet方法
*
* @param isJsonPost true等于json的方式提交数据类似postman里post方法的raw
* false等于普通的表单提交
* @return
*/
public OkHttpUtils delete(boolean isJsonPost) {
RequestBody requestBody;
if (isJsonPost) {
String json = "";
if (paramMap != null) {
json = JSON.toJSONString(paramMap);
}
requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
} else {
FormBody.Builder formBody = new FormBody.Builder();
if (paramMap != null) {
paramMap.forEach((key,value) ->{
formBody.add(key, String.valueOf(value));
});
}
requestBody = formBody.build();
}
request = new Request.Builder().delete(requestBody).url(url);
return this;
}
/**
* 初始化post方法
*
* @param isJsonPost true等于json的方式提交数据类似postman里post方法的raw
* false等于普通的表单提交
* @return
*/
public OkHttpUtils post(boolean isJsonPost) {
RequestBody requestBody;
if (isJsonPost) {
String json = "";
if (paramMap != null) {
json = JSON.toJSONString(paramMap);
}
requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
} else {
FormBody.Builder formBody = new FormBody.Builder();
if (paramMap != null) {
paramMap.forEach((key,value) ->{
formBody.add(key, String.valueOf(value));
});
}
requestBody = formBody.build();
}
request = new Request.Builder().post(requestBody).url(url);
return this;
}
public OkHttpUtils post(Map<String, Object> data, boolean isJsonPost) {
RequestBody requestBody;
if (isJsonPost) {
String json = "";
if (data != null) {
json = JSON.toJSONString(data);
}
requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
} else {
FormBody.Builder formBody = new FormBody.Builder();
if (data != null) {
data.forEach((key,value) ->{
formBody.add(key, String.valueOf(value));
});
}
requestBody = formBody.build();
}
request = new Request.Builder().post(requestBody).url(url);
return this;
}
/**
* 初始化post方法
*
* @param isJsonPut true等于json的方式提交数据类似postman里post方法的raw
* false等于普通的表单提交
* @return
*/
public OkHttpUtils put(boolean isJsonPut) {
RequestBody requestBody;
if (isJsonPut) {
String json = "";
if (paramMap != null) {
json = JSON.toJSONString(paramMap);
}
requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
} else {
FormBody.Builder formBody = new FormBody.Builder();
if (paramMap != null) {
paramMap.forEach((key,value) ->{
formBody.add(key, String.valueOf(value));
});
}
requestBody = formBody.build();
}
request = new Request.Builder().put(requestBody).url(url);
return this;
}
/**
* 初始化post方法
*
* @param isJsonPut true等于json的方式提交数据类似postman里post方法的raw
* false等于普通的表单提交
* @return
*/
public OkHttpUtils put(Map<String, Object> data, boolean isJsonPut) {
RequestBody requestBody;
if (isJsonPut) {
String json = "";
if (data != null) {
json = JSON.toJSONString(data);
}
requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
} else {
FormBody.Builder formBody = new FormBody.Builder();
if (data != null) {
data.forEach((key,value) ->{
formBody.add(key, String.valueOf(value));
});
}
requestBody = formBody.build();
}
request = new Request.Builder().put(requestBody).url(url);
return this;
}
/**
* 同步请求
*
* @return
*/
public String sync() {
setHeader(request);
try {
Response response = okHttpClient.newCall(request.build()).execute();
assert response.body() != null;
System.out.println(response.headers().toString());
return response.body().string();
} catch (IOException e) {
e.printStackTrace();
return "请求失败:" + e.getMessage();
}
}
public Headers syncHeader() {
setHeader(request);
try {
Response response = okHttpClient.newCall(request.build()).execute();
System.out.println(response.headers());
return response.headers();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* 异步请求,有返回值
*/
public String async() {
StringBuilder buffer = new StringBuilder("");
setHeader(request);
okHttpClient.newCall(request.build()).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
buffer.append("请求出错:").append(e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
assert response.body() != null;
buffer.append(response.body().string());
getSemaphoreInstance().release();
}
});
try {
getSemaphoreInstance().acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
return buffer.toString();
}
/**
* 异步请求,带有接口回调
*
* @param callBack
*/
public void async(ICallBack callBack) {
setHeader(request);
okHttpClient.newCall(request.build()).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
callBack.onFailure(call, e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
assert response.body() != null;
callBack.onSuccessful(call, response.body().string());
}
});
}
/**
* 为request添加请求头
*
* @param request
*/
private void setHeader(Request.Builder request) {
if (headerMap != null) {
try {
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
request.addHeader(entry.getKey(), entry.getValue());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 生成安全套接字工厂用于https请求的证书跳过
*
* @return
*/
private static SSLSocketFactory createSSLSocketFactory(TrustManager[] trustAllCerts) {
SSLSocketFactory ssfFactory = null;
try {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new SecureRandom());
ssfFactory = sc.getSocketFactory();
} catch (Exception e) {
e.printStackTrace();
}
return ssfFactory;
}
private static TrustManager[] buildTrustManagers() {
return new TrustManager[]{new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[]{};
}
}};
}
/**
* 自定义一个接口回调
*/
public interface ICallBack {
void onSuccessful(Call call, String data);
void onFailure(Call call, String errorMsg);
}
}

View File

@ -0,0 +1,278 @@
package com.mosty.lzother.utils;
import org.apache.tomcat.util.codec.binary.Base64;
import javax.crypto.Cipher;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;
/**
* RSA加密和解密工具
*/
public class RSAUtil {
/**
* 数字签名,密钥算法
*/
private static final String RSA_KEY_ALGORITHM = "RSA";
/**
* 数字签名签名/验证算法
*/
private static final String SIGNATURE_ALGORITHM = "MD5withRSA";
/**
* RSA密钥长度RSA算法的默认密钥长度是1024密钥长度必须是64的倍数在512到65536位之间
*/
private static final int KEY_SIZE = 1024;
/**
* 生成密钥对
*/
private static Map<String, String> initKey() throws Exception {
KeyPairGenerator keygen = KeyPairGenerator.getInstance(RSA_KEY_ALGORITHM);
SecureRandom secrand = new SecureRandom();
/**
* 初始化随机产生器
*/
secrand.setSeed("initSeed".getBytes());
/**
* 初始化密钥生成器
*/
keygen.initialize(KEY_SIZE, secrand);
KeyPair keys = keygen.genKeyPair();
byte[] pub_key = keys.getPublic().getEncoded();
String publicKeyString = Base64.encodeBase64String(pub_key);
byte[] pri_key = keys.getPrivate().getEncoded();
String privateKeyString = Base64.encodeBase64String(pri_key);
Map<String, String> keyPairMap = new HashMap<>();
keyPairMap.put("publicKeyString", publicKeyString);
keyPairMap.put("privateKeyString", privateKeyString);
return keyPairMap;
}
/**
* 密钥转成字符串
*
* @param key
* @return
*/
public static String encodeBase64String(byte[] key) {
return Base64.encodeBase64String(key);
}
/**
* 密钥转成byte[]
*
* @param key
* @return
*/
public static byte[] decodeBase64(String key) {
return Base64.decodeBase64(key);
}
/**
* 公钥加密
*
* @param data 加密前的字符串
* @param publicKey 公钥
* @return 加密后的字符串
* @throws Exception
*/
public static String encryptByPubKey(String data, String publicKey) throws Exception {
byte[] pubKey = com.mosty.common.core.util.RSAUtil.decodeBase64(publicKey);
byte[] enSign = encryptByPubKey(data.getBytes(), pubKey);
return Base64.encodeBase64String(enSign);
}
/**
* 公钥加密
*
* @param data 待加密数据
* @param pubKey 公钥
* @return
* @throws Exception
*/
public static byte[] encryptByPubKey(byte[] data, byte[] pubKey) throws Exception {
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(pubKey);
KeyFactory keyFactory = KeyFactory.getInstance(RSA_KEY_ALGORITHM);
PublicKey publicKey = keyFactory.generatePublic(x509KeySpec);
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return cipher.doFinal(data);
}
/**
* 私钥加密
*
* @param data 加密前的字符串
* @param privateKey 私钥
* @return 加密后的字符串
* @throws Exception
*/
public static String encryptByPriKey(String data, String privateKey) throws Exception {
byte[] priKey = com.mosty.common.core.util.RSAUtil.decodeBase64(privateKey);
byte[] enSign = encryptByPriKey(data.getBytes(), priKey);
return Base64.encodeBase64String(enSign);
}
/**
* 私钥加密
*
* @param data 待加密的数据
* @param priKey 私钥
* @return 加密后的数据
* @throws Exception
*/
public static byte[] encryptByPriKey(byte[] data, byte[] priKey) throws Exception {
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(priKey);
KeyFactory keyFactory = KeyFactory.getInstance(RSA_KEY_ALGORITHM);
PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
return cipher.doFinal(data);
}
/**
* 公钥解密
*
* @param data 待解密的数据
* @param pubKey 公钥
* @return 解密后的数据
* @throws Exception
*/
public static byte[] decryptByPubKey(byte[] data, byte[] pubKey) throws Exception {
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(pubKey);
KeyFactory keyFactory = KeyFactory.getInstance(RSA_KEY_ALGORITHM);
PublicKey publicKey = keyFactory.generatePublic(x509KeySpec);
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, publicKey);
return cipher.doFinal(data);
}
/**
* 公钥解密
*
* @param data 解密前的字符串
* @param publicKey 公钥
* @return 解密后的字符串
* @throws Exception
*/
public static String decryptByPubKey(String data, String publicKey) throws Exception {
byte[] pubKey = com.mosty.common.core.util.RSAUtil.decodeBase64(publicKey);
byte[] design = decryptByPubKey(Base64.decodeBase64(data), pubKey);
return new String(design);
}
/**
* 私钥解密
*
* @param data 待解密的数据
* @param priKey 私钥
* @return
* @throws Exception
*/
public static byte[] decryptByPriKey(byte[] data, byte[] priKey) throws Exception {
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(priKey);
KeyFactory keyFactory = KeyFactory.getInstance(RSA_KEY_ALGORITHM);
PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return cipher.doFinal(data);
}
/**
* 私钥解密
*
* @param data 解密前的字符串
* @param privateKey 私钥
* @return 解密后的字符串
* @throws Exception
*/
public static String decryptByPriKey(String data, String privateKey) throws Exception {
byte[] priKey = com.mosty.common.core.util.RSAUtil.decodeBase64(privateKey);
byte[] design = decryptByPriKey(Base64.decodeBase64(data), priKey);
return new String(design);
}
/**
* RSA签名
*
* @param data 待签名数据
* @param priKey 私钥
* @return 签名
* @throws Exception
*/
public static String sign(byte[] data, byte[] priKey) throws Exception {
// 取得私钥
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(priKey);
KeyFactory keyFactory = KeyFactory.getInstance(RSA_KEY_ALGORITHM);
// 生成私钥
PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
// 实例化Signature
Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
// 初始化Signature
signature.initSign(privateKey);
// 更新
signature.update(data);
return Base64.encodeBase64String(signature.sign());
}
/**
* RSA校验数字签名
*
* @param data 待校验数据
* @param sign 数字签名
* @param pubKey 公钥
* @return boolean 校验成功返回true失败返回false
*/
public boolean verify(byte[] data, byte[] sign, byte[] pubKey) throws Exception {
// 实例化密钥工厂
KeyFactory keyFactory = KeyFactory.getInstance(RSA_KEY_ALGORITHM);
// 初始化公钥
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(pubKey);
// 产生公钥
PublicKey publicKey = keyFactory.generatePublic(x509KeySpec);
// 实例化Signature
Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
// 初始化Signature
signature.initVerify(publicKey);
// 更新
signature.update(data);
// 验证
return signature.verify(sign);
}
public static void main(String[] args) {
try {
Map<String, String> keyMap = initKey();
String publicKeyString = keyMap.get("publicKeyString");
String privateKeyString = keyMap.get("privateKeyString");
System.out.println("公钥:" + publicKeyString);
System.out.println("私钥:" + privateKeyString);
// 待加密数据
String data = "admin123";
// 公钥加密
String encrypt = com.mosty.common.core.util.RSAUtil.encryptByPubKey(data, publicKeyString);
// 私钥解密
String decrypt = com.mosty.common.core.util.RSAUtil.decryptByPriKey(encrypt, privateKeyString);
System.out.println("加密前:" + data);
System.out.println("加密后:" + encrypt);
System.out.println("解密后:" + decrypt);
} catch (Exception e) {
e.printStackTrace();
}
}
}